These are the notes for Low-Level Design (LLD) episode 6, the first episode of the object-oriented design block. We build a metro smart card (the card you tap at the station gate) and break it again and again until we have invented every rule that keeps it safe: object-oriented programming (state and behaviour together), encapsulation, invariants, information hiding, the getters and setters debate, tell, don't ask, anemic vs rich domain models, immutable objects, defensive copying and value objects. Every program was run with javac Main.java && java -cp . Main (Java 21), the same way the SyntaxPilot compiler runs it; outputs and error messages are real.
1. What object-oriented programming is
A metro card knows things (its owner, its balance of Rs 100) and does things (pays a fare at the gate, gets recharged at the counter).
| Word | Meaning | On the metro card | In Java |
|---|---|---|---|
| State | What an object knows at a given moment | owner = Priya, balance = 100 | fields |
| Behaviour | What an object can do | pay a fare, get recharged | methods |
| Object-oriented programming (OOP) | Building a program out of objects, each keeping its state and behaviour together in one place | the card checks its own balance | a class with fields + methods |
OOP has four classic pillars: encapsulation (this episode), abstraction (episode 7), inheritance (episode 8) and polymorphism (episode 9).
2. The problem: public fields
class MetroCard {
public String owner;
public int balance;
}
public class Main {
public static void main(String[] args) {
MetroCard card = new MetroCard();
card.owner = "Priya";
card.balance = 100;
card.balance -= 60; // to MG Road
card.balance -= 60; // and back home
System.out.println(card.owner + ": Rs " + card.balance);
card.balance = 100000; // "free recharge"
System.out.println(card.owner + ": Rs " + card.balance);
}
}
Priya: Rs -20
Priya: Rs 100000
Two rides of Rs 60 on a Rs 100 card leave it at Rs -20, and any code anywhere can "recharge" it to one lakh with one assignment. Both compiled and ran without a single error. The data is open to everyone, so the card has no say in what happens to its own balance.
3. Encapsulation
Real-life example: at the metro recharge counter, the cash drawer is behind glass (you can't reach in), you talk through the counter window ("recharge Rs 200, please"), and the clerk checks first (no fake notes, no minus amounts).
Encapsulation = put the data and the methods that work on it inside one capsule (the class), and let the outside change the data only through those methods. The methods are the guards.
Step 1: make the field private (only code inside the class can touch it). With the same main:
Main.java:9: error: balance has private access in MetroCard
card.balance = 100;
^
Main.java:10: error: balance has private access in MetroCard
card.balance -= 60; // to MG Road
^
Main.java:11: error: balance has private access in MetroCard
card.balance -= 60; // and back home
^
Main.java:12: error: balance has private access in MetroCard
System.out.println(card.owner + ": Rs " + card.balance);
^
Main.java:13: error: balance has private access in MetroCard
card.balance = 100000; // "free recharge"
^
Main.java:14: error: balance has private access in MetroCard
System.out.println(card.owner + ": Rs " + card.balance);
^
6 errors
Step 2: give the class a "counter window": a constructor and methods that check.
class MetroCard {
private final String owner;
private int balance;
MetroCard(String owner, int balance) {
this.owner = owner;
this.balance = balance;
}
boolean pay(int fare) {
if (fare > balance) return false;
balance -= fare;
return true;
}
void recharge(int amount) {
if (amount <= 0)
throw new IllegalArgumentException("Bad: " + amount);
balance += amount;
}
int balance() { return balance; }
}
public class Main {
public static void main(String[] args) {
MetroCard card = new MetroCard("Priya", 100);
System.out.println(card.pay(60) + " " + card.pay(60));
System.out.println("Balance: Rs " + card.balance());
card.recharge(-500);
}
}
true false
Balance: Rs 40
Exception in thread "main" java.lang.IllegalArgumentException: Bad: -500
at MetroCard.recharge(Main.java:15)
at Main.main(Main.java:25)
payrefuses a fare larger than the balance and returnsfalse: the second ride is refused, the balance stays at Rs 40.rechargethrows anIllegalArgumentException(the standard exception for a bad argument) for zero or negative amounts.balance()lets others read the balance, but not write it.
4. Invariants
An invariant is a rule that must be true for an object at every moment of its life. Here: the balance is never below zero. Like a lift's "maximum 8 people": the sensor never lets a ninth person in, and it checks at the door.
Our methods were guarded, but the constructor (the "door") was not:
MetroCard card = new MetroCard("Priya", -900);
System.out.println("Balance: Rs " + card.balance());
Balance: Rs -900
Fix: the constructor checks too.
MetroCard(String owner, int balance) {
if (balance < 0)
throw new IllegalArgumentException("Negative: " + balance);
this.owner = owner;
this.balance = balance;
}
Exception in thread "main" java.lang.IllegalArgumentException: Negative: -900
at MetroCard.<init>(Main.java:6)
at Main.main(Main.java:24)
<init> is the name Java uses for a constructor in stack traces. Rule: the constructor makes the invariants true, every method keeps them true. Encapsulation is the tool that makes this possible: if a field is public, nobody can promise anything about it.
5. Information hiding
You don't know how your card's chip stores the balance (rupees? paise? a list of trips?), and you don't need to. Information hiding = hiding how something works, so the outside depends only on what it does. Then the inside can change freely.
| Encapsulation | Information hiding | |
|---|---|---|
| What it is | A mechanism: bundle data + methods, guard the data with private |
A goal: hide design decisions that may change |
| Question it answers | "Who may touch this data?" | "What must callers know?" |
Example: the card switches from int rupees to long paise inside, to handle a 50-paise half fare. Callers still call pay(...) and balance(); nothing outside changes.
class MetroCard {
private long paise; // was: private int balance (rupees)
MetroCard(int rupees) {
if (rupees < 0) throw new IllegalArgumentException("Negative: " + rupees);
paise = rupees * 100L;
}
boolean pay(int fare) {
if (fare * 100L > paise) return false;
paise -= fare * 100L;
return true;
}
void payDiscounted(int fare) { paise -= fare * 50L; } // half fare, can be 50 paise
int balance() { return (int) (paise / 100); }
}
public class Main {
public static void main(String[] args) {
MetroCard card = new MetroCard(100);
System.out.println(card.pay(60) + ", Rs " + card.balance());
card.payDiscounted(15);
System.out.println("Rs " + card.balance());
}
}
true, Rs 40
Rs 32
(Rs 40 minus a half fare of Rs 7.50 is Rs 32.50; balance() still returns whole rupees, so it shows 32.) Hide whatever is likely to change: a storage format, a tax rule, a third-party library.
6. The getters and setters debate
A getter is a method that returns a field (getBalance()); a setter is a method that sets one (setBalance(int)). Many tutorials say "make every field private, then add a getter and a setter for each". Watch:
class MetroCard {
private int balance;
MetroCard(int balance) { this.balance = balance; }
public int getBalance() { return balance; }
public void setBalance(int balance) { this.balance = balance; }
}
public class Main {
public static void main(String[] args) {
MetroCard card = new MetroCard(40);
int fare = 60;
card.setBalance(card.getBalance() - fare);
System.out.println("Balance: Rs " + card.getBalance());
}
}
Balance: Rs -20
The field is private, yet the balance is Rs -20 again: setBalance accepts any number. A blind setter is a public field in disguise.
| Side | Argument |
|---|---|
| "Getters and setters are fine" | Frameworks (JPA, JSON mappers, JavaBeans tools) expect them; simple data holders need nothing more; you can add checks later inside the setter |
| "Setters break encapsulation" | Every caller does the object's maths and can forget a check; the class's rules are spread across the codebase |
Practical answer: getters are often fine (prefer returning copies or immutable values). Do not add setters by reflex. Ask what the caller really wants to do, and write a method with that meaning: pay(fare), recharge(amount), block().
7. Tell, don't ask
Real-life example: in an auto, you could ask the driver "how much fuel? which gear? now turn left, now brake" (doing his job), or tell him "MG Road, please" (he knows the road and his own fuel).
Tell, don't ask = don't ask an object for its data so you can make a decision for it; tell it what you want and let it decide using its own data.
The asking style: the gates do the card's maths, and one gate forgets the check.
class MetroCard {
private int balance;
MetroCard(int balance) { this.balance = balance; }
int getBalance() { return balance; }
void setBalance(int b) { balance = b; }
}
class EntryGate {
void tap(MetroCard c, int fare) {
if (c.getBalance() >= fare) {
c.setBalance(c.getBalance() - fare);
System.out.println("Entry: open");
} else System.out.println("Entry: low balance");
}
}
class ParkingGate {
void tap(MetroCard c, int fee) {
c.setBalance(c.getBalance() - fee);
System.out.println("Parking: open");
}
}
public class Main {
public static void main(String[] args) {
MetroCard card = new MetroCard(50);
new EntryGate().tap(card, 60);
new ParkingGate().tap(card, 80);
System.out.println("Balance: Rs " + card.getBalance());
}
}
Entry: low balance
Parking: open
Balance: Rs -30
The telling style: the rule lives in pay, and one Gate class only tells the card what to do.
class MetroCard {
private int balance;
MetroCard(int balance) { this.balance = balance; }
boolean pay(int fare) {
if (fare > balance) return false;
balance -= fare;
return true;
}
int balance() { return balance; }
}
class Gate {
private final String name;
Gate(String name) { this.name = name; }
void tap(MetroCard c, int fare) {
if (c.pay(fare)) System.out.println(name + ": open");
else System.out.println(name + ": low balance");
}
}
public class Main {
public static void main(String[] args) {
MetroCard card = new MetroCard(50);
new Gate("Entry").tap(card, 60);
new Gate("Parking").tap(card, 80);
new Gate("Exit").tap(card, 30);
System.out.println("Balance: Rs " + card.balance());
}
}
Entry: low balance
Parking: low balance
Exit: open
Balance: Rs 20
No gate can skip a rule it never had to write.
8. Anemic vs rich domain model
- Domain: the real-world area the software is about (here, metro travel).
- Domain model: the classes that represent it (
MetroCard,Gate,Ticket). - Anemic domain model: the domain classes only hold data (fields + getters/setters) and all rules live in other "service" classes. Anemic means weak. Like a paper file that every clerk edits by hand.
- Rich domain model: the domain classes hold their data and the rules about it. Like a smart card that checks its own rules.
| Anemic | Rich | |
|---|---|---|
| MetroCard | getBalance, setBalance |
pay, recharge, balance |
| Gates | each repeats the checks | card.pay(fare) |
| Rule "min balance Rs 10" | edit every gate | edit MetroCard.pay once |
| Risk | one copy forgets the rule | the object guards itself |
Plain data carriers (a request sent over the network, a row read from a file) can stay simple, but the core of a design (what interviewers judge in a machine-coding round) should be rich.
9. Immutable objects
A mutable ticket can be edited after it is paid for:
class Ticket {
String from, to;
int fare;
Ticket(String from, String to, int fare) {
this.from = from; this.to = to; this.fare = fare;
}
}
public class Main {
public static void main(String[] args) {
Ticket t = new Ticket("Majestic", "MG Road", 20);
t.to = "Whitefield"; // changed after paying!
System.out.println(t.from + " -> " + t.to + ", Rs " + t.fare);
}
}
Majestic -> Whitefield, Rs 20
An immutable object is one whose state can never change after it is created, like a printed QR ticket. Recipe:
- Make the class
final(nobody can extend it and add changing parts). - Make every field
final(set once, in the constructor) and, in real code,private. - No setters. A "change" returns a new object (often named
withX). - If a field holds a mutable object (a list, an array), copy it (section 10).
final class Ticket {
final String from, to;
final int fare;
Ticket(String from, String to, int fare) {
this.from = from; this.to = to; this.fare = fare;
}
String to() { return to; }
Ticket withTo(String newTo, int newFare) {
return new Ticket(from, newTo, newFare);
}
public String toString() {
return from + " -> " + to + ", Rs " + fare;
}
}
public class Main {
public static void main(String[] args) {
Ticket t = new Ticket("Majestic", "MG Road", 20);
t.to = "Whitefield";
System.out.println(t);
}
}
Main.java:18: error: cannot assign a value to final variable to
t.to = "Whitefield";
^
1 error
With withTo instead of the assignment:
Ticket longer = t.withTo("Whitefield", 50);
System.out.println(t);
System.out.println(longer);
Majestic -> MG Road, Rs 20
Majestic -> Whitefield, Rs 50
Benefits: invariants are checked once (in the constructor) and stay true forever; it is safe to share with any code, even code running at the same time on other threads; it is safe as a HashMap key. Java's String, Integer and records are immutable.
10. Defensive copying
private final is not enough when the field holds a mutable object:
import java.util.*;
class MetroCard {
private final List<String> trips;
MetroCard(List<String> trips) { this.trips = trips; }
List<String> trips() { return trips; }
}
public class Main {
public static void main(String[] args) {
List<String> start = new ArrayList<>();
start.add("Majestic->MG Road");
MetroCard card = new MetroCard(start);
start.add("FAKE: free ride");
System.out.println(card.trips());
card.trips().clear();
System.out.println(card.trips());
}
}
[Majestic->MG Road, FAKE: free ride]
[]
A variable holding an object holds a reference (the object's address), not the object itself. final only stops the reference from changing; the list it points to is shared with main, which can still edit it. Two variables pointing at the same object are called aliases.
Defensive copying = making your own copy of mutable data at the boundary of your object, so no outsider shares it. Like making a photocopy of papers you're given, and handing out sealed copies instead of your originals.
import java.util.*;
class MetroCard {
private final List<String> trips;
MetroCard(List<String> trips) { this.trips = new ArrayList<>(trips); }
List<String> trips() { return List.copyOf(trips); }
}
public class Main {
public static void main(String[] args) {
List<String> start = new ArrayList<>();
start.add("Majestic->MG Road");
MetroCard card = new MetroCard(start);
start.add("FAKE: free ride");
System.out.println(card.trips());
card.trips().clear();
}
}
[Majestic->MG Road]
Exception in thread "main" java.lang.UnsupportedOperationException
at java.base/java.util.ImmutableCollections.uoe(ImmutableCollections.java:142)
at java.base/java.util.ImmutableCollections$AbstractImmutableCollection.clear(ImmutableCollections.java:149)
at Main.main(Main.java:15)
- Copy in:
new ArrayList<>(trips)in the constructor. - Copy out:
List.copyOf(trips)returns an unmodifiable copy; changing it throwsUnsupportedOperationException. (Collections.unmodifiableList(trips)returns a read-only view instead: cheaper, but it shows later changes made inside the card.) - Or store immutable things to begin with (a
List.copyOflist, records, Strings).
11. Value objects
Money as a plain int:
public class Main {
public static void main(String[] args) {
int fare = 60;
int discount = 100; // festival offer, typed wrong
int toPay = fare - discount;
System.out.println("Charge: Rs " + toPay);
int a = 60, b = 6000; // rupees? paise? who knows
System.out.println(a + b);
}
}
Charge: Rs -40
6060
A Rs 100 discount on a Rs 60 fare charges Rs -40, and rupees + paise add up to 6060. An int doesn't know it's money.
Real-life example: any Rs 100 note is as good as any other (equal by value), but your metro card is yours (it has a card number). So:
- Entity: an object with an identity that stays the same while its state changes (a metro card, a user, an order). Two cards with the same balance are still two cards.
- Value object: a small object defined only by its value (money, a distance, a date range, a location). It is immutable, equal when the values are equal, and validates itself.
record Money(int paise) {
Money {
if (paise < 0)
throw new IllegalArgumentException("Negative: " + paise);
}
static Money rupees(int r) { return new Money(r * 100); }
Money minus(Money other) { return new Money(paise - other.paise); }
public String toString() {
return String.format("Rs %d.%02d", paise / 100, paise % 100);
}
}
public class Main {
public static void main(String[] args) {
Money fare = Money.rupees(60);
System.out.println(fare + " " + fare.equals(Money.rupees(60)));
System.out.println(fare.minus(Money.rupees(15)));
System.out.println(fare.minus(Money.rupees(100)));
}
}
Rs 60.00 true
Rs 45.00
Exception in thread "main" java.lang.IllegalArgumentException: Negative: -4000
at Money.<init>(Main.java:4)
at Money.minus(Main.java:7)
at Main.main(Main.java:17)
Storing paise means rupees and paise can never be mixed; the compact constructor (episode 3) rejects negative money; rupees(...) is a static factory method (a static method that creates an object); minus returns a new Money. The Rs -40 charge can no longer happen.
The class diagram
Gate «entity» MetroCard «value object» Money
- name: String - - > - owner: String ────> paise: int
+ tap(card, fare) - balance: Money + minus(Money): Money
(tells: pay()) - trips: List<String> ^
+ pay(fare): boolean |
+ recharge(amount) «immutable» Ticket
+ trips(): List «copy» from, to: String
fare: Money
+ withTo(...): Ticket
- = private, + = public; the dashed arrow is a dependency (Gate uses MetroCard); solid arrows are associations (a field of that type).
Common mistakes
| Mistake | Exact message | Why | Fix |
|---|---|---|---|
| Assigning a private field from outside | error: balance has private access in MetroCard |
Only the class may touch it | Call a method: card.recharge(200) |
| A public setter with no checks | no error: Balance: Rs -20 |
A blind setter is a public field in disguise | Methods with meaning: pay, recharge |
| Checking only in methods, not in the constructor | no error: Balance: Rs -900 |
The invariant is broken at birth | Validate in the constructor |
| Passing a bad value to a guarded method | java.lang.IllegalArgumentException: Bad: -500 |
The method rejects it (good!) | Pass a valid value, or handle the exception |
Assigning a final field |
error: cannot assign a value to final variable to |
Immutable fields are set once | Return a new object: t.withTo(...) |
| Returning / storing your private list | no error: history changed from outside | Callers share the same list | new ArrayList<>(in), List.copyOf(out) |
Modifying a List.copyOf list |
java.lang.UnsupportedOperationException |
It is unmodifiable | Ask the owner object to make the change |
Money as a raw int |
no error: Charge: Rs -40, 6060 |
An int doesn't know its unit or rules | A value object: record Money(int paise) |
Mini project
Make the card production-ready: a card number (its identity), the balance as Money, a minimum balance of Rs 10 enforced in exactly one place, block() so a blocked card refuses every payment, and a trip history that outsiders can read but not change.
Solution
import java.util.*;
record Money(int paise) {
Money {
if (paise < 0) throw new IllegalArgumentException("Negative: " + paise);
}
static Money rupees(int r) { return new Money(r * 100); }
Money plus(Money o) { return new Money(paise + o.paise); }
Money minus(Money o) { return new Money(paise - o.paise); }
boolean lessThan(Money o) { return paise < o.paise; }
public String toString() { return String.format("Rs %d.%02d", paise / 100, paise % 100); }
}
class MetroCard {
private static final Money MIN_BALANCE = Money.rupees(10);
private final String number;
private Money balance;
private boolean blocked;
private final List<String> trips = new ArrayList<>();
MetroCard(String number, Money start) {
this.number = Objects.requireNonNull(number);
this.balance = Objects.requireNonNull(start);
}
boolean pay(Money fare, String trip) {
if (blocked) return false;
if (balance.lessThan(fare.plus(MIN_BALANCE))) return false;
balance = balance.minus(fare);
trips.add(trip);
return true;
}
void recharge(Money amount) {
if (amount.paise() == 0) throw new IllegalArgumentException("Recharge must be more than zero");
balance = balance.plus(amount);
}
void block() { blocked = true; }
Money balance() { return balance; }
List<String> trips() { return List.copyOf(trips); }
}
public class Main {
public static void main(String[] args) {
MetroCard card = new MetroCard("4521-0099", Money.rupees(100));
System.out.println(card.pay(Money.rupees(60), "Majestic->MG Road") + " " + card.balance());
System.out.println(card.pay(Money.rupees(35), "MG Road->Indiranagar") + " " + card.balance());
card.recharge(Money.rupees(200));
System.out.println(card.pay(Money.rupees(35), "MG Road->Indiranagar") + " " + card.balance());
card.block();
System.out.println(card.pay(Money.rupees(20), "Indiranagar->MG Road") + " " + card.balance());
System.out.println(card.trips());
}
}
true Rs 40.00
false Rs 40.00
true Rs 205.00
false Rs 205.00
[Majestic->MG Road, MG Road->Indiranagar]
Objects.requireNonNull(x) throws a NullPointerException right away if x is null, so a card can never be created without a number or a balance. The minimum-balance rule is one line in pay; no gate knows it exists.
Practice
- A
Studentclass haspublic int marks;. Name two invariants you would protect, and how.
Solution
0 <= marks <= 100, and marks can't change after results are published. Make marks private, validate it in the constructor and in a method like updateMarks(int), and add a publish() method after which updateMarks throws.
- Rewrite in tell-don't-ask style:
if (order.getStatus() == Status.PLACED) order.setStatus(Status.CANCELLED);
Solution
order.cancel(); with the rule inside Order: void cancel() { if (status != Status.PLACED) throw new IllegalStateException("Can't cancel: " + status); status = Status.CANCELLED; }
- A class has
private final Date issuedOn;andDate issuedOn() { return issuedOn; }. Is it immutable?
Solution
No. java.util.Date is mutable, so a caller can do t.issuedOn().setTime(0). Copy in and out (new Date(d.getTime())), or better, use the immutable java.time.LocalDate.
- Entity or value object: (a) a bank account, (b) a PIN code, (c) a delivery partner, (d) a distance of 5 km?
Solution
(a) entity (account number), (b) value object, (c) entity (partner id), (d) value object.
Quick quiz
A wallet must never go below zero. Which design protects that rule?
public int balanceprivatebalance +setBalance(int)privatebalance +spend(int)that checks- A
WalletServicethat checks, + get/set on the wallet
Answer
private balance + spend(int) that checks. The rule lives inside the object. A blind setter or an outside service (an anemic model) lets any caller skip the check.
Interview questions
- What is encapsulation? Bundling data with the methods that operate on it and restricting direct access to the data, so every change goes through methods that protect the object's invariants.
- Encapsulation vs information hiding? Encapsulation is the mechanism (private fields + methods); information hiding is the design goal (hide decisions likely to change so callers depend only on behaviour).
- Are getters and setters encapsulation? Not by themselves. A setter that accepts anything is as open as a public field. Prefer intention-revealing methods.
- What is "tell, don't ask"? Ask objects to do work, not to hand over data so you can do the work for them; it keeps rules next to the data.
- Anemic vs rich domain model? Anemic: data-only classes plus service classes holding the logic. Rich: domain objects hold their own behaviour and rules.
- How do you make a class immutable in Java?
finalclass,private finalfields, no setters, validate in the constructor, defensive copies of mutable fields, "with" methods return new objects. - Why are immutable objects useful? Thread-safe without locks, safe to share and cache, safe as map keys, invariants checked once.
- Value object vs entity? A value object is equal by value and immutable (Money); an entity has an identity that persists while its state changes (MetroCard).
Glossary
| Term | Meaning, with an example |
|---|---|
| Object-oriented programming (OOP) | Building programs from objects that keep their state and behaviour together. A MetroCard with a balance and pay() |
| Object | One thing made from a class, with its own field values. new MetroCard("Priya", 100) |
| State | What an object knows right now, stored in fields. balance = 40 |
| Behaviour | What an object can do, written as methods. pay(60) |
| Field | A variable that belongs to an object. private int balance; |
| Method | A named block of code an object can run. recharge(200) |
| Pillars of OOP | Encapsulation, abstraction, inheritance, polymorphism |
| Encapsulation | Bundling data and its methods in a class and allowing changes only through those methods |
private |
Access modifier: only code inside the same class can use it |
public |
Access modifier: any code can use it |
| Constructor | Special method that runs when an object is created with new |
| Exception | An object that reports a problem and stops normal flow. IllegalArgumentException |
throw |
Stops the method and reports an exception |
| IllegalArgumentException | Standard exception for a bad argument. recharge(-500) |
| Invariant | A rule that is true for an object at every moment of its life. "balance >= 0" |
<init> |
Java's internal name for a constructor in stack traces |
| Information hiding | Hiding how something works so callers depend only on what it does. Rupees → paise inside, callers unchanged |
| Getter | A method that returns a field. getBalance() |
| Setter | A method that sets a field. setBalance(int) |
| Getters and setters debate | Whether a getter/setter for every field is good practice; answer: getters often fine, setters only with meaning and checks |
| Tell, don't ask | Tell objects what to do instead of asking for their data and deciding for them. card.pay(fare) |
| Domain | The real-world area the software is about. Metro travel |
| Domain model | The classes that represent the domain. MetroCard, Gate, Ticket |
| Anemic domain model | Domain classes with only data; rules live in other classes |
| Rich domain model | Domain classes that hold their data and their rules |
| Service class | A class that holds logic but little or no state. EntryGate doing the card's maths |
| Immutable object | An object whose state never changes after creation. A printed QR ticket, String |
| Mutable | Can be changed after creation. ArrayList |
final (field) |
Can be assigned only once |
final (class) |
Cannot be extended by another class |
| "with" method | Returns a new object with one value changed. t.withTo("Whitefield", 50) |
| Reference | The address of an object held by a variable; two variables can hold the same reference |
| Alias | Two variables pointing at the same object |
| Defensive copying | Copying mutable data on the way into and out of an object so no outsider shares it |
List.copyOf |
Makes an unmodifiable copy of a list |
| Unmodifiable collection | A collection that throws UnsupportedOperationException when you try to change it |
| UnsupportedOperationException | Thrown when an operation isn't allowed, like clear() on List.copyOf(...) |
| Value object | A small immutable object defined only by its value, equal by value, self-validating. Money |
| Entity | An object with an identity that persists while its state changes. A metro card with card number 4521-0099 |
| Record | A class that just carries values, with equals, hashCode, toString generated (episode 3) |
| Compact constructor | A record constructor without a parameter list, used to validate |
| Static factory method | A static method that creates an object. Money.rupees(60) |
| Paise | 1/100 of a rupee; storing money in the smallest unit avoids decimals |
Objects.requireNonNull |
Throws NullPointerException at once if the value is null |
| Dependency (UML) | Dashed arrow: one class uses another |
| Association (UML) | Solid line: one class holds a field of another's type |
Summary
- OOP keeps state (fields) and behaviour (methods) together in objects.
- Encapsulation: private data, changed only through methods; those methods protect invariants (the constructor makes them true, methods keep them true).
- Information hiding: hide what is likely to change so the inside can change without breaking callers.
- Don't add setters by reflex; write methods with meaning and tell, don't ask. Prefer a rich domain model over an anemic one.
- Immutable objects: final class, final fields, no setters, changes return new objects.
- Defensive copying: copy mutable data in and out.
- Value objects like
Moneyare immutable, validated and equal by value; entities have an identity.
Next episode: OOP 2: abstraction and programming to an interface.