Design methods, not just setters
35 min · Beginner
Need help? Ask a tutor on WhatsApp (opens in a new tab)Good classes offer actions, not just setters. A bank account has deposit and withdraw, not setBalance. Each action knows the rules, so callers simply say what happened and the object keeps itself correct.
A setter is not always the right door
A real bank never lets you type your balance: you deposit or withdraw, and the bank works out the new balance. A setBalance setter lets any code type any number, and the history of what happened is lost.
acc.setBalance(1000000); // a setter: any code can type any number
acc.deposit(500); // events: the class works out the new balanceacc.withdraw(200);So for each field, ask how it really changes in life. If the answer is "through events", like a payment or a booking, write one method per event instead of a setter.
Tell the object; don’t ask and change
Two screens take money from one account, and the balance ends at Rs. -200: the rule lived in main. Tell, don't ask fixes it: tell the object what you want and let it decide with its own data.
Example 1 · Ask and change: the rule lives in main
class Account { private int balance;
public int getBalance() { return balance; } public void setBalance(int balance) { this.balance = balance; }}
public class AskDemo { public static void main(String[] args) { Account acc = new Account(); acc.setBalance(1000);
if (acc.getBalance() >= 700) { acc.setBalance(acc.getBalance() - 700); }
// another screen forgot the check acc.setBalance(acc.getBalance() - 500);
System.out.println("Balance: Rs. " + acc.getBalance()); }}Balance: Rs. -200
What this code does
- Every caller must remember the "enough balance" rule. The second one forgot, and the balance went negative.
setBalanceaccepts any number, so the class cannot protect itself.
Example 2 · Tell: deposit and withdraw keep the rules
class BankAccount { private String holder; private int balance;
public BankAccount(String holder) { this.holder = holder; }
public void deposit(int amount) { if (amount <= 0) { throw new IllegalArgumentException("Deposit must be positive"); } balance += amount; }
public void withdraw(int amount) { if (amount <= 0) { throw new IllegalArgumentException("Withdrawal must be positive"); } if (amount > balance) { throw new IllegalArgumentException("Not enough balance"); } balance -= amount; }
public int getBalance() { return balance; }}
public class TellDemo { public static void main(String[] args) { BankAccount acc = new BankAccount("Kavya"); acc.deposit(1000); acc.withdraw(700); try { acc.withdraw(500); } catch (IllegalArgumentException e) { System.out.println("Error: " + e.getMessage()); } System.out.println("Balance: Rs. " + acc.getBalance()); }}Error: Not enough balance Balance: Rs. 300
What this code does
- There is no
setBalance. The only ways to change the balance aredepositandwithdraw, and both check first. - No caller can forget the rule, because callers never do the maths themselves.
Asking for a value, deciding in main and writing it back spreads the rule over every caller; one of them forgets. Telling the object, acc.withdraw(500), keeps the rule in one place, inside the class.
Name methods after actions and report the result
Use verbs from the real world: deposit, withdraw, pay, book, cancel, markPresent. An action can fail, so it must tell the caller what happened.
public boolean book(int seats) { // a normal "no": return false if (seats <= 0 || seats > getSeatsLeft()) { return false; } booked = booked + seats; return true;}
public void deposit(int amount) { // a wrong value: throw if (amount <= 0) { throw new IllegalArgumentException("Amount must be positive"); } balance = balance + amount;}There are three common ways:
- Return
boolean:trueif done,falseif not. Good for normal "no" answers, like "no seats left". - Throw
IllegalArgumentException: the value itself is wrong, like a negative amount. - Throw
IllegalStateException: a built-in exception for "not allowed right now", like cancelling a ticket twice.
Private helpers keep public methods short
A UPI payment needs several checks: enough balance, and under the daily limit. Put each check in a small private helper with a clear name, like hasBalance(amount), so the public method reads like a list of steps.
Example 3 · A UPI wallet with private helpers
class UpiWallet { private int balance; private int spentToday; private int dailyLimit = 2000;
public UpiWallet(int balance) { this.balance = balance; }
private boolean hasBalance(int amount) { return amount <= balance; }
private boolean withinLimit(int amount) { return spentToday + amount <= dailyLimit; }
public boolean pay(String to, int amount) { if (!hasBalance(amount) || !withinLimit(amount)) { System.out.println("Declined: Rs. " + amount + " to " + to); return false; } balance -= amount; spentToday += amount; System.out.println("Paid Rs. " + amount + " to " + to); return true; }}
public class UpiDemo { public static void main(String[] args) { UpiWallet w = new UpiWallet(5000); w.pay("Chai shop", 40); w.pay("Bookstore", 1500); boolean ok = w.pay("Phone shop", 900); System.out.println("Last payment done? " + ok); }}Paid Rs. 40 to Chai shop Paid Rs. 1500 to Bookstore Declined: Rs. 900 to Phone shop Last payment done? false
What this code does
- Each rule is a small private helper with a clear name, so
payreads like a sentence. payreturnsfalsefor a declined payment: a normal "no", not a programming mistake. 40 + 1500 + 900 would cross the Rs. 2000 limit.
Helpers are not part of the public menu. You can split, rename or remove them later, and no caller will notice.
Designing a class from a requirement
A cinema show has 10 seats and must never be overbooked. Sort each piece of the requirement into data, fixed values, events, rules and answers you can work out; each kind has its place in the class.
Example 4 · Booking seats with no overbooking
class Show { private String movie; private int capacity; private int booked;
public Show(String movie, int capacity) { this.movie = movie; this.capacity = capacity; }
public boolean book(int seats) { if (seats <= 0 || seats > getSeatsLeft()) { return false; } booked += seats; return true; }
public void cancel(int seats) { if (seats <= 0 || seats > booked) { throw new IllegalArgumentException("Cannot cancel " + seats + " seats"); } booked -= seats; }
public int getSeatsLeft() { return capacity - booked; }}
public class ShowDemo { public static void main(String[] args) { Show s = new Show("Jawan", 10); System.out.println("Book 6: " + s.book(6)); System.out.println("Book 5: " + s.book(5)); s.cancel(2); System.out.println("Book 5: " + s.book(5)); System.out.println("Seats left: " + s.getSeatsLeft()); }}Book 6: true Book 5: false Book 5: true Seats left: 1
What this code does
getSeatsLeft()is computed fromcapacityandbooked, so it is always right.bookuses it to refuse overbooking.- Callers only
bookandcancel. There is nosetBooked, so nobody can make the count wrong.
Example 5 · A ticket can be cancelled only once
class Ticket { private String pnr; private int fare; private boolean cancelled;
public Ticket(String pnr, int fare) { this.pnr = pnr; this.fare = fare; }
public int cancel() { if (cancelled) { throw new IllegalStateException("Ticket " + pnr + " is already cancelled"); } cancelled = true; return fare / 2; // 50% refund }
public boolean isCancelled() { return cancelled; }}
public class CancelDemo { public static void main(String[] args) { Ticket t = new Ticket("8812", 1200); System.out.println("Refund: Rs. " + t.cancel()); try { System.out.println("Refund: Rs. " + t.cancel()); } catch (IllegalStateException e) { System.out.println("Error: " + e.getMessage()); } }}Refund: Rs. 600 Error: Ticket 8812 is already cancelled
What this code does
- The object remembers its own state in
cancelled. A secondcancelis not allowed in that state, so it throwsIllegalStateException. - With a plain
setCancelled(true)setter, the refund rule could be skipped or done twice. The action method keeps both together.
The same sorting works for any class:
- Data →
privatefields. - Values that never change (an account number) → set in the constructor, getter only.
- Things that happen (pay, book, cancel) → public methods named as verbs.
- Rules (no overbooking, Rs. 2000 a day) → checks inside those methods, in private helpers.
- Answers you can work out (seats left) → computed getters.
- Everything else stays
private.
Find the bug
Find the action-method bug
Select the line that is wrong.
The balance must never go below 0.
Round 1 of 4Next step
Check your understanding
12 quick questions