Clean code is something talked about a great deal in software development circles. There are two main books that people will site when they discuss clean code. The first one called Clean Code, A Handbook of Agile Software Crafstmanship by Robert C. Martin and Refactoring, Improving the design of existing code by Martin Fowler. These are great books and I will talk more about them at a later date. Today I would like to discuss one of the The Clean Code Talks that Google has put out that is led by Misko Hevery.
“The Clean Code Talks — Inheritance, Polymorphism, & Testing” is the name of this talk, it is one of a series that Google has online. Misko starts off with a interesting and provocative statement, “Most ifs can be replaced by Polymorphism.” I know I have used a lot of if statements in my daily coding. So at first I wasn’t sure if this was possible. The reason why we would want to do this is that code without ifs is:
- Easier to read
- Easier to test
- Easier to maintain
He then suggests we should use polymorphism when objects should behave differently based on the state or we check the same condition multiple times. The place where he confirms that you must use conditionals is when we need to compare primitives objects. To help your code become if free we should never return nulls in our code, we should instead return a Null Object or an empty list. From my experience I can see this being very helpful as I remember many bugs that required adding a null check to fix. Along this line we should also never return an error code but throw an exception.
Now we should go ahead and create a lot of sub-classes right? As ESPN Gameday analyst Lee Corso would say, “Not so fast my friend!” Misko points out we need to walk a fine line and avoid “Rampant Subclassing”, this can create a unmanageable hierarchy.
State Based Behavior
When we have a conditional that chooses different behavior based on the object we should consider using polymorphism. We can make the original method abstract and then take each portion of the conditional to the overriding method of the subclass. This is from Martin Fowler’s book called Refactoring. Misko talks through an example of this in code where there is a switch statement where we replace the switch statement with a sub-classes of types of birds. The next segment he goes through an example that models a mathematical operation.
In summary of this section he recaps that polymorphic solutions are usually better because, new behavior could be added without having the source code and each operation is broken into a separate file that is easier to test or understand. We should try to replace conditionals with polymorphism. A switch statement should be reworked with sub-classes. If statements should also be replaced but, if it is a primitive comparison it can’t be replaced.
If you enjoyed this please share this and don’t forget to subscribe to our newsletter.