Wednesday, December 28, 2011

if (fred)

if (fred) {
...
}

Cryptic?

How much better is

if (preloadCaches()){
}

You would probably guess that this returns false for an error. An exception might be a better way of handling this.


So what about

if (reloadCaches()){
}

Any guesses when this would return true or false? maybe true if this is the first time it's loaded the cache? or perhaps true if anything changed? or perhaps true if there were no errors?


If a function name does not give away the result, don't return a bool.
  • bool isValidId() 
  • bool isEnabled()
  • bool isOverDrawn()
The above are just fine.
  • bool setAccountOverdraftLimit()
  • bool preInitialisationCheck()
  • bool fred()
These all require me to go looking into the function to see what it is all about.


I may be looking for a bug in the account balance, but when I see the code.

if (setAccountOverdraftLimit(10000)){
   ....
}


Then I don't know if I'm going into the if() or not. Now I need to read setAccountOverdraftLimit at the outset. Every time I come across this ambiguity I am forced to read more and more code which in all probability has no relation to the bug.

And wait for the fun that happens when someone overrides setAccountOverdraftLimit() and one instance returns true/false for the limit has been set/not set, and the other instance returns true/false for the limit has been increased compared to the previous limit.

No comments:

Post a Comment