Advanced Coding Skills
Advanced Coding Skills
Consignas:
Good developers are defined by the quality of their codes. In the software industry,
writing good code means saving the money that may be invested in testing,
updating, extending or fixing bugs. In this article, I will show you real-life examples of
some techniques and ideas that will help you to clean up your legacy code and refactor
it to make it more robust and modular. These techniques will not only help you to
refactor your old code but will give you great ideas as to how to write clean code from
now on.
Refactoring refers to techniques and steps that help you to write clean code. This is
important for other developers, who then will be able to read, extend and reuse the code
without the need to edit much. Some examples of refactoring a legacy code and making it
better will be shown next.
● Never refactor a production code that does not have unit tests
My first advice is to not ever start refactoring a legacy code, which does not have proper
unit tests. I guess the reason is obvious: You will end up with broken functionalities that
are difficult to fix because you won’t be able to figure out what’s broken. Therefore, if you
need to refactor it, start with testing it first. Make sure the part you are going to refactor is
covered by the tests.
Take a look at the next picture. This is a real project for a hotel management system that I
found on GitHub. This is a real open source project so the closed source can be worse.
As you can see in this method, there are three levels marked in red. The deepest point
should be the nested if/else statement inside the first if condition. Usually, the deepest
point is focusing on a single logic which makes it easier to refactor.
The next deepest point will be fetching the post data and loading the views. Now, take a
look at the method add() after refactoring the other parts. It is much cleaner, readable and
testable.
Analista de Sistemas ORT Inglés Técnico
In the next example, you notice if rooms are more than 250, it returns an error message.
In this case, 250 is considered a magic number. If you’re not the developer who wrote it, it
will be hard to figure out what it represents.
In order to refactor this method, we can figure out that 250 is the maximum number of
rooms. Therefore, instead of hardcoding it, we can extract it to variable
$maxAvailableRooms. Now, it is more understandable to other developers.