5.22.2008

Death Of A Thousand Default Values

I'm sure we've all seen this:



class MyVideo
{...
int loadVideo(string name, bool loop = false, bool fullscreen = false,
int ioBufferStart = 256, int width = 10, int height = 20, int xLoc = 10, int yLoc = 20);

};



But, it should really look like this:



class MyVideo
{...

class LoadParms
{
public:
   string mName;
   int mIOBufferStart;
   int mWidth;
   int mHeight;
   int mXLoc;
   int mYLoc;
   bool mLoop;
   bool mFullscreen;

   LoadParms():
    string name(""),
    loop(false),
    fullscreen(false),
    ioBufferStart(256),
    width(10),
    height(20),
    xLoc(10),
    yLoc(20)
   {};
};
   int loadVideo(LoadParms lp);

};



The reasoning lies in the fact that default values will, eventually, screw you. Period. If not you directly, it'll screw someone else, using your code. If it hasn't happened to you yet, it will. Having a class that contains all the loading information keeps the actual load function nice & tidy, as well as it allows you to generate default values w/o allowing other users to pass in wrong values to wrong items when they want to set just one variable.

You shouldn't be worried about creating a new structure for this data. Most of the load options would have copied the data to the local version anyway, so you're just temporarily moving some information onto the stack.


~Main

0 comments: