Sunday, September 28, 2008

Program Defensively

There's nothing worse than running an optimized build, where the symbols are gone and the locals wrong, because an edge condition happened. And yes, we can play tough and decide that such cases are so rare, we don't put a check for it.

And by Murphy's law, nothing happens the first six months; then you get a crash a couple of days before submitting to your publisher, and it will take the best guys in your team to track it. And very probably, a very simple edge condition will have caused this.

For example:
int * FunctionThatNeverFails( int nSlots, int * pOriginal )
{
int * pNewData = new int[ nSlots ];
memcpy( pNewData, pOriginal, nSlots * sizeof( int ) );
return pNewData;
}

A lot of things can go wrong here. So let's look at the defensive function:

int * FunctionThatNeverFails( int nSlots, int * pOriginal )
{
ASSERT( nSlots > 0 );
ASSERT( pOriginal != NULL );
int * pNewData = new int[ nSlots ];
ASSERT( pNewData != NULL );
memcpy( pNewData, pOriginal, nSlots * sizeof( int ) );
return pNewData;
}

Too much typing? Overkill?
Yes, but it will trap a bunch of things we are sometimes lazy (or just too confident) won't happen at all.

1 comment:

Edmundo. said...

It reminds me a debate we had log time ago at school: who is responsible for the call to a funcition / method in a library?

Some said it was responsibility for the library programmer to validate all the inputs and make sure everything on the function / method to work properly.

Library programmers said it was responsability for the users of the library to call it properly.

Sure, this was a zillion-years before the internet and all the jungle out there of hackers / crackers and so on, and we were limited to single computers or at most on LANs and there were no concern about computer security other than some viruses.

Now it is clear that all has to be validated and sometimes double and triple-checked just to make sure everithing is going to work as expected.

And thinking out loud, this shouldn't be a problem with modern text editors where you can create macros to do the boring extra typing you wouldn't want to do ;).