Refactoring

Table of contents

Summarise with:

Refactoring is a technical term commonly known as clean up the code, that is, refining a piece of software’s code to improve it, removing redundancies and flaws, and making it more efficient. Generally speaking, this refactoring does not focus so much on fixing bugs or coding errors, but rather on addressing design flaws that may affect its performance and scalability.

This process is of the utmost importance to ensure that the code is easy to understand and, therefore, to modify. In many software projects, the code is written by several developers, each with their own logic, skills and established habits. If a set of best practices has been established and all developers have a sufficient level of programming proficiency, there will be no need to refactor so much code.

However, it is not uncommon for many projects to be characterised by a rush to complete them and a somewhat haphazard approach to code quality; as a result, reviewing the code and refactoring it will become a regular and essential task to ensure that the software developed is functional.

What coding issues can refactoring resolve?

When refactoring code, we aim to make it more efficient so that it has a cleaner design and is more readable for both programmers and the system. There is therefore an extensive list of bad practices which slow down the code and tend to cause errors sooner or later. Some of the most common code defects that refactoring addresses are:

  • Bloated code (bloater): This refers to code that has become excessively long and is now difficult to understand and maintain. For example, this is the case with code containing classes or methods that are too long, an excess of comments, or an excessive number of parameters in functions.
  • Duplicate code: This occurs when there are fragments of code that are repeated in different parts of the programme, which causes maintenance problems, as any change to one duplicate instance would require changes to all the other instances.
  • Obsolete code: This refers to parts of the code that are no longer used or have become redundant due to changes in software requirements or the evolution of the design. Refactoring removes or updates this code to keep the codebase clean and functional.
  • Classes with too many methods: This occurs when a class has an excessive number of methods, which indicates a breach of the single responsibility principle. During refactoring, these classes are split into smaller, more cohesive classes, each with a clear and limited responsibility.
  • Confusing function and variable names: Non-descriptive or ambiguous names that make it difficult to understand the purpose or functionality of a function or variable. During refactoring, these entities are renamed so that they better reflect their purpose, with a view to future modifications.
  • Go-to commands: The use of unconditional jump instructions, such as `goto`, can make the flow of the programme difficult to follow and understand. This command is used to make the system jump from one section of code to another that are separated from one another, skipping the code in between. One refactoring technique involves rewriting the code to use more readable and structured control structures, such as loops and conditional statements.
  • Several concatenated `if` commands: This occurs when there are multiple nested or chained `if` statements, which makes it significantly more difficult to understand the control flow and can lead to logical errors. To address this, these structures are simplified during the refactoring process using techniques such as conditional restructuring, so that the code becomes clearer and more concise.

 

Example of code refactoring

The code shown below contains two separate functions for calculating the area and the perimeter of a rectangle, which is rather redundant.

 Faulty and redundant code

def calculate_rectangle_area(base, height):

    # Calculate the area of the rectangle

    result = base * height

    return result

def calculate_perimeter_of_rectangle(base, height):

    # Calculate the perimeter of the rectangle

    result = 2 * (base + height)

    return result

 

base_rectangle = 5

rectangle_height = 3

 

area = calculate_rectangle_area(rectangle_base, rectangle_height)

print(«Area of the rectangle:», area)

 

perimeter = calculate_rectangle_perimeter(rectangle_base, rectangle_height)

print(«Perimeter of the rectangle:», perimeter)

 

 

Refactored code

In this refactored code, we have created a `Rectangle` class that encapsulates the properties and behaviours associated with a rectangle. This makes the code more modular, reusable and easier to understand. Now, the functions for calculating the area and perimeter are encapsulated within the `Rectangle` class, making the code clearer.

class Rectangle:

    def __init__(self, base, height):

        self.base = base

        self.height = height

 

    def calculate_area(self):

        # Calculate the area of the rectangle

        return self.base * self.height

 

    def calcular_perimetro(self):

        # Calculate the perimeter of the rectangle

        return 2 * (self.base + self.altura)

 

# Creamos un objeto Rectangulo con la base y altura dadas

rectangulo = Rectangulo(5, 3)

 

# Calculamos y mostramos el área del rectángulo

print(«Área del rectángulo:», rectangulo.calcular_area())

 

# Calculamos y mostramos el perímetro del rectángulo

print(«Perímetro del rectángulo:», rectangulo.calcular_perimetro())

 

Share in:

Related articles

UTM

UTM stands for Urchin Tracking Module and is a system of codes that are added to the end of URLs to track the origin of web traffic. These codes allow marketers and web analysts to identify where visitors are coming from.

Spamming

Spamming is the massive and indiscriminate sending of unsolicited messages through various digital media, such as email, social networks, forums or text messages. These messages often contain advertising content, scams or malicious links aimed at misleading the user.

Big Data

Big Data refers to high-volume, highly interrelated data sets from many different sources that are difficult to manage with traditional data processing tools and methods. Three V's of Big Data There are three V's that define Big Data.

Sidebar

Within a website, the sidebar plays a very important role, as it forms a unique space to offer elements that interest us. Nowadays, it is very common to see forms to sign up for a newsletter or lead magnets downloads on

Scroll to Top