Skip to lesson

Spot OOP design problems

A design problem is code that works today but is easy to break and hard to change tomorrow. These problems repeat so often that they have names, so you can spot them, say the risk and give the usual fix.

Why working code can still be bad

A code smell is a sign in working code that the design is weak: the program compiles and gives the right output, but changing it later is hard or risky. Public fields, magic numbers, copied code and god classes are common smells.

A smell is not a compile error: javac is happy, and the output may be right. The trouble shows up later. A program is changed far more often than it is written: a new payment type, a new GST rate, a second address.

Good design makes such a change small and safe: one class, one place. For each smell, learn how to spot it, what can go wrong and the usual fix. That is also how to answer "What would you improve in this code?" in an interview.

Data without rules: public fields and blind setters

With public int balance;, any code anywhere can write w.balance = -200;. Private fields with a setter for each, which accepts any value, are no better: the rule "never negative" still has no home.

Example 1 · Before and after: public field vs rule-keeping methods

WalletDesignDemo.javaJava
class OldWallet {    public int balance;}
class Wallet {    private int balance;
    int getBalance() {        return balance;    }
    void addMoney(int amount) {        if (amount > 0) {            balance += amount;        }    }
    boolean pay(int amount) {        if (amount <= 0 || amount > balance) {            return false;        }        balance -= amount;        return true;    }}
public class WalletDesignDemo {    public static void main(String[] args) {        OldWallet old = new OldWallet();        old.balance = 300;        old.balance -= 500;        System.out.println("Before: balance " + old.balance);
        Wallet w = new Wallet();        w.addMoney(300);        System.out.println("After: paid? " + w.pay(500) + ", balance " + w.getBalance());    }}
Output
Before: balance -200
After: paid? false, balance 300

What this code does

  • Before: nothing stops main from pushing the balance below zero; the rule has no home.
  • After: there is no setter for balance. Money moves only through addMoney and pay, which check every amount.

Such a class only carries data, while its rules live outside, copied into many places. It is often called an anemic class: data but no behaviour.

Fix: keep the rule with the data. Give the class methods for real actions, like pay(amount) and addMoney(amount), and check every value inside them, as in Design methods, not just setters (opens in a new tab).

Find the bug

Where can bad data get in?

Select the line that is wrong.

A wallet must never go below zero. Which line lets it?

Round 1 of 2

Repetition: magic numbers and duplicated code

Refactoring is changing the inside design of working code without changing what it does, so that it becomes easier to read and change. The output before and after a refactoring is exactly the same.

A magic number is an unnamed number, like the 18 in amount * 18 / 100. Duplicated code is the same logic copied into two places. Both hide one rule in many spots, so a change made in one spot is missed in another.

Example 2 · Magic numbers and duplicated code, fixed

BillDemo.javaJava
class Bill {    static final int GST_PERCENT = 5;    static final int FREE_DELIVERY_FROM = 500;    static final int DELIVERY_FEE = 40;    static final int PACKING_FEE = 10;
    int food(int amount) {        return withTaxAndDelivery(amount) + PACKING_FEE;    }
    int grocery(int amount) {        return withTaxAndDelivery(amount);    }
    private int withTaxAndDelivery(int amount) {        int delivery = amount >= FREE_DELIVERY_FROM ? 0 : DELIVERY_FEE;        return amount + amount * GST_PERCENT / 100 + delivery;    }}
public class BillDemo {    public static void main(String[] args) {        Bill b = new Bill();        System.out.println("Food Rs. 400: Rs. " + b.food(400));        System.out.println("Grocery Rs. 600: Rs. " + b.grocery(600));    }}
Output
Food Rs. 400: Rs. 470
Grocery Rs. 600: Rs. 630

What this code does

  • Before the fix, food and grocery each had their own copy of amount * 5 / 100 and the 500 / 40 delivery rule.
  • Now every number has a name, and the shared rule lives in one private method. A GST change is a one-line edit.

Fix: give numbers a name with a static final constant, like GST_PERCENT, and move copied logic into one method that every place calls. Both fixes are refactorings: the output stays the same, only the design gets better.

Predict the output

Copies drift apart

Read the code and pick what it prints.

Round 1 of 2

Three discount methods, each a copy of the same formula.

class Rates {
int student(int fee) {
return fee - fee * 10 / 100;
}
int senior(int fee) {
return fee - fee * 15 / 100;
}
int staff(int fee) {
return fee - fee * 10 / 10;
}
}
public class RatesRound {
public static void main(String[] args) {
Rates r = new Rates();
System.out.println(r.student(1000) + " " + r.senior(1000) + " " + r.staff(1000));
}
}

Wrong structure: instanceof chains and inheritance for reuse

An if (p instanceof Upi) … else if (p instanceof Card) … chain asks each object what it is, then decides for it. Every new type means finding and editing every such chain.

Example 3 · Before: an instanceof chain breaks silently

ChainSmellDemo.javaJava
class Payment {    int amount;
    Payment(int amount) {        this.amount = amount;    }}
class Upi extends Payment {    Upi(int amount) {        super(amount);    }}
class Card extends Payment {    Card(int amount) {        super(amount);    }}
class NetBanking extends Payment {    NetBanking(int amount) {        super(amount);    }}
public class ChainSmellDemo {    static int fee(Payment p) {        if (p instanceof Upi) {            return 0;        } else if (p instanceof Card) {            return p.amount * 2 / 100;        }        return 0;    }
    public static void main(String[] args) {        Payment[] list = { new Upi(1000), new Card(1000), new NetBanking(1000) };        for (Payment p : list) {            System.out.println(p.getClass().getSimpleName() + " fee: Rs. " + fee(p));        }    }}
Output
Upi fee: Rs. 0
Card fee: Rs. 20
NetBanking fee: Rs. 0

What this code does

  • NetBanking was added later, but nobody updated fee. The chain falls through and charges Rs. 0, with no error.
  • In a real app the same chain is often copied into receipts, refunds and reports, and each copy can be forgotten.
  • p.getClass().getSimpleName() gives the real class name as text, like Upi; it is used here only for printing.

Example 4 · After: each class decides its own fee

ChainFixDemo.javaJava
abstract class Payment {    int amount;
    Payment(int amount) {        this.amount = amount;    }
    abstract int fee();}
class Upi extends Payment {    Upi(int amount) {        super(amount);    }
    @Override    int fee() {        return 0;    }}
class Card extends Payment {    Card(int amount) {        super(amount);    }
    @Override    int fee() {        return amount * 2 / 100;    }}
class NetBanking extends Payment {    NetBanking(int amount) {        super(amount);    }
    @Override    int fee() {        return 10;    }}
public class ChainFixDemo {    public static void main(String[] args) {        Payment[] list = { new Upi(1000), new Card(1000), new NetBanking(1000) };        for (Payment p : list) {            System.out.println(p.getClass().getSimpleName() + " fee: Rs. " + p.fee());        }    }}
Output
Upi fee: Rs. 0
Card fee: Rs. 20
NetBanking fee: Rs. 10

What this code does

  • abstract int fee() forces every payment type to decide its fee: a new class that forgets it does not compile.
  • The caller just writes p.fee(); dynamic dispatch replaces the whole if chain.

Example 5 · Wrong inheritance replaced by composition

AddressDemo.javaJava
class Address {    String city;
    Address(String city) {        this.city = city;    }}
class BadCustomer extends Address {    String name;
    BadCustomer(String name, String city) {        super(city);        this.name = name;    }}
class Customer {    String name;    Address home;    Address office;
    Customer(String name, Address home, Address office) {        this.name = name;        this.home = home;        this.office = office;    }}
public class AddressDemo {    static void printLabel(Address a) {        System.out.println("Ship to: " + a.city);    }
    public static void main(String[] args) {        BadCustomer bad = new BadCustomer("Arjun", "Pune");        printLabel(bad);        Customer c = new Customer("Arjun", new Address("Pune"), new Address("Mumbai"));        printLabel(c.office);    }}
Output
Ship to: Pune
Ship to: Mumbai

What this code does

  • printLabel(bad) compiles because a BadCustomer is-an Address: nonsense that the type system now allows.
  • Customer has-an Address, so it can hold two of them, and only real addresses go to printLabel.

Fix: put an abstract method in the parent and let each class override it; the caller just writes p.fee().

Wrong inheritance is extends used only to reuse code when the is-a test fails, like class Customer extends Address. Fix: composition, a field, as in Composition vs inheritance (opens in a new tab).

instanceof is fine at the edges, for example in equals, or when you truly cannot change the classes. It is a smell when it decides behaviour that the classes could decide themselves.

Too much in one place: the god class

A god class is one huge class that holds most of a program's data and does most of its jobs, so every change touches it and its data easily gets out of step.

The classic case is a CollegeSystem with student marks, fee rules, report printing and SMS sending in one class. Try to describe a class in one sentence without "and": if you cannot, it has too many jobs.

CollegeSystem holds marks, fee due, printReport() and sendSms(): one class, four jobs. It is split into Student, FeeAccount, ReportPrinter and SmsSender, each with one job.

Example 6 · The god class, split by job

CollegeDemo.javaJava
class Student {    private final String name;    private final int marks;
    Student(String name, int marks) {        this.name = name;        this.marks = marks;    }
    String getName() {        return name;    }
    String grade() {        return marks >= 75 ? "Distinction" : marks >= 35 ? "Pass" : "Fail";    }}
class FeeAccount {    private int due;
    FeeAccount(int due) {        this.due = due;    }
    void pay(int amount) {        due -= Math.min(amount, due);    }
    int getDue() {        return due;    }}
class ReportPrinter {    void print(Student s, FeeAccount f) {        System.out.println(s.getName() + " | " + s.grade() + " | fee due Rs. " + f.getDue());    }}
class SmsSender {    void send(Student s, FeeAccount f) {        System.out.println("SMS to parent of " + s.getName() + ": fee due Rs. " + f.getDue());    }}
public class CollegeDemo {    public static void main(String[] args) {        Student s = new Student("Kavya", 81);        FeeAccount f = new FeeAccount(45000);        f.pay(30000);        new ReportPrinter().print(s, f);        new SmsSender().send(s, f);    }}
Output
Kavya | Distinction | fee due Rs. 15000
SMS to parent of Kavya: fee due Rs. 15000

What this code does

  • The old CollegeSystem held marks, fees, printing and SMS in one class. Each job is now one small class you can describe without "and".
  • A change to fee rules touches only FeeAccount; the printer can change format without touching marks or fees.

Fix: group the fields and methods by job, and move each group into its own small class; the main class then just connects them. In a code review, say it in three parts:

  • Name the smell: "This is a god class."
  • Say the risk: "A fee change could break report printing."
  • Give the fix: "Split it into Student, FeeAccount and ReportPrinter."

Next step

Check your understanding

12 quick questions