From Spaghetti Code to Clean Code: A Step-by-Step Guide to Refactoring in Java

Borys Nikolenko
Javarevisited
Published in
6 min readApr 3, 2023

--

Designed by Freepik

What is ‘Spaghetti code’ (with example)

Have you ever struggled with reading spaghetti code? Code that is difficult to read and understand. It can be a nightmare for developers, especially if they need to modify it or add new features.

In this article, we will show you how to transform spaghetti code into clean code through the refactoring process. We will use a simple calculator as an example and walk you through the steps of refactoring. By the end of this article, you will have a better understanding of how to write code that is easy to read and maintain.

Before we get started, let’s take a look at the code we will be working with:

public class MessyCalculator implements Calculator {
@Override
public double calculate(double num1, double num2, char operator) {
double result;
if (operator == '+') {
result = num1 + num2;
} else if (operator == '-') {
result = num1 - num2;
} else if (operator == '*') {
result = num1 * num2;
} else if (operator == '/') {
if (num2 == 0) {
throw new ArithmeticException("Error: Division by zero is not allowed");
} else {
result = num1 / num2;
}
} else {…

--

--

Borys Nikolenko
Javarevisited

Passionate about Java Software Engineering, Yoga and continuous self-improvement