2014-07-03

Avoiding conditionals to improve code

Last year Michael Feathers wrote an article about unconditional programming which in essence is just an idea to avoid any type of control structures since control structures tend to make code harder to understand. This is not a new idea.

I think the idea of having no conditions in your program and rather rely on other patters like polymorphism to achieve the same things has been floating around for quite some time. I know some people who have tried this and the verdict is that "it is really hard to write a program without ant conditionals, but once you manage to do it the code is really easy to understand and test". The only big caveat I've heard of is that you tend to end up with a lot more and smaller classes than you usually do. And some people tend to believe that is a huge problem. I just think it is different.

A partial variant of unconditional programming is actually rule 2 of object calisthenics; do not use the else key word. A rule put in place to force you to think about alternatives. But this does not mean we should throw conditionals out the door!

Object calisthenics is for practicing skills, not for your day job. Michael Feathers also states conditionals are in general needed, but unconditional programming is an interesting idea. And I have not yet met anybody who thought conditionals could be abandoned 100%. At the very least you need simple mathematical functions such as max and a way to create the right class.

I think the key takeaway here is that reducing the number of conditionals in your code in favor of other patters is a good idea for understandability and maintainability in general. Your business logic is probably the most important piece of your code so if you can push your conditionals out of that layer then your code is more likely to be more robust.

No comments:

Post a Comment