Have you ever heard about Bad Smell? This week we will focus on this topic in our blog with a series of posts talking about key insights related to this subject, that is so important in the life of a Developer. Did you know that a code has its health? Yes, it has! Do you know how to check if it is healthy?
If you have no idea what SOLID or Clean Code is, I will leave in the reference section the links to the posts that I wrote about SOLID principles and one about Clean Code from balta-io blog.
There are some factors, such as increasingly tight deadlines, abstract documentation, and even technical deficiency, that usually make us create unhealthy codes and that do not correspond to what was requested or is not the best solution for that problem.
To find out if your code is healthy, you don’t need to watch House or Greys Anatomy. When it isn’t healthy, we start to find several symptoms that the code is not well, we identify the famous “Bad Smell” or “Code Smell”. So, get ready, sanitize your hands, put on your mask and we will analyse our codes.
According to Martin Fowler, a Bad Smell happens when the code is poorly designed or when the implementation chosen was wrong. These symptoms help us check some problems in the code, such as:
First, we will use the principle of minimal surprise where we follow the rules below:
There are some categories that we use to know what types of Bad Smell we are facing. These categories are:
In this post, we will focus on the Bloaters category.
Bloater is a category that is found whenever a code grows unnecessarily frequently. This usually impacts the code speed and processing.
The prevention for this category is to create lean and focused codes.
A Bad Smell that can be classified as a Bloater is the Primitive Obsession.
It occurs when many primitive types are used instead of "abstraction" structures. It can make the code less readable, and unintentional, and this makes reading it extremely difficult, resulting in duplication, as data is not organized in a single structure.
In the image above we have a class called PrimitiveObsession, that contains several fields as primitive types. When we build classes containing several primitive types, usually, at first glance, they don't seem very organized, looking like a totally procedural and expressionless code. As the constructor contains several parameters, it is not so readable.
So, let's refactor that class and solve the problems.
The first thing would be to use Object Orientation to create an abstraction that represents an object that aggregates fields making sense for the context. In our case we have the fields:
So, we create a topic called Address that will contain all these properties.
And after this “refactor”, the class looks like this:
Note that the visibility of the class is elegant, much leaner and simpler to identify the content.
I hope you enjoyed it! Next post, we will talk about the Bad Smell of the Obfuscates Family.
May the force be with you!