Refactoring Ideas [4]: Get the role without casting

Bill Tsapalos
3 min readOct 15, 2022

--

Type Casting is the way to change an object from one type into another. It is good to verify (instanceOf) that the object you are going to handle fits to your requirements for the next steps.
This way you can be sure that you will catch the error and inform the user in a polite way and your application is not going to crash into his/her face.

Photo by Ludomił Sawicki on Unsplash

Code smell with if statements and type casting

Let’s take a look in a simple code snippet like the one below:

This code snippet describes the situation of having various types of vehicles and calculating the tax based on the engine size. It is a straight forward implementation and it is easy to read and maintain.

We should not have anything to discuss but what about the expansion of this code? Would it be easy to write a new feature?
What if we want to calculate tax for electric cars? We should create a new Car class and update this if statement over there.
What if we would like to add a new tax calculation logic? We should create a new calculateTax method with different logic but almost the same implementation.

Is there anything we can do to improve the future states of this code? Of course it is, refactoring

Refactoring Process

In the Main class we have a method which handles objects which are not members of this class. This rings a bell that we should get this method out of there!

When we have no imagination of what the new class should be named, just name it after the method name. I wish I was the creator of this simple and clever idea but I am not! So, thank you Kent Beck for your Method Object idea! We are going to create the TaxCalculator class so easily!

As always a good refactoring cannot be done in a single step! After all, Rome wasn’t built in a day!

We should increase reusability and this can be done through interfaces. Let’s introduce 2 new interfaces in our code:

Everything that could be taxes should implement the Taxation interface and anything that could calculate tax should implement TaxCalculator interface.

If you are deep into the object oriented world, TaxCalculator will probably remind you the Visitor Pattern.
If you are into Android world TaxCalculator will remind you some part of the dependency injection process using Dagger2.
Both of the above are correct!

Let’s see what we have achieved so far:

This code seems to be much more lengthy but imagine how easy it is to add a new Vehicle or a new tax calculator for a different country.

Rules

When shall I refactor? How am I going to understand? That’s why I made up the 2 rules!

  • Keep strong cohesion between the data handled by an class and its enclosing methods. Otherwise move your method to a new object.
  • When you are going to use if with casting consider using Visitor pattern.

More

Do you want to see more refactoring/design ideas? Here is the table of contents.

--

--