Welcome back to the second part of advanced coding tips. If you missed the first part, feel free to catch up on it here. In this article, we will continue with the rest of the coding smells with real-life examples and how we can resolve them.
This coding smell appears when you start using primitive data-Types everywhere in your application. For example, using the integer for phone numbers and string for currency sign. If that is the case with you, take a look at the following class.
As you can see, the address here is defined as an array. This approach mainly will cause two problems, such as every time we need the address we will have to hard code it. So, why not we create a new class called Address.
Now, every time we need to add/edit an address we hit the Address class. Also, any time we need to add a new “contact us” method we hit ContactUs class. So, each class has a single responsibility.
Maybe you wonder why the switch statement is terrible. Well, it is not always bad, but if you can notice in the next example, the switch statement is big and unextractable by its nature. So when it becomes huge, you can’t divide it into smaller methods.
Just remember! if your switch statement is not big, then you can leave it. You can find an excellent example of a switch statement within the factory design pattern.
Parallel Inheritance Hierarchies
Sometimes I wonder whether the Parallel Inheritance Hierarchies is really a bad practice. Well, let’s first explain what Parallel Inheritance Hierarchies is. Then decide if it is a bad thing or not.
So, as you noticed from the image above that every time we create a new department class we also need to create a privilege class which leads us to the “Shotgun Surgery” code smell.
A Lazy Class is the one that doesn’t do so much. Do you remember this image from above?
We decided to move the address to a separate class, but we didn’t do the same with the hot-line because it would be a class with 3 lines only. So, whenever you found these lazy classes, you should eliminate them.
Temporary Fields code smell happens when you have a class instance variables that have been used only sometimes. Have a look at the next example; you will notice that $name and $contactDetails are only used in the notify() method.
So why not pass them as a method parameters.