Categories
Uncategorized

Clean Code

‘Clean code’ written by Robert C. Martin is the standard book to learn how to write clean code and avoid code smells. Having not purchased the book, I read a summary on GitHub [1]. I came across a design rule that said, “prefer polymorphism to if/else or switch/case.” To be honest, I have the habit of using if/else and switch/cases, and it is my go-to method, so I decided to research this more.

I found a website called refactoring.guru [2], which seems to be a helpful resource in this area. The website has options to view the code before and after, with a problem or solution. I chose to view it in Python. The article describes how a conditional, with various actions depending on the object type, can be refactored with the creation of subclasses to match the conditional branches. The benefits of using polymorphism is to conform to the “Tell-Don’t-Ask” principle, remove duplicate code, and easier maintenance.

[1] https://gist.github.com/wojteklu/73c6914cc446146b8b533c0988cf8d29
[2] https://refactoring.guru/replace-conditional-with-polymorphism