Mastering Code Smells: Identify and Refactor Common Bad Practices
This guide explains the most frequent code smells—Long Method, Large Class, Duplicated Code, Long Parameter List, Shotgun Surgery, Speculative Generality, and excessive comments—detailing why they harm readability and maintainability, and provides concrete refactoring techniques with Java examples to produce cleaner, more modular software.
Bad Smell: Long Method
A long method is a function whose length exceeds reasonable limits, both horizontally (line width) and vertically (number of lines). Horizontal overflow forces horizontal scrolling, while vertical overflow makes the method hard to understand and modify.
How to fix it
Configure the IDE to wrap lines at a standard width (e.g., 80 or 120 characters) and format the code.
Break long chained expressions, such as Java 8 streams, onto separate lines:
List<String> nodes = list.stream()
.filter()
.filter()
.map()
.filter()
.collect(Collectors.toList());For vertically long methods, extract smaller methods to isolate responsibilities:
public void longMethod() {
// many lines of logic
}
// Refactor to
public void longMethod() {
extractedPart();
// remaining logic
}
private void extractedPart() {
// isolated logic
}Bad Smell: Large Class (God Class)
A God Class aggregates too many responsibilities, violating the Single Responsibility Principle and often containing duplicated code.
Design patterns’ six principles (SOLID): Single Responsibility, Open‑Closed, Liskov Substitution, Law of Demeter, Interface Segregation, Dependency Inversion.
Criteria for a God Class (any three of the following):
CPFD – accesses data from many unrelated classes.
WOC – total cyclomatic complexity of its methods exceeds 65.
TCC – tight capsule cohesion less than 1/3 (few private methods relative to total methods).
How to fix it
Identify related fields and Extract Class to a new class, moving related methods with Move.
Identify related methods and Extract Subclass to split behavior into separate subclasses.
Bad Smell: Duplicated Code
Robert C. Martin: “Duplication may be the root of all evil in software.”
Duplicate code usually arises from copy‑and‑paste during rapid development. It leads to missed updates and higher maintenance cost.
Refactoring scenarios
Scenario 1 – Duplicate logic in two methods of the same class
class A {
public void method1() {
logic1;
logic2;
logic3;
}
public void method2() {
logic1;
logic2;
logic4;
}
}Extract the common part:
class A {
public void method1() {
baseMethod();
logic3;
}
public void method2() {
baseMethod();
logic4;
}
private void baseMethod() {
logic1;
logic2;
}
}Scenario 2 – Duplicate logic in sibling subclasses
class A extends Base {
public void method1() {
logic1;
logic2;
logic3;
}
}
class B extends Base {
public void method2() {
logic1;
logic2;
logic3;
}
}Move the shared code to the parent class:
class Base {
protected void baseMethod() {
logic1;
logic2;
}
}
class A extends Base {
public void method1() {
baseMethod();
logic3;
}
}
class B extends Base {
public void method2() {
baseMethod();
logic3;
}
}Scenario 3 – Duplicate code in unrelated classes
Extract the repeated logic into a utility class and use composition.
Bad Smell: Long Parameter List
Excessive parameters reduce readability and make method calls error‑prone. Adding new features often forces additional parameters, propagating changes throughout the codebase.
Solution
Group related parameters into a Data Transfer Object (DTO) and pass the DTO instead of many individual arguments.
A DTO (Data Transfer Object) is a design pattern used to transfer data between software subsystems.
Sometimes a long parameter list is justified, but if the method changes frequently, consider refactoring ("three‑times‑the‑same‑code, refactor").
Bad Smell: Shotgun Surgery
When a small change requires modifications in many classes, it is easy to miss locations, leading to bugs.
public class A {
@Value("${db.mysql.url}")
private String mysqlDbUrl;
}
public class B {
@Value("${db.mysql.url}")
private String mysqlDbUrl;
}If the database URL changes, multiple classes must be updated.
Solution
Use Move Method and Move Field to consolidate related code into a single class, or create a new class to hold the shared data.
Bad Smell: Speculative Generality
Prematurely adding abstractions or “future‑proof” code that is not needed now increases complexity and burdens the system with unnecessary baggage.
Principle: Simple Design – keep the design minimal, only adding elements that solve current requirements.
When implementing current business logic, follow four principles: test, reveal intent, eliminate duplication, and use the fewest elements. To avoid speculative generality: Remove unused parameters, methods, or calls. Rename methods to clearly express the present intent rather than abstract technical terms.
Bad Smell: Excessive Comments
Common comment smells listed in "Clean Code": chatter, redundant, misleading, boilerplate, log‑style, nonsense, explaining variable meaning, location markers, class ownership, commented‑out code, etc.
Too many or outdated comments can mislead readers and reduce code readability.
How to address
Delete dead code instead of commenting it out.
Prefer self‑descriptive names; let the code speak for itself.
If a short comment cannot fully describe a method, consider refactoring the method to have a single responsibility.
Summary
The article enumerates several typical code smells and provides practical refactoring steps—such as extracting methods or classes, using DTOs, consolidating duplicated logic, and simplifying designs—to help developers write cleaner, more maintainable code.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Liangxu Linux
Liangxu, a self‑taught IT professional now working as a Linux development engineer at a Fortune 500 multinational, shares extensive Linux knowledge—fundamentals, applications, tools, plus Git, databases, Raspberry Pi, etc. (Reply “Linux” to receive essential resources.)
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
