SyntaxPilot
Courses/Low-Level Design/Lesson 52
Video coming soonThis lesson’s video is being made

Start with the notes below; the video appears here as soon as it is on YouTube.

Low-Level Design · Lesson 52 of 90

Refactoring techniques

refactoringbehaviour-preserving changeextract methodextract classinline methodrenameintroduce parameter objectreplace conditional with polymorphismreplace type code with subclassesmove methodencapsulate fieldsafe refactoring with testsIDE refactoring tools

These are the notes for Low-Level Design (LLD) episode 52. Episode 51 taught us to smell bad code; this episode fixes the smells safely. Refactoring is a set of small, named, behaviour-preserving moves that improve the design without changing what the program does. We invent it at Ravi's canteen: a "clean rewrite" that silently changes the bill, then safe refactoring with tests, extract method, inline method, rename, introduce parameter object, encapsulate field, move method, extract class, replace type code with subclasses and replace conditional with polymorphism, and the IDE refactoring tools that do the typing for you. Every program was actually run with javac Main.java && java -cp . Main (Java 21), and every output shown is real.

1. The real-life idea: rearranging a busy kitchen

In the kitchen In code
The kitchen is a mess, but dinner runs every night Working code with a poor design
Close for a week and rebuild everything The big rewrite: risky, behaviour changes unnoticed
Move one shelf at a time, taste the dal after each move Refactoring: one small step, then run the tests
Same dishes, better kitchen, guests never noticed Behaviour preserved, design improved

2. The problem: the big rewrite

public class Main {
    static double totalBill(double food, int distanceKm, boolean isMember) {   // the OLD code: works
        if (isMember) food = food * 0.9;
        double delivery = distanceKm > 3 ? 20 : 0;
        return (food + delivery) * 1.05;
    }
    static double totalBillRewritten(double food, int distanceKm, boolean isMember) {   // the big rewrite
        double amount = food + (distanceKm > 3 ? 20 : 0);
        if (isMember) amount = amount * 0.9;
        return amount * 1.05;
    }
    static void check(String name, double expected, double actual) {   // a tiny test
        System.out.println((expected == actual ? "PASS " : "FAIL ") + name
                + ": expected " + expected + ", got " + actual);
    }
    public static void main(String[] args) {
        check("old code", 210.0, totalBill(200, 5, true));
        check("rewrite ", 210.0, totalBillRewritten(200, 5, true));
    }
}

Output (real):

PASS old code: expected 210.0, got 210.0
FAIL rewrite : expected 210.0, got 207.9

The rewrite looks cleaner but applies the member discount to the delivery fee too, so the bill changed from 210.0 to 207.9. Without the tiny check test, nobody would notice until a customer complained.

3. What refactoring is

Martin Fowler, author of the book Refactoring (first edition written 1997–1999 with Java examples; the second edition uses JavaScript), defines a refactoring as "a change made to the internal structure of software to make it easier to understand and cheaper to modify" (refactoring.com). The verb to refactor means restructuring code through a series of such refactorings without changing its observable behaviour.

  • Behaviour-preserving change: for every input, the program gives exactly the same output as before. Only the inside changes.
  • A test is a small piece of code that runs your code and checks the result automatically. Tests are the safety net that proves the behaviour didn't change.

The safe loop:

tests pass  ->  ONE small move  ->  run tests  ->  pass? commit (save)  |  fail? undo that one step

Two hats rule: never refactor and add a feature in the same step. First make the change easy (refactor), then make the easy change (feature). If a test fails while you wear both hats, you can't tell which change broke it.

4. Extract method

Extract method: take a fragment of a long method that does one job, move it into a new method with a good name, and call it.

Steps: (1) create the new method and copy the fragment in; (2) pass what it reads as parameters, return what it produces; (3) replace the fragment with a call; (4) run the tests.

public class Main {
    static void printBill(String[] names, int[] quantities, double[] prices) {
        for (int i = 0; i < names.length; i++) {
            System.out.println(quantities[i] + " x " + names[i] + " = " + quantities[i] * prices[i]);
        }
        double total = subtotal(quantities, prices);                // step 2: call it
        System.out.println("Total: " + total);
    }
    static double subtotal(int[] quantities, double[] prices) {     // step 1: extracted
        double sum = 0;
        for (int i = 0; i < quantities.length; i++) sum += quantities[i] * prices[i];
        return sum;
    }
    static void check(String name, double expected, double actual) {
        System.out.println((expected == actual ? "PASS " : "FAIL ") + name
                + ": expected " + expected + ", got " + actual);
    }
    public static void main(String[] args) {
        printBill(new String[]{"chai", "thali"}, new int[]{2, 1}, new double[]{15, 120});
        check("subtotal", 150.0, subtotal(new int[]{2, 1}, new double[]{15, 120}));
    }
}

Output (real):

2 x chai = 30.0
1 x thali = 120.0
Total: 150.0
PASS subtotal: expected 150.0, got 150.0

In IntelliJ IDEA (Windows/Linux keys) select the lines and press Ctrl+Alt+M: the IDE works out parameters and the return value for you.

5. Inline method and rename

Inline method is the opposite of extract: when a method's body is as clear as its name, or it only forwards to another method, put the body back into the callers and delete it.

// before: a method that adds nothing
boolean isFar(int km) { return km > 3; }
fee = isFar(km) ? 20 : 0;

// after: body put back in the caller (with a named constant)
fee = km > FREE_DELIVERY_KM ? 20 : 0;

IntelliJ IDEA: Ctrl+Alt+N.

Rename is the most common refactoring: give a variable, method or class a name that says what it is (c(q, p) → subtotal(quantities, prices)). By hand you might miss a use; the IDE (integrated development environment, the editor you code in) renames every use in every file. IntelliJ IDEA: Shift+F6.

6. The problem: too many positional parameters

public class Main {
    static int deliveryFee(int distanceKm, int weightKg, boolean raining, boolean lateNight) {
        int fee = distanceKm > 3 ? 20 : 0;
        if (weightKg > 5) fee += 10;
        if (raining) fee += 15;
        if (lateNight) fee += 25;
        return fee;
    }
    public static void main(String[] args) {
        System.out.println("Asha: Rs " + deliveryFee(5, 2, true, false));   // rain
        System.out.println("Ravi: Rs " + deliveryFee(5, 2, false, true));   // late night
        System.out.println("Neha: Rs " + deliveryFee(2, 5, false, false));  // meant 5 km, 2 kg!
    }
}

Output (real):

Asha: Rs 35
Ravi: Rs 45
Neha: Rs 0

Neha's trip is 5 km and 2 kg, but 2, 5 was typed. Both are int, so it compiles, and she pays Rs 0 delivery. And what does true, false mean at a call site? You must read the method to find out.

7. Introduce parameter object

Introduce parameter object: replace a group of parameters that travel together with one object.

record Trip(int distanceKm, int weightKg, boolean raining, boolean lateNight) {
    static Trip of(int distanceKm, int weightKg) { return new Trip(distanceKm, weightKg, false, false); }
    Trip inRain() { return new Trip(distanceKm, weightKg, true, lateNight); }
    Trip atNight() { return new Trip(distanceKm, weightKg, raining, true); }
}
public class Main {
    static int deliveryFee(Trip trip) {                     // one parameter, with names inside
        int fee = trip.distanceKm() > 3 ? 20 : 0;
        if (trip.weightKg() > 5) fee += 10;
        if (trip.raining()) fee += 15;
        if (trip.lateNight()) fee += 25;
        return fee;
    }
    public static void main(String[] args) {
        System.out.println("Asha: Rs " + deliveryFee(Trip.of(5, 2).inRain()));
        System.out.println("Ravi: Rs " + deliveryFee(Trip.of(5, 2).atNight()));
        System.out.println("Neha: Rs " + deliveryFee(Trip.of(5, 2)));   // no flags to mix up
    }
}

Output (real):

Asha: Rs 35
Ravi: Rs 45
Neha: Rs 20

The booleans became named methods (inRain(), atNight()), so a call reads like a sentence. A new rule (say a festival surcharge) is added inside Trip, and no caller's parameter list changes. For many optional values, a Builder (episode 25) is the next step.

8. Encapsulate field

class Wallet {
    public double balance;                  // anyone can write anything
}
public class Main {
    public static void main(String[] args) {
        Wallet asha = new Wallet();
        asha.balance = 100;
        asha.balance = asha.balance - 600;  // a thali on credit?
        System.out.println("Asha's wallet: Rs " + asha.balance);
    }
}

Output (real):

Asha's wallet: Rs -500.0

A public field can be written by any code anywhere, so the rule "never below zero" has no place to live.

Encapsulate field: (1) make the field private; (2) add a getter; (3) replace every write with a method that enforces the rule; (4) run the tests after each step.

class Wallet {
    private long balance;                                  // step 1: private
    long balance() { return balance; }                    // step 2: a getter
    void add(long rupees) { balance += rupees; }
    void pay(long rupees) {                               // step 3: rules live here
        if (rupees > balance)
            throw new IllegalStateException("not enough money: balance " + balance + ", needed " + rupees);
        balance -= rupees;
    }
}
public class Main {
    public static void main(String[] args) {
        Wallet asha = new Wallet();
        asha.add(100);
        asha.pay(60);
        System.out.println("Asha's wallet: Rs " + asha.balance());
        asha.pay(600);
    }
}

Output (real):

Asha's wallet: Rs 40
Exception in thread "main" java.lang.IllegalStateException: not enough money: balance 40, needed 600
    at Wallet.pay(Main.java:7)
    at Main.main(Main.java:17)

9. Move method and extract class

Move method: when a method uses another class's data more than its own (the feature envy smell), move it to that class. A safe sequence: copy the method to the target class; make the old method forward to the new one; switch callers one by one; delete the old method. IntelliJ IDEA: F6.

// before, in Billing:   double discountFor(Customer c) { ... c.isMember() ... c.visits() ... }
// after, in Customer:   double discount() { ... isMember ... visits ... }
// callers:              customer.discount()

Extract class: a class has grown too big (the large class smell). Order has 12 fields, and 5 of them (name, phone, street, city, PIN) are really about the customer. Create Customer, move those fields and the methods that use them, and give Order a Customer field: Order now has a customer instead of being one.

// before
class Order { String customerName, customerPhone, street, city, pin; List<Item> items; ... }
// after
record Customer(String name, String phone, Address address) { }
class Order { Customer customer; List<Item> items; ... }

10. The problem: type codes and switches

A type code is a plain number or string that says what kind of thing something is (1 = dine in, 2 = takeaway, 3 = delivery), with a switch on it in every method that cares.

public class Main {
    static final int DINE_IN = 1, TAKEAWAY = 2, DELIVERY = 3, PICKUP_COUNTER = 4;   // 4 is new
    static int extraCharge(int type) {
        switch (type) {
            case DINE_IN: return 0;
            case TAKEAWAY: return 5;              // packing
            case DELIVERY: return 20;
            case PICKUP_COUNTER: return 0;        // added here...
            default: return 0;
        }
    }
    static String label(int type) {
        switch (type) {
            case DINE_IN: return "Dine in";
            case TAKEAWAY: return "Takeaway";
            case DELIVERY: return "Delivery";
            default: return "UNKNOWN";            // ...but forgotten here
        }
    }
    public static void main(String[] args) {
        for (int type = 1; type <= 4; type++)
            System.out.println(label(type) + ": +Rs " + extraCharge(type));
    }
}

Output (real):

Dine in: +Rs 0
Takeaway: +Rs 5
Delivery: +Rs 20
UNKNOWN: +Rs 0

The new type was added to one switch and forgotten in the other. Every new type means hunting through every switch: that's shotgun surgery.

11. Replace type code with subclasses, replace conditional with polymorphism

Two refactorings together:

  • Replace type code with subclasses: each type becomes its own class (here, implementations of an interface).
  • Replace conditional with polymorphism: each class answers the question itself (extraCharge(), label()), so the switches disappear. Polymorphism (episode 9) means one call, t.label(), runs a different method depending on the object's real class.
interface OrderType {
    int extraCharge();
    String label();
}
class DineIn implements OrderType {
    public int extraCharge() { return 0; }
    public String label() { return "Dine in"; }
}
class Takeaway implements OrderType {
    public int extraCharge() { return 5; }
    public String label() { return "Takeaway"; }
}
class Delivery implements OrderType {
    public int extraCharge() { return 20; }
    public String label() { return "Delivery"; }
}
class PickupCounter implements OrderType {        // the new type
    public int extraCharge() { return 0; }
}
public class Main {
    public static void main(String[] args) {
        OrderType[] types = { new DineIn(), new Takeaway(), new Delivery(), new PickupCounter() };
        for (OrderType t : types) System.out.println(t.label() + ": +Rs " + t.extraCharge());
    }
}

Compiler output (real):

Main.java:17: error: PickupCounter is not abstract and does not override abstract method label() in OrderType
class PickupCounter implements OrderType {        // the new type
^
1 error

The forgotten method is now a compile error, so the mistake can't reach a customer. Add it:

interface OrderType {
    int extraCharge();
    String label();
}
class DineIn implements OrderType {
    public int extraCharge() { return 0; }
    public String label() { return "Dine in"; }
}
class Takeaway implements OrderType {
    public int extraCharge() { return 5; }
    public String label() { return "Takeaway"; }
}
class Delivery implements OrderType {
    public int extraCharge() { return 20; }
    public String label() { return "Delivery"; }
}
class PickupCounter implements OrderType {        // the new type
    public int extraCharge() { return 0; }
    public String label() { return "Pickup counter"; }
}
public class Main {
    public static void main(String[] args) {
        OrderType[] types = { new DineIn(), new Takeaway(), new Delivery(), new PickupCounter() };
        for (OrderType t : types) System.out.println(t.label() + ": +Rs " + t.extraCharge());
    }
}

Output (real):

Dine in: +Rs 0
Takeaway: +Rs 5
Delivery: +Rs 20
Pickup counter: +Rs 0

Adding a fifth type means adding one class; no existing code changes. That's the Open-Closed Principle (episode 13), reached by refactoring. (With Java 21 you can also use a sealed interface and a switch with pattern matching, which the compiler checks for missing cases; see episode 43.)

12. IDE refactoring tools

IntelliJ IDEA shortcuts on Windows/Linux, from JetBrains' documentation:

Refactoring Shortcut
Refactor This (menu for whatever is under the cursor) Ctrl+Alt+Shift+T
Rename Shift+F6
Extract Method Ctrl+Alt+M
Inline Ctrl+Alt+N
Move F6

Eclipse and VS Code have their own Refactor menus. The tool keeps the code compiling and changes every use correctly; only tests prove the behaviour stayed the same, so still run them after each step.

Common mistakes

Mistake What you see (real) Why Fix
Big-bang rewrite FAIL rewrite : expected 210.0, got 207.9 Behaviour changed unseen Small steps, tests after each
Refactoring and adding a feature together A failing test, but which change broke it? Two changes mixed One hat at a time
Refactoring without tests Nothing, until a customer complains No safety net Pin current behaviour with tests first
Same-typed positional parameters No error: Neha: Rs 0 Arguments swapped Parameter object, named methods
Public mutable field No error: Asha's wallet: Rs -500.0 Rules can't be enforced Encapsulate field → IllegalStateException: not enough money: balance 40, needed 600
Type code + many switches No error: UNKNOWN: +Rs 0 One switch forgotten Polymorphism → compile error is not abstract and does not override abstract method label()
Find-and-replace renaming Compile errors, or a wrong word renamed in a string Text replace doesn't understand code IDE Rename (Shift+F6)

Mini project: refactor a legacy parking-fee calculator

Step 0: pin the behaviour with tests (these are called characterization tests: they record what the code does today, right or wrong).

public class Main {
    // legacy parking fee: type 1 = bike, 2 = car, 3 = bus; hours parked
    static int fee(int t, int h) {
        int f = 0;
        if (t == 1) { f = 10 + (h > 2 ? (h - 2) * 5 : 0); }
        else if (t == 2) { f = 20 + (h > 2 ? (h - 2) * 10 : 0); }
        else if (t == 3) { f = 50 + (h > 2 ? (h - 2) * 25 : 0); }
        if (h > 24) f = f + 100;                     // overnight penalty
        return f;
    }
    static void check(String name, int expected, int actual) {
        System.out.println((expected == actual ? "PASS " : "FAIL ") + name + ": expected " + expected + ", got " + actual);
    }
    public static void main(String[] args) {         // step 0: pin the behaviour with tests
        check("bike 1h", 10, fee(1, 1));
        check("car 5h", 50, fee(2, 5));
        check("bus 3h", 75, fee(3, 3));
        check("car 26h", 360, fee(2, 26));
    }
}

Output (real):

PASS bike 1h: expected 10, got 10
PASS car 5h: expected 50, got 50
PASS bus 3h: expected 75, got 75
PASS car 26h: expected 360, got 360

Steps 1–5, running the tests after each: rename (t → type, h → hoursParked); replace magic numbers with constants (FREE_HOURS, OVERNIGHT_PENALTY); extract method (extraHoursFee, overnightPenalty); replace type code with classes (Bike, Car, Bus); replace conditional with polymorphism (baseFee(), perExtraHour()). The result:

interface Vehicle {
    int baseFee();                                    // first 2 hours
    int perExtraHour();
}
record Bike() implements Vehicle { public int baseFee() { return 10; } public int perExtraHour() { return 5; } }
record Car() implements Vehicle { public int baseFee() { return 20; } public int perExtraHour() { return 10; } }
record Bus() implements Vehicle { public int baseFee() { return 50; } public int perExtraHour() { return 25; } }
final class ParkingFee {
    private static final int FREE_HOURS = 2, OVERNIGHT_HOURS = 24, OVERNIGHT_PENALTY = 100;
    static int fee(Vehicle vehicle, int hoursParked) {
        return vehicle.baseFee() + extraHoursFee(vehicle, hoursParked) + overnightPenalty(hoursParked);
    }
    private static int extraHoursFee(Vehicle vehicle, int hoursParked) {
        return Math.max(0, hoursParked - FREE_HOURS) * vehicle.perExtraHour();
    }
    private static int overnightPenalty(int hoursParked) { return hoursParked > OVERNIGHT_HOURS ? OVERNIGHT_PENALTY : 0; }
}
public class Main {
    static void check(String name, int expected, int actual) {
        System.out.println((expected == actual ? "PASS " : "FAIL ") + name + ": expected " + expected + ", got " + actual);
    }
    public static void main(String[] args) {          // the SAME tests, still green
        check("bike 1h", 10, ParkingFee.fee(new Bike(), 1));
        check("car 5h", 50, ParkingFee.fee(new Car(), 5));
        check("bus 3h", 75, ParkingFee.fee(new Bus(), 3));
        check("car 26h", 360, ParkingFee.fee(new Car(), 26));
    }
}

Output (real):

PASS bike 1h: expected 10, got 10
PASS car 5h: expected 50, got 50
PASS bus 3h: expected 75, got 75
PASS car 26h: expected 360, got 360

Same four results, so the behaviour is preserved. Adding a truck is now one new record.

Practice

1. Refactor with extract method: a report(Student s) method that sums marks, computes the average and picks a grade (A ≥ 75, B ≥ 60, else C), all inline.

Answer
public class Main {
    record Student(String name, int[] marks) { }
    static void report(Student s) {
        double average = average(s.marks());
        System.out.println(s.name() + ": average " + average + ", grade " + grade(average));
    }
    static double average(int[] marks) {
        int sum = 0;
        for (int m : marks) sum += m;
        return (double) sum / marks.length;
    }
    static String grade(double average) {
        if (average >= 75) return "A";
        if (average >= 60) return "B";
        return "C";
    }
    public static void main(String[] args) {
        report(new Student("Priya", new int[]{80, 72, 91}));
        report(new Student("Kabir", new int[]{55, 61, 58}));
    }
}

Output (real):

Priya: average 81.0, grade A
Kabir: average 58.0, grade C

2. Replace the conditional with polymorphism: double area(Shape s) { switch (s.kind) { case CIRCLE: ...; case SQUARE: ...; } }, then add a triangle.

Answer
interface Shape { double area(); }
record Circle(double r) implements Shape { public double area() { return Math.PI * r * r; } }
record Square(double side) implements Shape { public double area() { return side * side; } }
record Triangle(double base, double height) implements Shape { public double area() { return 0.5 * base * height; } }
public class Main {
    public static void main(String[] args) {
        Shape[] shapes = { new Circle(1), new Square(2), new Triangle(3, 4) };
        for (Shape s : shapes) System.out.printf("%s area %.2f%n", s, s.area());
    }
}

Output (real):

Circle[r=1.0] area 3.14
Square[side=2.0] area 4.00
Triangle[base=3.0, height=4.0] area 6.00

3. A cinema Show has public int seatsLeft; and code anywhere does show.seatsLeft -= n. Encapsulate it so overbooking is impossible.

Answer
class Show {
    private final int capacity;
    private int booked;                                   // was: public int seatsLeft
    Show(int capacity) { this.capacity = capacity; }
    int seatsLeft() { return capacity - booked; }
    void book(int seats) {
        if (seats <= 0) throw new IllegalArgumentException("seats must be positive: " + seats);
        if (seats > seatsLeft()) throw new IllegalStateException("only " + seatsLeft() + " seats left");
        booked += seats;
    }
}
public class Main {
    public static void main(String[] args) {
        Show show = new Show(5);
        show.book(3);
        System.out.println("left: " + show.seatsLeft());
        show.book(4);
    }
}

Output (real):

left: 2
Exception in thread "main" java.lang.IllegalStateException: only 2 seats left
    at Show.book(Main.java:8)
    at Main.main(Main.java:17)

4. Which refactoring? (a) sendInvoice(String email, String name, String gstin, String address, boolean paid, boolean urgent) (b) a one-line private method isEmpty(list) that just calls list.isEmpty() (c) Report.formatAddress(Customer c) uses only c's fields.

Answer

(a) introduce parameter object (an InvoiceRecipient record) and replace the booleans with named methods or an enum; (b) inline method; (c) move method to Customer.

5. Your refactoring step made one test fail. What do you do?

Answer

Undo that one step (it was small, so it's cheap), then redo it more carefully or in even smaller steps. Never "fix forward" by changing the test to match the new behaviour, unless the old behaviour was a confirmed bug, and then that's a separate, deliberate behaviour change.

Quick quiz

double area(Shape s) {
  switch (s.kind) {
    case CIRCLE: return PI * s.r * s.r;
    case SQUARE: return s.side * s.side;
  }
}

More shapes will come. Which refactoring fits? (a) Inline method (b) Rename (c) Replace conditional with polymorphism (d) Encapsulate field

Answer

(c). Each shape gets its own class with its own area(); a new Triangle can't forget it, because the compiler checks that every class implements the interface.

Interview questions

  1. What is refactoring? Changing the internal structure of code to make it easier to understand and cheaper to modify, without changing its observable behaviour.
  2. Refactoring vs rewriting? Refactoring is many small, verified, behaviour-preserving steps; a rewrite replaces code wholesale and risks changing behaviour unseen.
  3. How do you refactor safely? Tests first (characterization tests for legacy code), one small step at a time, run tests after each, commit often, use IDE automated refactorings.
  4. Name five refactorings and the smell each fixes. Extract method (long method), introduce parameter object (long parameter list, data clumps), move method (feature envy), extract class (large class), replace conditional with polymorphism (type-code switches, shotgun surgery).
  5. When would you inline a method? When its body is as clear as its name, or it only forwards to another method.
  6. Why is replacing type codes with polymorphism useful? Adding a type means adding a class (Open-Closed), and the compiler forces every behaviour to be implemented.
  7. What does encapsulate field give you? A single place to enforce invariants, and freedom to change the representation later.

Glossary

Term Meaning, with an example
Refactoring A change to the internal structure of code that keeps its behaviour: extracting subtotal() from printBill()
Behaviour-preserving change For every input, the same output as before
Big rewrite Replacing code wholesale in one go; risky because changes go unnoticed
Test Code that runs your code and checks the result automatically: check("rewrite", 210.0, ...)
Safety net The set of tests you run after every refactoring step
Characterization test A test that records what legacy code does today, before you change it
Two hats Refactoring and adding features are separate activities; never both at once
Extract method Move a fragment into a new, well-named method and call it
Inline method Put a trivial method's body back into its callers and delete it
Rename Give a variable, method or class a better name everywhere it is used
Introduce parameter object Replace a group of parameters with one object: deliveryFee(Trip trip)
Encapsulate field Make a field private and route reads/writes through methods that enforce rules
Move method Move a method to the class whose data it uses most
Extract class Split part of a big class's fields and methods into a new class: Customer out of Order
Type code A number/string that says what kind something is: DELIVERY = 3
Replace type code with subclasses Turn each type code value into its own class
Replace conditional with polymorphism Replace a switch/if chain on a type with a method each class implements
Polymorphism One call runs different code depending on the object's real class: t.label()
Open-Closed Principle Open for extension (add a class), closed for modification (no existing code edited)
IDE Integrated development environment, the editor you code in: IntelliJ IDEA, Eclipse, VS Code
Automated refactoring A refactoring the IDE performs for you: Rename with Shift+F6 in IntelliJ IDEA
IllegalStateException Standard exception for "the object can't do this right now": not enough money: balance 40, needed 600
Commit Saving a snapshot of the code in version control (git)

Summary

  • Refactoring changes structure, never behaviour; a big rewrite risks silent changes (207.9 instead of 210.0).
  • Work in tiny steps with tests run after each; undo a step that breaks a test; wear one hat at a time.
  • Extract method, inline method and rename make code readable.
  • Introduce parameter object fixes long parameter lists; encapsulate field gives rules one home.
  • Move method and extract class put behaviour where its data lives.
  • Replace type code with subclasses + replace conditional with polymorphism turn forgotten cases into compile errors.
  • IDE tools do the typing (Shift+F6, Ctrl+Alt+M, Ctrl+Alt+N, F6); tests prove the behaviour.

Next episode: Designing for testability: JUnit 5, test doubles, Mockito, seams, injecting clocks, and test-driven development.