Wednesday, May 28, 2014

[Programming] #3: How NOT to use default arguments

A friend of mine described this code he saw the other day to me in the legacy code of the game he is working in that involves default arguments in functions. I imagine that it looks something like this (it's in PHP):

//PHP!!
bool someFunc( $a = -1, $b = -1 ) {
    // Defensive programming!
    if ( $a == -1 ) {
        return false;
    }

    // More defensive programming!
    if ( $b == -1 ) {
        return false;
    }

    return true;
}
It's funny because you can tell the innocent thought process of the programmer who wrote this. It's simple: preset default unwanted values and reject them if they are not set. That way you can ensure that they are set by the invoker!

Except that it is much more robust and safer if the programmer would just remove the default arguments, together with the defensive programming lines of code.

I wonder if that programmer got stuck while dealing with a language without default argument support?

No comments:

Post a Comment