Fundamentals 14 min read

10 Practical Java Refactoring Techniques Every Developer Should Master

This article presents ten concrete Java refactoring techniques—from extracting duplicate code and splitting long methods to optimizing nested conditionals and removing temporary variables—each illustrated with clear before‑and‑after code examples and practical advice for improving code readability and maintainability.

Code Ape Tech Column
Code Ape Tech Column
Code Ape Tech Column
10 Practical Java Refactoring Techniques Every Developer Should Master

Ten Practical Refactoring Techniques (Java examples)

No.1 Extract Duplicate Code

Duplicated code inflates the code base and makes maintenance harder. Locate identical fragments that perform the same sub‑task and move them into a shared method placed in an appropriate class.

Example

class BadExample {
    public void someMethod1(){
        //code
        System.out.println("Duplicate code"); // duplicate block
        //code
    }
    public void someMethod2(){
        //code
        System.out.println("Duplicate code"); // duplicate block
        //code
    }
}

/* ---------------------separator---------------------- */

class GoodExample {
    public void someMethod1(){
        //code
        someMethod3();
        //code
    }
    public void someMethod2(){
        //code
        someMethod3();
        //code
    }
    private void someMethod3(){
        System.out.println("Duplicate code"); // duplicate block
    }
}

No.2 Split Long Methods

Very long methods hide duplicated logic and are difficult to understand. After extracting duplicates, break the remaining large method into smaller, well‑named private methods.

Example

class BadExample {
    public void someMethod(){
        //function[1]
        //function[2]
        //function[3]
    }
}

/* ---------------------separator---------------------- */

class GoodExample {
    public void someMethod(){
        function1();
        function2();
        function3();
    }
    private void function1(){
        //function[1]
    }
    private void function2(){
        //function[2]
    }
    private void function3(){
        //function[3]
    }
}

No.3 Optimize Nested Conditionals – Guard Clauses (Part 1)

Deeply nested conditionals obscure the main logic. Use guard clauses to return early when a precondition is not met, keeping the happy path at the top level.

Example

class BadExample {
    public void someMethod(Object A, Object B){
        if (A != null) {
            if (B != null) {
                //code[1]
            } else {
                //code[3]
            }
        } else {
            //code[2]
        }
    }
}

/* ---------------------separator---------------------- */

class GoodExample {
    public void someMethod(Object A, Object B){
        if (A == null) {
            //code[2]
            return;
        }
        if (B == null) {
            //code[3]
            return;
        }
        //code[1]
    }
}

No.4 Optimize Nested Conditionals – Combine Conditions (Part 2)

If guard clauses are not suitable, merge related conditions into a single compound expression to flatten the structure.

Example

class BadExample {
    public void someMethod(Object A, Object B){
        if (A != null) {
            if (B != null) {
                //code
            }
        }
    }
}

/* ---------------------separator---------------------- */

class GoodExample {
    public void someMethod(Object A, Object B){
        if (A != null && B != null) {
            //code
        }
    }
}

No.5 Remove One‑Time Temporary Variables

Transient variables that are used only once add noise. Replace them with the original expression directly.

Example

class BadExample {
    private int i;
    public int someMethod(){
        int temp = getVariable();
        return temp * 100;
    }
    public int getVariable(){
        return i;
    }
}

/* ---------------------separator---------------------- */

class GoodExample {
    private int i;
    public int someMethod(){
        return getVariable() * 100;
    }
    public int getVariable(){
        return i;
    }
}

No.6 Eliminate Long Parameter Lists

Methods with many parameters are hard to read and maintain. Group related parameters into a dedicated data object and pass that object instead.

Example

class BadExample {
    public void someMethod(int i,int j,int k,int l,int m,int n){
        //code
    }
}

/* ---------------------separator---------------------- */

class GoodExample {
    public void someMethod(Data data){
        //code
    }
}

class Data {
    private int i;
    private int j;
    private int k;
    private int l;
    private int m;
    private int n;
    // getters / setters
}

No.7 Extract Constants from Classes or Inheritance Hierarchies

Replace magic strings or numbers with named constants. This improves readability and centralises changes.

Example

class BadExample {
    public void someMethod1(){
        send("Your operation succeeded!");
    }
    public void someMethod2(){
        send("Your operation succeeded!");
    }
    public void someMethod3(){
        send("Your operation succeeded!");
    }
    private void send(String message){
        //code
    }
}

/* ---------------------separator---------------------- */

class GoodExample {
    protected static final String SUCCESS_MESSAGE = "Your operation succeeded!";
    public void someMethod1(){
        send(SUCCESS_MESSAGE);
    }
    public void someMethod2(){
        send(SUCCESS_MESSAGE);
    }
    public void someMethod3(){
        send(SUCCESS_MESSAGE);
    }
    private void send(String message){
        //code
    }
}

No.8 Let Classes Provide Their Own Behavior

A class should encapsulate its responsibilities. Instead of external code pulling data fields and performing calculations, move the calculation into the class itself.

Example

class BadExample {
    public int someMethod(Data data){
        int i = data.getI();
        int j = data.getJ();
        int k = data.getK();
        return i * j * k;
    }
    public static class Data{
        private int i;
        private int j;
        private int k;
        public Data(int i, int j, int k){
            this.i = i; this.j = j; this.k = k;
        }
        public int getI(){ return i; }
        public int getJ(){ return j; }
        public int getK(){ return k; }
    }
}

/* ---------------------separator---------------------- */

class GoodExample {
    public int someMethod(Data data){
        return data.getResult();
    }
    public static class Data{
        private int i;
        private int j;
        private int k;
        public Data(int i, int j, int k){
            this.i = i; this.j = j; this.k = k;
        }
        public int getI(){ return i; }
        public int getJ(){ return j; }
        public int getK(){ return k; }
        public int getResult(){ return i * j * k; }
    }
}

No.9 Split Overly Large Classes

When a class grows too large, separate distinct responsibilities into different classes. Group related fields and the methods that use them together, and resolve any remaining dependencies via parameter passing.

No.10 Pull Up Repeated Attributes and Methods to a Superclass

Identify fields or behaviours that appear in multiple subclasses. Move them to a common parent class, optionally applying the Template Method pattern. After refactoring, run comprehensive tests to ensure behaviour remains unchanged.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaSoftware Engineeringbest practicescode qualityrefactoring
Code Ape Tech Column
Written by

Code Ape Tech Column

Former Ant Group P8 engineer, pure technologist, sharing full‑stack Java, job interview and career advice through a column. Site: java-family.cn

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.