Return Values, Exceptions And Special Cases


Some C++ books will recommend against passing parameters as default types, for instance, if you have a function:

Code:
void NetConnect( const char * address, int port, int flags )

Calling code looks like:

Code:
NetConnect( "localhost", 21, 0x21 )

Then we can get into dangerous ground if someone forgets which parameter is port, and which is flags. But instead you can specify the function prototype as:

Code:
void NetConnect( Address address, Port port, Flags flags )

Where Address/Port/Flags are classes that just contain the original type as member data, a constructor that initialises the member data, and a cast operator to get back to the original data. Then calling code can look like:

Code:
NetConnect( Address( "localhost" ), Port( 21 ), Flags( 0x21 ) );

Which makes it a lot more clear exactly which argument does what. You can setup a macro that allows you to define these extra classes something along the lines of:

Code:
SpecialMacro( Address, int );
SpecialMacro( Port, int );

Personally, I find the above a bit over the top in C++, but I have certainly worked with other peoples code which uses a lot of the above, along with decent scoping (be it class based or namespace based) to avoid conflicts/pollution.

This can at least help with the issue of having to validate incoming parameters to make sure they are suitable - I appreciate it doesn't fix all the potential problems, but I can see why some people like it. Certainly I'm quite a big fan of named parameters in Python, which means function calls can look like:

Code:
MyFunction(
  Width  = 64,
  Height = 32,
  Accel  = 1.2
)

But I'm not sure I'd be a fan of it if it required the extra gubbins C++ requires.

As I find it makes it a lot easier to understand what code is doing at a glance, rather than having to constantly be looking up method signatures and so on.

Steve

EDIT : Also, I wanted to mention, I have worked on many pieces of software, where doing debug checks is certainly not viable for the final product, it can cause a lot of code bloat, as well as slowing things down while the checks are performed (by debug checks I typically mean asserts).
 
Back
Top