GoogleTechTalks – The Clean Code Talks
The Clean Code Talks — Inheritance, Polymorphism, & Testing
A little old one, but it’s a nice coding-technique presentation from the father of AngularJS. It talks about using polymorphism instead of “if statements” for writing codes which are easier to read/test/maintain.
The philosophy behind the presentation seems like the origin of the AngularJS concepts. The modularity and declarative definition of behaviors, and also dependency injection for separating out business logics and object factories. Nice.
The good candidates for applying polymorphism instead of “if statements” are the followings.
- an object behaves differently based on its state.
- you have to check the same conditions in multiple places.
The example used here is modeling “1 + 2 * 3” calculation tree structure (figure in 7:52). The simple design is to create a “Node” class which contains “operators” and “values” along with the child left/right nodes (figure in 10:10), but it results in redundant representation, since the “operators” and “values” only requires some of them (figure in 11:10). Therefore, not required fields need to be nullified or filled with an invalid value like -1.
In such situation, applying polymorphism (figure in 14:26) helps simplifying the code. Separating out “ValueNode” and “OpNode” from “Node”, then creating “AdditionNode” and “MultiplicationNode” from the “OpNode” removes the redundancy of fields.
As a result, each class have a specific role, and it doesn’t require “if” branching. Also, new behavior can be added without modifying the original code (ex. adding operator). Each behavior is separated and easy to understand and easy to test.