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.

  1. an object behaves differently based on its state.
  2. 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.


Posted on June 7, 2013, in JavaScript, Web. Bookmark the permalink. 1 Comment.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: