Friday, September 26, 2008

Returning the comparison results

Over the last couple weeks I have been looking at some of my old code as well as going over other peoples projects. A personal pet peeve of mine keeps popping up in the code the worst part is when I started out programming I did the same thing. It’s when you do a Boolean comparison then return true or false rather than just returning the results of the comparison. Below is an example of what I am talking about.

   21 if (foo == otherFoo)
   22 {
   23     return true;
   24 }
   25 else
   26 {
   27     return false;
   28 }


The above is an example of what not to do. There have been many times in my life where I have done this not thinking about what I was doing. I am glad to say that time has passed. I have talked to others about it and they say they do it because it is more explicit and easier to read. I have a hard time agreeing with this stance how can the above be easier to read then the following.


   21 return foo == otherFoo;  


It’s short simple and easy to read.

2 comments:

Anonymous said...

Good thinking. This actually reduces the amount of assembly to 2 assembly lines. Compare and return. Nice!

James and Crystal said...

That is seks and my biggest pet peeve of any dev I've ever met. Anytime a boolean state can be inferred is always preferable as it also reduces the amount of error that can happen and as Trixtur says it does reduce code. Great phoast m8.