Code refactoring

Refactoring is the process of changing a software system in such a way that it does not alter the behavior of the code yet improves its structure. It is a disciplined way to clean up code. In essence, when you refactor you are improving the design of the code after it has been written.

Code smells are a set of common signs which indicate that the written code is probably not good enough and is in need of refactoring. Redundant comments are one of many documented code smells. A comment is redundant if it describes something that adequately describes itself. An example is a Javadoc that says nothing more than (or less than) the function signature.

i++; // increment i
/**
 * @param sellRequest
 * @return
 * @throws ManagedComponentException
 */
public SellResponse beginSellItem(SellRequest sellRequest)
throws ManagedComponentException {
   // ... 
}

Comments should say things that the code cannot say for itself, i.e. intentions or why something is the way it is.

Refactoring techniques: Decompose conditional

When code consists of a complicated conditional (if-then-else) statement, usually refactoring should be applied. One solution is to decompose the complicated parts of the conditional into separate methods: the condition, then and else. By extracting conditional code to methods named, so that the intention of that block of code is specified, you make life easier for the person who will be maintaining the code later.

if (date.before (SUMMER_START) || date.after(SUMMER_END)) {
    charge = quantity * _winterRate + _winterServiceCharge;
} else {
    charge = quantity * _summerRate;
}

if (isSummer(date)) {
charge = summerCharge(quantity);
} else {
charge = winterCharge(quantity);
}

“Code Refactoring & Decompose Conditional Technique” Tech Bite was brought to you by Edin Begić, Junior Software Engineer at Atlantbh. 

Tech Bites are tips, tricks, snippets or explanations about various programming technologies and paradigms, which can help engineers with their everyday job.

oban
Software DevelopmentTech Bites
February 23, 2024

Background Jobs in Elixir – Oban

When and why do we need background jobs? Nowadays, background job processing is indispensable in the world of web development. The need for background jobs stems from the fact that synchronous execution of time-consuming and resource-intensive tasks would heavily impact an application's  performance and user experience.  Even though Elixir is…
selenium
QA/Test AutomationTech Bites
December 22, 2023

Selenium Grid 4 with Docker

Introduction When talking about automation testing, one of the first things that comes to mind is Selenium. Selenium is a free, open-source automated testing framework used to validate web applications across different browsers and platforms. It is not just a single tool but a suite of software. Every component of…

Want to discuss this in relation to your project? Get in touch:

Leave a Reply