SyntaxPilot
Courses/Low-Level Design/Lesson 45
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 45 of 90

Beyond GoF: Null Object, Repository, Specification and MVC

Null Object patternRepository patternDAOUnit of WorkSpecification patterncomposable business rulesService layerDTOmapperMVCMVPMVVMlayered architecture controller service repository

These are the notes for Low-Level Design (LLD) episode 45. With the Interpreter pattern we finished the 23 classic Gang of Four patterns (from the 1994 book Design Patterns, episode 21). Real business apps use a second family of patterns every day: Null Object, Repository (and the older DAO), Specification, Unit of Work, the service layer, DTOs and mappers, the controller → service → repository layers, and MVC / MVP / MVVM for screens. We invent each one as the fix for a real problem in Asha's cafe app. Every program was actually run with javac Main.java && java -cp . Main (Java 21). Outputs are real.

1. Null Object: the walk-in customer

At the counter the cashier types a phone number; members get a discount (10% with 100+ points, else 5%). find returns null when the phone isn't in the book.

import java.util.*;
class Customer {
    private final String name; private final int points;
    Customer(String name, int points) { this.name = name; this.points = points; }
    int discountPercent() { return points >= 100 ? 10 : 5; }    // loyal customers get more
    String greeting() { return "Welcome back, " + name + "!"; }
}
class CustomerBook {
    private final Map<String, Customer> byPhone = new HashMap<>();
    CustomerBook() { byPhone.put("98450", new Customer("Priya", 120)); }
    Customer find(String phone) { return byPhone.get(phone); }    // null if not found
}
public class Main {
    static void bill(CustomerBook book, String phone, int total) {
        Customer c = book.find(phone);
        System.out.println(c.greeting() + " Pay: " + total * (100 - c.discountPercent()) / 100);
    }
    public static void main(String[] args) {
        CustomerBook book = new CustomerBook();
        bill(book, "98450", 500);                                   // a known customer
        bill(book, "11111", 500);                                   // a walk-in customer
    }
}

Output (real):

Welcome back, Priya! Pay: 450
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "Customer.greeting()" because "<local3>" is null
    at Main.bill(Main.java:16)
    at Main.main(Main.java:21)

<local3> is how Java names the variable c when the code wasn't compiled with debug names (javac -g). null means no object, so it has no methods. The usual patch, an if (c == null) before every use, must be remembered by every caller, forever.

The fix: an object that does nothing, safely

Billing counters already do this: no account? Bill it as a walk-in.

import java.util.*;
interface Customer { int discountPercent(); String greeting(); }
record Member(String name, int points) implements Customer {
    public int discountPercent() { return points >= 100 ? 10 : 5; }
    public String greeting() { return "Welcome back, " + name + "!"; }
}
final class Guest implements Customer {                          // the null object
    static final Guest INSTANCE = new Guest();
    private Guest() { }
    public int discountPercent() { return 0; }                   // does nothing, safely
    public String greeting() { return "Welcome!"; }
}
class CustomerBook {
    private final Map<String, Customer> byPhone = new HashMap<>(Map.of("98450", new Member("Priya", 120)));
    Customer find(String phone) { return byPhone.getOrDefault(phone, Guest.INSTANCE); }   // never null
}
public class Main {
    static void bill(CustomerBook book, String phone, int total) {
        Customer c = book.find(phone);                           // no null check needed
        System.out.println(c.greeting() + " Pay: " + total * (100 - c.discountPercent()) / 100);
    }
    public static void main(String[] args) {
        CustomerBook book = new CustomerBook();
        bill(book, "98450", 500);
        bill(book, "11111", 500);
    }
}

Output (real):

Welcome back, Priya! Pay: 450
Welcome! Pay: 500

Null Object pattern: instead of null, return a real object with harmless do-nothing behaviour (Guest: 0% discount, a plain greeting), so callers treat everyone the same. One shared instance is enough because it holds no data.

Use it only when "do nothing" is truly correct. If a missing object is a real problem (a payment to an unknown account), return an Optional (episode 5) or throw an exception.

2. Repository: the storeroom keeper

In a big kitchen In code
The cook asks "two kilos of rice" Business code asks for orders, not database rows
The storeroom keeper knows every shelf Repository: looks like a collection of objects (save, find)
Shelves can be rearranged any time Storage: a map today, a database tomorrow
import java.util.*; import java.util.function.Predicate;
record Order(int id, String city, int total, boolean veg) { }
interface OrderRepository {                                      // looks like a collection
    void save(Order o);
    Optional<Order> findById(int id);
    List<Order> findByCity(String city);
    List<Order> findByMinTotal(int min);
    List<Order> findVeg();
}
class InMemoryOrderRepository implements OrderRepository {        // storage details live here
    private final Map<Integer, Order> rows = new LinkedHashMap<>();
    public void save(Order o) { rows.put(o.id(), o); }
    public Optional<Order> findById(int id) { return Optional.ofNullable(rows.get(id)); }
    private List<Order> where(Predicate<Order> p) { return rows.values().stream().filter(p).toList(); }
    public List<Order> findByCity(String c) { return where(o -> o.city().equals(c)); }
    public List<Order> findByMinTotal(int m) { return where(o -> o.total() >= m); }
    public List<Order> findVeg() { return where(Order::veg); }
}
public class Main {
    public static void main(String[] args) {
        OrderRepository repo = new InMemoryOrderRepository();
        repo.save(new Order(1, "Pune", 650, true));   repo.save(new Order(2, "Pune", 300, false));
        repo.save(new Order(3, "Delhi", 900, true));  repo.save(new Order(4, "Pune", 1200, true));
        System.out.println(repo.findById(3));
        System.out.println(repo.findByCity("Pune"));
        System.out.println(repo.findBigVegOrdersInPune());           // the manager's new question
    }
}

Output (real):

Main.java:26: error: cannot find symbol
        System.out.println(repo.findBigVegOrdersInPune());           // the manager's new question
                               ^
  symbol:   method findBigVegOrdersInPune()
  location: variable repo of type OrderRepository
1 error

The repository works, but every new question ("big veg orders in Pune", "non-veg orders in Delhi over 1000") needs a new method on the interface and on every implementation: method explosion.

Fowler's definition: a Repository "Mediates between the domain and data mapping layers using a collection-like interface for accessing domain objects." A domain object is an object from the real-world problem, like Order or Customer.

Repository vs DAO

DAO (Data Access Object) Repository
Shaped like The database: one class per table The business: a collection of domain objects
Methods insertRow, updateRow, selectByColumn save(order), findById(3), findAll(spec)
Speaks Rows and columns Orders and customers
Relationship Can be used inside a repository Can use one or more DAOs

3. Specification: business rules you combine

import java.util.*;
interface Spec<T> { boolean isSatisfiedBy(T t);                  // one business rule
    default Spec<T> and(Spec<T> o) { return t -> isSatisfiedBy(t) && o.isSatisfiedBy(t); }
    default Spec<T> or(Spec<T> o)  { return t -> isSatisfiedBy(t) || o.isSatisfiedBy(t); }
    default Spec<T> not()          { return t -> !isSatisfiedBy(t); }
}
record Order(int id, String city, int total, boolean veg) { }
class OrderSpecs {                                               // small, named rules
    static Spec<Order> inCity(String c) { return o -> o.city().equals(c); }
    static Spec<Order> totalAtLeast(int m) { return o -> o.total() >= m; }
    static Spec<Order> veg() { return Order::veg; } }
interface OrderRepository { void save(Order o); List<Order> findAll(Spec<Order> spec); }
class InMemoryOrderRepository implements OrderRepository {
    private final Map<Integer, Order> rows = new LinkedHashMap<>();
    public void save(Order o) { rows.put(o.id(), o); }
    public List<Order> findAll(Spec<Order> s) { return rows.values().stream().filter(s::isSatisfiedBy).toList(); }
}
public class Main {
    public static void main(String[] args) {
        OrderRepository repo = new InMemoryOrderRepository();
        repo.save(new Order(1, "Pune", 650, true));   repo.save(new Order(2, "Pune", 300, false));
        repo.save(new Order(3, "Delhi", 900, true));  repo.save(new Order(4, "Pune", 1200, true));
        Spec<Order> bigVegPune = OrderSpecs.inCity("Pune")                 // compose small rules
                .and(OrderSpecs.totalAtLeast(500)).and(OrderSpecs.veg());
        System.out.println(repo.findAll(bigVegPune));
        System.out.println(repo.findAll(OrderSpecs.veg().not()));       // reuse: non-veg orders
    }
}

Output (real):

[Order[id=1, city=Pune, total=650, veg=true], Order[id=4, city=Pune, total=1200, veg=true]]
[Order[id=2, city=Pune, total=300, veg=false]]
  • A specification is one business rule as an object, with isSatisfiedBy(t).
  • and, or, not are default methods returning new specs (as lambdas, episode 5): that's what composable means, small pieces combined into bigger ones.
  • The repository needs one finder, findAll(spec); new questions need no new methods.
  • Eric Evans and Martin Fowler's paper: "Create a specification that is able to tell if a candidate object matches some criteria." The specification "has a method isSatisfiedBy (anObject) : Boolean that returns true if all criteria are met by anObject", and you "Create composite nodes for the and, or, and not operators".
  • The same spec can filter a list, validate a new object, or decide an offer. It's the Interpreter tree of episode 44, applied to business rules.

4. Unit of Work: save it all, or nothing

Placing one order = three changes: a new order, stock − 1, loyalty points + 10. Saved one by one, a crash after the second leaves half an order. A business transaction must happen completely or not at all.

Unit of Work: keep a list of new, changed and deleted objects during one business transaction, then commit() writes them all together (inside one database transaction) or rolls everything back. Like a shopping cart: collect first, pay once. Data-access frameworks usually do this for you.

import java.util.*;
class Database {                                                  // pretend storage, all-or-nothing writes
    final Map<String, Integer> stock = new HashMap<>(Map.of("Thali", 5));
    final Map<String, Integer> points = new HashMap<>(Map.of("Priya", 120));
    final List<String> orders = new ArrayList<>();
}
class UnitOfWork {                                                // tracks changes, writes them together
    private final Database db; private final List<Runnable> pending = new ArrayList<>();
    private final List<String> log = new ArrayList<>();
    UnitOfWork(Database db) { this.db = db; }
    void registerNew(String order) { log.add("new " + order); pending.add(() -> db.orders.add(order)); }
    void registerChanged(String what, Runnable change) { log.add("changed " + what); pending.add(change); }
    void commit(boolean failHalfway) {
        Map<String, Integer> stock = new HashMap<>(db.stock), points = new HashMap<>(db.points);
        List<String> orders = new ArrayList<>(db.orders);                       // backup = rollback point
        try {
            for (int i = 0; i < pending.size(); i++) {
                if (failHalfway && i == 2) throw new IllegalStateException("disk full");
                pending.get(i).run();
            }
            System.out.println("committed: " + log);
        } catch (IllegalStateException e) {
            db.stock.clear(); db.stock.putAll(stock); db.points.clear(); db.points.putAll(points);
            db.orders.clear(); db.orders.addAll(orders);
            System.out.println("rolled back (" + e.getMessage() + "): nothing saved");
        }
        pending.clear(); log.clear();
    }
}
public class Main {
    static void placeOrder(Database db, boolean fail) {
        UnitOfWork uow = new UnitOfWork(db);
        uow.registerNew("order#1 Priya Thali");
        uow.registerChanged("stock Thali", () -> db.stock.merge("Thali", -1, Integer::sum));
        uow.registerChanged("points Priya", () -> db.points.merge("Priya", 10, Integer::sum));
        uow.commit(fail);
        System.out.println("  orders=" + db.orders + " stock=" + db.stock + " points=" + db.points);
    }
    public static void main(String[] args) {
        Database db = new Database();
        placeOrder(db, true);                                     // crash after 2 of 3 writes
        placeOrder(db, false);                                    // all 3 writes
    }
}

Output (real):

rolled back (disk full): nothing saved
  orders=[] stock={Thali=5} points={Priya=120}
committed: [new order#1 Priya Thali, changed stock Thali, changed points Priya]
  orders=[order#1 Priya Thali] stock={Thali=4} points={Priya=130}

5. Layers: controller → service → repository

In a restaurant In an app
The waiter: takes orders, never cooks Controller: takes requests, returns responses
The chef: recipes and rules Service layer: business rules and use cases ("place an order")
The storeroom Repository: storage behind an interface
The order slip: dish names only, no card number DTO: just the data that crosses a boundary

Layered architecture: each layer talks only to the one directly below it.

First try: the controller returns the domain object

import java.util.*;
record Order(int id, String customer, List<String> items, int total, String card) { }  // the domain object
record OrderDto(int id, String items, int total) { }               // only what the screen needs
class OrderMapper {                                                // domain object -> DTO
    static OrderDto toDto(Order o) { return new OrderDto(o.id(), String.join(" + ", o.items()), o.total()); } }
interface OrderRepository { void save(Order o); }
class InMemoryOrderRepository implements OrderRepository {         // layer 3: storage
    private final List<Order> rows = new ArrayList<>();    public void save(Order o) { rows.add(o); } }
class OrderService {                                               // layer 2: business rules
    private final OrderRepository repo; private int nextId = 1;    OrderService(OrderRepository r) { repo = r; }
    Order place(String customer, List<String> items, int total, String card) {
        if (total <= 0) throw new IllegalArgumentException("total must be positive");
        Order o = new Order(nextId++, customer, items, total, card); repo.save(o); return o;
    } }
class OrderController {                                            // layer 1: requests in, responses out
    private final OrderService service;    OrderController(OrderService s) { service = s; }
    String post(String customer, String items, int total, String card) {
        try { return "201 " + service.place(customer, List.of(items.split(",")), total, card); }
        catch (IllegalArgumentException e) { return "400 " + e.getMessage(); }
    }
}
public class Main {
    public static void main(String[] args) {
        OrderController api = new OrderController(new OrderService(new InMemoryOrderRepository()));
        System.out.println(api.post("Priya", "Thali,Chai", 250, "4111-1111-1111-1111"));
        System.out.println(api.post("Ravi", "Chai", 0, "4111-1111-1111-1111"));
    }
}

Output (real):

201 Order[id=1, customer=Priya, items=[Thali, Chai], total=250, card=4111-1111-1111-1111]
400 total must be positive

201 means created and 400 means bad request (standard HTTP status codes). The first response leaked the whole Order, including the (test) card number. A domain object is built for business rules, not screens: send it out and every field leaks, and every screen depends on its exact shape.

The fix: DTO + mapper

import java.util.*;
record Order(int id, String customer, List<String> items, int total, String card) { }  // the domain object
record OrderDto(int id, String items, int total) { }               // only what the screen needs
class OrderMapper {                                                // domain object -> DTO
    static OrderDto toDto(Order o) { return new OrderDto(o.id(), String.join(" + ", o.items()), o.total()); } }
interface OrderRepository { void save(Order o); }
class InMemoryOrderRepository implements OrderRepository {         // layer 3: storage
    private final List<Order> rows = new ArrayList<>();    public void save(Order o) { rows.add(o); } }
class OrderService {                                               // layer 2: business rules
    private final OrderRepository repo; private int nextId = 1;    OrderService(OrderRepository r) { repo = r; }
    Order place(String customer, List<String> items, int total, String card) {
        if (total <= 0) throw new IllegalArgumentException("total must be positive");
        Order o = new Order(nextId++, customer, items, total, card); repo.save(o); return o;
    } }
class OrderController {                                            // layer 1: requests in, responses out
    private final OrderService service;    OrderController(OrderService s) { service = s; }
    String post(String customer, String items, int total, String card) {
        try { return "201 " + OrderMapper.toDto(service.place(customer, List.of(items.split(",")), total, card)); }
        catch (IllegalArgumentException e) { return "400 " + e.getMessage(); }
    }
}
public class Main {
    public static void main(String[] args) {
        OrderController api = new OrderController(new OrderService(new InMemoryOrderRepository()));
        System.out.println(api.post("Priya", "Thali,Chai", 250, "4111-1111-1111-1111"));
        System.out.println(api.post("Ravi", "Chai", 0, "4111-1111-1111-1111"));
    }
}

Output (real):

201 OrderDto[id=1, items=Thali + Chai, total=250]
400 total must be positive
  • DTO (Data Transfer Object): a plain object carrying only the data that must cross a boundary (OrderDto: id, items, total).
  • Mapper: a class that converts one shape of data into another (OrderMapper.toDto).
  • Main wires the layers in one place, the composition root (episode 16). The service depends on the OrderRepository interface: dependency inversion (episode 16).
  request ──> OrderController ──> OrderService ──> OrderRepository (interface)
  response <── OrderDto            business rules        ^ implements
                                                   InMemoryOrderRepository

6. MVC, MVP, MVVM: screens apart from logic

A TV MVC
The channel's signal: the show's data Model: data + business rules
The screen: shows it, decides nothing View: displays the model
The remote: your button presses Controller: handles input, updates the model
MVC MVP MVVM
Middle part Controller Presenter ViewModel
View Shows the model Passive: an interface (showTotal) Bound to the ViewModel's state
Who updates the view View reads the model Presenter calls the view Data binding, automatically
Testing Controller + model Presenter with a fake view ViewModel alone

Data binding: the screen is connected to a value and redraws itself whenever the value changes.

MVP in plain Java, tested with a fake view

import java.util.*;
class BillModel {                                                 // model: data + rules
    private final List<Integer> prices = new ArrayList<>();
    void add(int price) { if (price <= 0) throw new IllegalArgumentException("price must be positive"); prices.add(price); }
    int total() { return prices.stream().mapToInt(Integer::intValue).sum(); }
}
interface BillView { void showTotal(int total); void showError(String message); }   // passive view
class BillPresenter {                                             // presenter: all screen logic
    private final BillModel model; private final BillView view;
    BillPresenter(BillModel m, BillView v) { model = m; view = v; }
    void onAddClicked(String typed) {
        try { model.add(Integer.parseInt(typed.trim())); view.showTotal(model.total()); }
        catch (NumberFormatException e) { view.showError("not a number: " + typed); }
        catch (IllegalArgumentException e) { view.showError(e.getMessage()); }
    }
}
class ConsoleView implements BillView {                           // a real view: prints
    public void showTotal(int t) { System.out.println("Total: Rs " + t); }
    public void showError(String m) { System.out.println("Error: " + m); }
}
class FakeView implements BillView {                              // a test view: just remembers
    final List<String> calls = new ArrayList<>();
    public void showTotal(int t) { calls.add("total " + t); }
    public void showError(String m) { calls.add("error " + m); }
}
public class Main {
    public static void main(String[] args) {
        BillPresenter screen = new BillPresenter(new BillModel(), new ConsoleView());
        screen.onAddClicked("200"); screen.onAddClicked("chai"); screen.onAddClicked("-5"); screen.onAddClicked("50");
        FakeView fake = new FakeView();                           // unit-testing the presenter, no screen
        BillPresenter tested = new BillPresenter(new BillModel(), fake);
        tested.onAddClicked("100"); tested.onAddClicked("x");
        System.out.println("test saw: " + fake.calls + (fake.calls.equals(List.of("total 100", "error not a number: x")) ? "  PASS" : "  FAIL"));
    }
}

Output (real):

Total: Rs 200
Error: not a number: chai
Error: price must be positive
Total: Rs 250
test saw: [total 100, error not a number: x]  PASS

The presenter is unit-tested with FakeView, with no real screen at all: that's MVP's main benefit.

7. Which pattern, when?

Pattern Use when
Null Object A harmless default is truly correct (guest, no discount, no-op logger)
Repository Business code shouldn't know how data is stored; you want in-memory fakes for tests
Specification Rules must be combined, reused for filtering and validation
Unit of Work Several changes must be saved together or not at all
Service layer Business rules shared by many entry points (web, app, batch jobs)
DTO + mapper Data leaves the app (API, screen, message)
MVC / MVP / MVVM Any user interface with logic worth testing

In machine-coding rounds, a clear controller/service/repository split with an in-memory repository is expected almost every time.

Common mistakes

Mistake What you see Why Fix
find() returns null, a caller forgets to check NullPointerException: Cannot invoke "Customer.greeting()" because "<local3>" is null null has no methods Null Object, or Optional
A Null Object where absence is an error No error: payments to unknown accounts "succeed" The problem is hidden Optional or an exception
A finder method per question error: cannot find symbol ... method findBigVegOrdersInPune() Method explosion findAll(Spec)
Controller returns the entity No error: card=4111-1111-1111-1111 in the response Every field goes out DTO + mapper
Business rules in the controller No error: rules copied per screen, drifting apart Layers mixed Rules in the service
Saving related changes one by one Half an order after a crash No unit of work One transaction, commit all or nothing
Repository exposing SQL or table names Business code breaks when storage changes The abstraction leaks Collection-like methods only

Mini project: a layered order API with lookups

Add findById to the repository, find to the service and get to the controller (200 found, 404 not found).

import java.util.*;
record Order(int id, String customer, List<String> items, int total, String card) { }  // the domain object
record OrderDto(int id, String items, int total) { }               // only what the screen needs
class OrderMapper {                                                // domain object -> DTO
    static OrderDto toDto(Order o) { return new OrderDto(o.id(), String.join(" + ", o.items()), o.total()); } }
interface OrderRepository { void save(Order o); Optional<Order> findById(int id); }
class InMemoryOrderRepository implements OrderRepository {         // layer 3: storage
    private final List<Order> rows = new ArrayList<>();
    public void save(Order o) { rows.add(o); }
    public Optional<Order> findById(int id) { return rows.stream().filter(o -> o.id() == id).findFirst(); } }
class OrderService {                                               // layer 2: business rules
    private final OrderRepository repo; private int nextId = 1;    OrderService(OrderRepository r) { repo = r; }
    Order place(String customer, List<String> items, int total, String card) {
        if (total <= 0) throw new IllegalArgumentException("total must be positive");
        Order o = new Order(nextId++, customer, items, total, card); repo.save(o); return o;
    }
    Optional<Order> find(int id) { return repo.findById(id); }
}
class OrderController {                                            // layer 1: requests in, responses out
    private final OrderService service;    OrderController(OrderService s) { service = s; }
    String post(String customer, String items, int total, String card) {
        try { return "201 " + OrderMapper.toDto(service.place(customer, List.of(items.split(",")), total, card)); }
        catch (IllegalArgumentException e) { return "400 " + e.getMessage(); }
    }
    String get(int id) { return service.find(id).map(o -> "200 " + OrderMapper.toDto(o)).orElse("404 order " + id + " not found"); }
}
public class Main {
    public static void main(String[] args) {
        OrderController api = new OrderController(new OrderService(new InMemoryOrderRepository()));
        System.out.println(api.post("Priya", "Thali,Chai", 250, "4111-1111-1111-1111"));
        System.out.println(api.get(1));
        System.out.println(api.get(7));
    }
}

Output (real):

201 OrderDto[id=1, items=Thali + Chai, total=250]
200 OrderDto[id=1, items=Thali + Chai, total=250]
404 order 7 not found

Practice

1. Write a spec for "orders in Pune or Delhi with a total of at least 500".

Answer
import java.util.*;
interface Spec<T> {                                              // one business rule
    boolean isSatisfiedBy(T t);
    default Spec<T> and(Spec<T> o) { return t -> isSatisfiedBy(t) && o.isSatisfiedBy(t); }
    default Spec<T> or(Spec<T> o)  { return t -> isSatisfiedBy(t) || o.isSatisfiedBy(t); }
    default Spec<T> not()          { return t -> !isSatisfiedBy(t); }
}
record Order(int id, String city, int total, boolean veg) { }
class OrderSpecs {                                               // small, named rules
    static Spec<Order> inCity(String c) { return o -> o.city().equals(c); }
    static Spec<Order> totalAtLeast(int m) { return o -> o.total() >= m; }
    static Spec<Order> veg() { return Order::veg; }
}
interface OrderRepository { void save(Order o); List<Order> findAll(Spec<Order> spec); }
class InMemoryOrderRepository implements OrderRepository {
    private final Map<Integer, Order> rows = new LinkedHashMap<>();
    public void save(Order o) { rows.put(o.id(), o); }
    public List<Order> findAll(Spec<Order> s) { return rows.values().stream().filter(s::isSatisfiedBy).toList(); }
}
public class Main {
    public static void main(String[] args) {
        OrderRepository repo = new InMemoryOrderRepository();
        repo.save(new Order(1, "Pune", 650, true));   repo.save(new Order(2, "Pune", 300, false));
        repo.save(new Order(3, "Delhi", 900, true));  repo.save(new Order(4, "Mumbai", 1200, true));
        Spec<Order> puneOrDelhi = OrderSpecs.inCity("Pune").or(OrderSpecs.inCity("Delhi"));
        System.out.println(repo.findAll(puneOrDelhi.and(OrderSpecs.totalAtLeast(500))));
    }
}

Output (real):

[Order[id=1, city=Pune, total=650, veg=true], Order[id=3, city=Delhi, total=900, veg=true]]

2. Design a NoDiscount null object for a Discount interface with int apply(int total).

Answer
interface Discount { int apply(int total); }
final class NoDiscount implements Discount {
    static final NoDiscount INSTANCE = new NoDiscount();
    private NoDiscount() { }
    public int apply(int total) { return total; }   // does nothing, safely
}

Anywhere a discount may be missing, return NoDiscount.INSTANCE instead of null.

3. Why is it a problem if the service layer imports the controller's request classes?

Answer

Layers must only depend downwards. If the service knows web request types, it can't be reused from a batch job or a mobile app and can't be unit-tested without web classes. Pass plain values or a command object instead.

4. Repository or DAO: insertOrderRow(int id, String city, int total)?

Answer

DAO: it's shaped like a table row. A repository method would be save(Order order).

Quick quiz

Spec<Order> veg = Order::veg;
Spec<Order> big = o -> o.total() >= 500;
Order o = new Order(9, "Pune", 700, false);
System.out.println(
    veg.or(big).and(veg.not()).isSatisfiedBy(o));

What is printed? (a) true (b) false (c) NullPointerException (d) Compile error

Answer

(a) true (real output). veg is false, big is true, so veg.or(big) is true; veg.not() is true; true and true is true.

Interview questions

  1. What is the Null Object pattern? Replace null with an object implementing the same interface whose methods do nothing harmful, so callers need no null checks.
  2. Null Object vs Optional? Null Object hides absence (fine when "do nothing" is correct); Optional makes absence explicit so the caller must decide.
  3. What is a repository? A collection-like interface for domain objects that hides how they are stored.
  4. Repository vs DAO? DAO is table-oriented data access; a repository is domain-oriented and may use DAOs inside.
  5. What problem does Specification solve? Method explosion in repositories and duplicated business rules; specs are composable with and/or/not and reusable for filtering and validation.
  6. What is a Unit of Work? It tracks new, changed and deleted objects in one business transaction and commits them together or rolls back.
  7. Why DTOs? To control exactly what leaves the app (no secrets), and to decouple API/screen shapes from domain objects.
  8. What goes in a service vs a controller? Controller: parse the request, call the service, map to a response. Service: business rules and use cases.
  9. MVC vs MVP vs MVVM? MVC: controller handles input, view reads the model. MVP: presenter drives a passive view interface (easy to test). MVVM: view binds to ViewModel state (data binding).
  10. How would you lay out a machine-coding solution? Domain objects, repository interfaces + in-memory implementations, services with the rules, a thin controller or main driver, and a composition root wiring them.

Glossary

Term Meaning, with an example
Gang of Four (GoF) The four authors of the 1994 Design Patterns book with 23 classic patterns (episode 21)
Null Object pattern Return a do-nothing object instead of null: Guest.INSTANCE
null A reference that points to no object; calling a method on it throws NullPointerException
Optional A box that may or may not hold a value, making absence explicit (episode 5)
Domain object (entity) An object from the real-world problem: Order, Customer
Repository pattern A collection-like interface for domain objects that hides storage: save, findById
DAO (Data Access Object) A class hiding the database code for one table: insertRow, updateRow
Method explosion A new method for every combination of filters
Specification pattern A business rule as an object with isSatisfiedBy(t), combinable with and/or/not
Composable business rules Small rules joined into bigger ones: inCity("Pune").and(veg())
Default method A method with a body inside an interface (episode 3)
Lambda A short anonymous function: o -> o.total() >= 500 (episode 5)
Business transaction Several changes that must all happen or none: order + stock + points
Unit of Work Tracks new/changed/deleted objects and commits them together or rolls back
Commit / rollback Make all changes permanent / undo all of them
Service layer Classes holding business rules and use cases: OrderService.place
Use case One thing a user can do with the system: "place an order"
Controller Takes requests from outside, calls the service, returns responses
Layered architecture Code split into layers (controller, service, repository), each calling only the one below
DTO (Data Transfer Object) A plain object with only the data that crosses a boundary: OrderDto
Mapper Converts one data shape into another: OrderMapper.toDto(order)
HTTP status code A number in a web response: 200 OK, 201 Created, 400 Bad Request, 404 Not Found
Composition root The one place where objects are created and wired together (episode 16)
Dependency inversion High-level code depends on interfaces, not concrete classes (episode 16)
MVC Model (data + rules), View (shows it), Controller (handles input, updates the model)
MVP Model, passive View interface, Presenter with all screen logic
MVVM Model, View bound to a ViewModel's state, ViewModel exposing that state
Data binding The screen redraws itself automatically when a bound value changes
Fake (test double) A simple stand-in used in tests: FakeView records calls
Machine-coding round An interview round where you build a small working system in about 1-2 hours (episode 1)

Summary

  • Null Object replaces null with a harmless stand-in, only when "do nothing" is correct.
  • A repository is a collection of domain objects; a DAO is a table's data access.
  • Specifications are business rules you combine with and/or/not, ending method explosion.
  • A Unit of Work commits a business transaction's changes all together or not at all.
  • Apps are layered controller → service → repository, with DTOs and mappers at the edge so nothing leaks.
  • MVC, MVP, MVVM keep screens apart from logic; MVP and MVVM make screen logic easy to test.

Next episode: Concurrency 1: threads, race conditions and synchronized, when two cashiers sell the last thali at the same moment.