I just came from Simple Design and Testing Conference. In one of the session we were talking about evil keywords in programming languages. Corey Haines, who proposed the subject, was convinced that if
statement is absolute evil. His alternative was to create functions with predicates. Can you please explain to me why if
is evil.
I understand that you can write very ugly code abusing if
. But I don't believe that it's that bad.
IMO: I suspect he was trying to provoke a debate and make people think about the misuse of 'if'. No one would seriously suggest such a fundamental construction of programming syntax was to be completely avoided would they?
It probably comes down to a desire to keep code cyclomatic complexity down, and to reduce the number of branch points in a function. If a function is simple to decompose into a number of smaller functions, each of which can be tested, you can reduce the complexity and make code more easily testable.
A good quote from Code Complete:
IOW, keep it simple. If the readability of your application will be enhanced by using a predicate in a particular area, use it. Otherwise, use the 'if' and move on.
I think it depends on what you're doing to be honest.
If you have a simple
if..else
statement, why use apredicate
?If you can, use a
switch
for largerif
replacements, and then if the option to use a predicate for large operations (where it makes sense, otherwise your code will be a nightmare to maintain), use it.This guy seems to have been a bit pedantic for my liking. Replacing all
if
's with Predicates is just crazy talk.if
is not evil(I also hold that assigning morality to code-writing practices is asinine...).Mr. Haines is being silly and should be laughed at.
If is not evil! Consider ...
Boring, eh? Now with an added if ...
... your code creation productivity (measured in LOC) is doubled.
Also code readability has improved much, for now you can see in the blink of an eye what the result is when both argument are zero. You couldn't do that in the code above, could you?
Moreover you supported the testteam for they now can push their code coverage test tools use up more to the limits.
Furthermore the code now is better prepared for future enhancements. Let's guess, for example, the sum should be zero if one of the arguments is zero (don't laugh and don't blame me, silly customer requirements, you know, and the customer is always right). Because of the if in the first place only a slight code change is needed.
How much more code change would have been needed if you hadn't invented the if right from the start.
Thankfulness will be yours on all sides.
Conclusion: There's never enough if's.
There you go. To.