Sunday, February 19, 2017

Substituting polymorphism for if/else or switch/case - Example #1 - Shapes

This is Example #1 of the series of examples I'm going to give on "Substituting polymorphism for if/else or switch/case statements".


You have a new task


It's your first day at work. You are very excited to be involved in a real-world project.

Your team lead tried to explain to you the purpose of the project you are involved in.
"Here at Hugis Inc., we strive to be the best drawer of shapes."
After an hour, he gave you your first task.

You have to implement this method:

(Because I used C# for many years, I'm going to display C# in these posts. But I will also write these examples in Python and maybe other OO languages in the future. You can view them here.)

The codebase of the project you are involved in already have these classes:
  • a base Shape class,
  • classes for Circle, Square, and Triangle that derives from the Shape class.


The Evil code

This task is so easy!!! (you say to yourself)
You then started typing on the keyboard. Click! Click! Click!



Then after a few hours of hard work, you pushed your code to the repository, waiting for your team lead's comments.

The Good Code


Your team lead's comment came in.
"Good job!"
Wow!
"But there is a better way of doing this.

"We want to put the function drawCircle() inside the Circle class, and the function drawSquare() inside the Square class, because we want to have an easy access them anywhere in the system.

"Come over here. I'm going to show you how I will do the changes."
You then went to his table and watched him refactor your code.
"Because we want to be able to draw each Shape that we have, we will create an abstract method named draw() in our base Shape class.

     abstract public void Draw();

"Do you know what an abstract method is?"
No.
"An abstract method is a method definition that has no implementation -- like the getArea() method in the Shape class.

"Notice that getArea() does not have an implementation inside the Shape class. But any class that inherits from the Shape class is required to provide an implementation for getArea()"
Ahh! The Shape class did not provide an implementation for getArea() because different shapes has different formulas for getting the area! Great!

Now I understand what you want me to do with drawing shapes.

Let me be the one to refactor my code, please. I think I already know what to do.
"Ok! Go Ahead!"
You went back to your machine and started refactoring your code.

(Please go to the GitHub repository to view the complete refactoring.)



MTGOTB, TCOTU, BGWML

No comments:

Post a Comment