February 01, 2004

Error patterns: read-only "last"

In my programming experience, I find that there are some common errors that I make quite often. Maybe it'll be easier for me (or even for someone else) to get rid of them if I describe them in my blog.

The error I just made has to do with a common optimization: when a function is called with some parameter, do not do anything if it's equal to the parameter of the last call to that function. The error is forgetting to actually store the last selected value.

public void SetCurrentSomething( IResource something)
{
    if ( something == _lastSomething )
        return;

    // do stuff
    // forget to actually set _lastSomething
}

Posted by Dmitry Jemerov at February 1, 2004 01:47 PM | TrackBack
Comments

What about replacing the 'if (...) {}' block with an 'if (...) {} else {}' one? ;)

Posted by: Richard Chuo at February 5, 2004 10:49 AM

Rightly or wrongly, I strive to make methods have a single point of return; I also try to make most of the code within the method exexcute most of the time (i.e. make conditional blocks as small as possible even at the expense of some inefficiency). e.g.

public void setSomething(Resource something)
{
if (something != lastSomething)
{
// do stuff
}
lastSomething = something; // on every call
}

Posted by: Richie McMahon at April 30, 2004 01:50 AM

Your experience is very usefull. It can also use that check that parameter was changed.

Posted by: dast@irez.com at May 10, 2004 03:55 PM
Post a comment









Remember personal info?