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.

Decorator pattern
Software DevelopmentTech Bites
January 23, 2023

Decorator pattern

Design patterns are typical solutions to common problems in software design. Each pattern is like a blueprint that you can customize to solve a particular design problem in your code. A decorator pattern allows users to add new functionality to an existing object without altering its structure. This design pattern comes under…

Leave a Reply