Friday, May 2, 2008

Unnecessary Iffage

A friend of mine showed me an example of the kind of bad code he finds every day where he works:

image

There are a lot of things wrong with the example above.  Le'ts pick it apart and simplify.

1. This line is unnecessary:
image 

You could just use SomeBooleanFunction in place of someBooleanValue in the example above, like so:

image

2. " = True" is unnecessary.
The function already returns a boolean value.  Get rid of it:

image

3. anotherBooleanValue is also unnecessary. We could do away with it and return the value immediately from the If statement, like so:
image
 
4. In fact, almost all of it is unnecessary:
image
 

How does this happen?

Why didn't the programmer just use the existing SomeBooleanFunction() instead of creating a new method that does the exact same thing?  I bet I know.

I suspect the original programmer didn't know that SomeBooleanFunction() existed until after he'd already duplicated the same logic in MyBooleanFunction().  Once he found out that SomeBooleanFunction() was there, he wanted to use it, but didn't want to change all the code that was already using his new MyBooleanFunction().

A simple find/replace could have solved his problem, but he may have been afraid to change too much. That's not a good excuse, I know. I'm just sayin'.

No comments: