How to Refactor Badly Written Code: Principles, Code Smells, and Refactoring Techniques
This article explains the purpose and principles of refactoring, enumerates common code smells, and provides concrete refactoring techniques—including extracting functions, inlining, moving features, reorganizing data, simplifying conditionals and calls—illustrated with Java code examples.
(1) Refactoring Principles
Refactoring is a disciplined technique for improving the internal structure of software without changing its observable behavior, aiming to increase understandability and reduce modification cost.
What is Refactoring?
It is an adjustment of the internal structure of software while preserving its external behavior, often achieved by applying a series of refactoring patterns.
Why Refactor?
Improves design, helps locate bugs, and speeds up development by making the code easier to read and modify.
When to Refactor?
Refactoring should be done continuously; a practical rule is the "Three‑time rule": do it the first time you encounter a problem, avoid it the second time, and refactor on the third occurrence.
(2) Code Smells
Common indicators of poor design include:
Duplicate code
Long classes or methods
Large parameter lists
Divergent change
Shotgun surgery
Feature envy, data clumps, primitive obsession, switch statements, parallel hierarchies, redundant classes, excessive comments, and many others.
(3) Reorganizing Functions
Extract Method
Identify a long or unclear code fragment, create a new method with a descriptive name, move the code there, pass required variables as parameters, and replace the original fragment with a call.
Inline Method
When a method’s body is as clear as its name, replace its calls with the method body and delete the method.
Inline Temporary Variable
Replace a temporary variable that is used only once with the expression that computes it.
Example:
double basePrice = quantity * timePrice;
if (basePrice > 1000) {
return basePrice * 0.95;
} else {
return basePrice * 0.98;
}Can be refactored to:
if (basePrice() > 1000) {
return basePrice() * 0.95;
} else {
return basePrice() * 0.98;
}
double basePrice() {
return quantity * timePrice;
}Introduce Explaining Variable
Break a complex condition into well‑named boolean variables.
final boolean isMacOs = platform.toUpperCase().indexOf("MAC") > -1;
final boolean isIEBrowser = browser.toUpperCase().indexOf("IE") > -1;
final boolean wasResized = resize > 0;
if (isMacOs && isIEBrowser && wasInitialized() && wasResized) {
// do something
}(4) Moving Features Between Objects
Use Move Method, Move Field, Extract Class, Inline Class, Hide Delegate, Remove Middle Man, and other patterns to place responsibilities where they belong.
(5) Reorganizing Data
Techniques include Self‑Encapsulate Field, Replace Data Value with Object, Replace Array with Object, Replace Magic Number with Constant, Encapsulate Collection, and others.
(6) Simplifying Conditional Expressions
Decompose complex conditions, merge similar tests, extract conditionals into methods, replace control flags with early returns, and use polymorphism where appropriate.
(7) Simplifying Function Calls
Rename unclear functions, add or remove parameters, split queries from modifiers, replace parameter‑driven logic with separate functions, introduce parameter objects, and hide unused functions.
(8) Handling Generalization Relationships
Apply Pull Up Field/Method, Push Down Method/Field, Extract Superclass, Extract Subclass, Extract Interface, Collapse Hierarchy, Replace Inheritance with Delegation, or the opposite, to keep the class hierarchy clean.
These refactoring patterns collectively help transform "dog‑sh*t" code into maintainable, readable, and robust software.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
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.