Skip to lesson

Practice: layered architecture

A review of this module. Skip it if you feel confident; the next module does not need it.

Fix the mistakes

The slips that cost marks in this module. Spot each one, then check the fix.

Layered code comes down to three questions asked of every line: does it speak HTTP, does it decide, or does it store? Most exercises in this lesson are those questions, answered in working code.

Placing code: three questions for every line

Here is one requirement, a UPI refund, split across the three layers.

Example 1 · One requirement split across three layers: UPI refunds

RefundDemo.javaJava
import java.math.BigDecimal;import java.util.Map;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;
record RefundRequest(long orderId, BigDecimal amount) {}
record RefundResponse(long refundId, long orderId, BigDecimal amount, String status) {}
record Order(long id, String status, BigDecimal total) {}
record Refund(Long id, long orderId, BigDecimal amount) {}
class RefundRefusedException extends RuntimeException {    RefundRefusedException(String message) {        super(message);    }}
class AlreadyRefundedException extends RuntimeException {    AlreadyRefundedException(String message) {        super(message);    }}
// Repository: store and load onlyclass RefundRepository {    private final Map<Long, Refund> rows = new ConcurrentHashMap<>();    private final AtomicLong nextId = new AtomicLong(501);
    boolean existsByOrderId(long orderId) {        return rows.values().stream().anyMatch(r -> r.orderId() == orderId);    }
    Refund save(Refund refund) {        Refund row = new Refund(nextId.getAndIncrement(), refund.orderId(), refund.amount());        rows.put(row.id(), row);        return row;    }}
class OrderLookup {    private final Map<Long, Order> orders = Map.of(            7L, new Order(7L, "DELIVERED", new BigDecimal("1698.00")),            15L, new Order(15L, "PLACED", new BigDecimal("42990.00")));
    Optional<Order> findById(long id) {        return Optional.ofNullable(orders.get(id));    }}
// Service: the three refund rules, in order, then save and mapclass RefundService {    private final RefundRepository refunds;    private final OrderLookup orders;
    RefundService(RefundRepository refunds, OrderLookup orders) {        this.refunds = refunds;        this.orders = orders;    }
    RefundResponse refund(RefundRequest request) {        Order order = orders.findById(request.orderId())                .orElseThrow(() -> new RefundRefusedException("Order " + request.orderId() + " does not exist."));        if (!order.status().equals("DELIVERED") && !order.status().equals("CANCELLED")) {            throw new RefundRefusedException("Order " + order.id() + " is " + order.status() + "; nothing to refund yet.");        }        if (request.amount().compareTo(order.total()) > 0) {            throw new RefundRefusedException("Refund " + request.amount() + " is more than the order total " + order.total() + ".");        }        if (refunds.existsByOrderId(order.id())) {            throw new AlreadyRefundedException("Order " + order.id() + " already has a refund.");        }        Refund saved = refunds.save(new Refund(null, order.id(), request.amount()));        return new RefundResponse(saved.id(), saved.orderId(), saved.amount(), "INITIATED");    }}
// Controller: HTTP in and outclass RefundController {    private final RefundService service;
    RefundController(RefundService service) {        this.service = service;    }
    String post(RefundRequest body) {        try {            return "201 " + service.refund(body);        } catch (RefundRefusedException e) {            return "422 " + e.getMessage();        } catch (AlreadyRefundedException e) {            return "409 " + e.getMessage();        }    }}
public class RefundDemo {    public static void main(String[] args) {        RefundController controller = new RefundController(new RefundService(new RefundRepository(), new OrderLookup()));        System.out.println(controller.post(new RefundRequest(7, new BigDecimal("399.00"))));        System.out.println(controller.post(new RefundRequest(7, new BigDecimal("100.00"))));        System.out.println(controller.post(new RefundRequest(15, new BigDecimal("100.00"))));        System.out.println(controller.post(new RefundRequest(7, new BigDecimal("5000.00"))));    }}
Output
201 RefundResponse[refundId=501, orderId=7, amount=399.00, status=INITIATED]
409 Order 7 already has a refund.
422 Order 15 is PLACED; nothing to refund yet.
422 Refund 5000.00 is more than the order total 1698.00.

What this code does

  • The controller only builds the request record and picks 201, 409 or 422. The service holds the four checks in the contract's order; the repository only answers existsByOrderId and saves.
  • The second request is refused with 409 because order 7 already has a refund (a clash with stored state). The last one is refused with 422 earlier, because its amount breaks a rule before the duplicate check runs.

Placing code means asking three questions of every line, in order: does it read or write HTTP, does it decide what is allowed or in which order things happen, or does it only find, count, save or delete? The first yes decides the layer. Quick signs:

  • HTTP words (mapping, header, body, status, ResponseEntity) → controller.
  • Words like may, must, only, at most, before → service.
  • find, count, exists, save, delete → repository.
  • Converting entity ↔ DTO → a mapper used by the service.

"Refund a delivered order once, up to its total" gives the controller the request and the status, the service three rules in a fixed order, and the repository one lookup and one save. Watch the order of the rules, because it decides which error a client sees: rules about other data (422) before clashes with stored state (409), as the ShopLite contract says.

Refactoring a controller that does everything

Here is a scholarship controller that checks rules, calls storage and returns entities from one method.

Java
@PostMapping("/api/v1/scholarships")ResponseEntity<?> apply(@RequestBody Scholarship body) {    if (body.getMarksPercent() < 85) return ResponseEntity.unprocessableEntity().body("Marks below 85%");    if (body.getFamilyIncome().compareTo(new BigDecimal("800000")) > 0)        return ResponseEntity.unprocessableEntity().body("Family income above Rs 8,00,000");    if (repository.findByRollNo(body.getRollNo()).isPresent())        return ResponseEntity.status(409).body(body.getRollNo() + " has already applied");    body.setAmount(body.getMarksPercent() >= 95 ? new BigDecimal("50000.00") : new BigDecimal("25000.00"));    return ResponseEntity.status(201).body(repository.save(body));}

Example 2 · The scholarship controller after the five steps

ScholarshipDemo.javaJava
import java.math.BigDecimal;import java.util.Map;import java.util.Optional;import java.util.concurrent.ConcurrentHashMap;import java.util.concurrent.atomic.AtomicLong;
record ApplyRequest(String rollNo, int marksPercent, BigDecimal familyIncome) {}
record ScholarshipResponse(long id, String rollNo, BigDecimal amount) {}
record Scholarship(Long id, String rollNo, int marksPercent, BigDecimal familyIncome, BigDecimal amount) {}
class NotEligibleException extends RuntimeException {    NotEligibleException(String message) {        super(message);    }}
class AlreadyAppliedException extends RuntimeException {    AlreadyAppliedException(String message) {        super(message);    }}
// Step 3: storage behind an interfaceinterface ScholarshipRepository {    Optional<Scholarship> findByRollNo(String rollNo);
    Scholarship save(Scholarship scholarship);}
class InMemoryScholarshipRepository implements ScholarshipRepository {    private final Map<Long, Scholarship> rows = new ConcurrentHashMap<>();    private final AtomicLong nextId = new AtomicLong(1);
    public Optional<Scholarship> findByRollNo(String rollNo) {        return rows.values().stream().filter(s -> s.rollNo().equals(rollNo)).findFirst();    }
    public Scholarship save(Scholarship s) {        Scholarship row = new Scholarship(nextId.getAndIncrement(), s.rollNo(), s.marksPercent(), s.familyIncome(), s.amount());        rows.put(row.id(), row);        return row;    }}
// Step 2: every rule in one service methodclass ScholarshipService {    private static final BigDecimal INCOME_LIMIT = new BigDecimal("800000");    private final ScholarshipRepository repository;
    ScholarshipService(ScholarshipRepository repository) {        this.repository = repository;    }
    ScholarshipResponse apply(ApplyRequest r) {        if (r.marksPercent() < 85) {            throw new NotEligibleException("Marks below 85%");        }        if (r.familyIncome().compareTo(INCOME_LIMIT) > 0) {            throw new NotEligibleException("Family income above Rs 8,00,000");        }        if (repository.findByRollNo(r.rollNo()).isPresent()) {            throw new AlreadyAppliedException(r.rollNo() + " has already applied");        }        BigDecimal amount = r.marksPercent() >= 95 ? new BigDecimal("50000.00") : new BigDecimal("25000.00");        Scholarship saved = repository.save(new Scholarship(null, r.rollNo(), r.marksPercent(), r.familyIncome(), amount));        return new ScholarshipResponse(saved.id(), saved.rollNo(), saved.amount());    }}
// Step 5: the controller only translatesclass ScholarshipController {    private final ScholarshipService service;
    ScholarshipController(ScholarshipService service) {        this.service = service;    }
    String post(ApplyRequest body) {        try {            return "201 " + service.apply(body);        } catch (NotEligibleException e) {            return "422 " + e.getMessage();        } catch (AlreadyAppliedException e) {            return "409 " + e.getMessage();        }    }}
public class ScholarshipDemo {    public static void main(String[] args) {        ScholarshipController controller = new ScholarshipController(                new ScholarshipService(new InMemoryScholarshipRepository()));        System.out.println(controller.post(new ApplyRequest("CS101", 96, new BigDecimal("450000"))));        System.out.println(controller.post(new ApplyRequest("ME207", 88, new BigDecimal("620000"))));        System.out.println(controller.post(new ApplyRequest("EC115", 91, new BigDecimal("1200000"))));        System.out.println(controller.post(new ApplyRequest("CS101", 96, new BigDecimal("450000"))));        System.out.println(controller.post(new ApplyRequest("CE330", 72, new BigDecimal("300000"))));    }}
Output
201 ScholarshipResponse[id=1, rollNo=CS101, amount=50000.00]
201 ScholarshipResponse[id=2, rollNo=ME207, amount=25000.00]
422 Family income above Rs 8,00,000
409 CS101 has already applied
422 Marks below 85%

What this code does

  • Every rule from the snippet now lives in ScholarshipService.apply, in the same order, so the same five requests get the same answers.
  • The repository is an interface with an in-memory implementation, and the response is ScholarshipResponse: the family income no longer goes back to every client.
  • The controller lost its repository and all its ifs. What remains is one service call and one status per exception.

Refactor it in five steps, keeping the behaviour identical:

  1. List the rules.
  2. Move them into one service method.
  3. Put the storage calls behind a repository interface.
  4. Add request and response DTOs.
  5. Leave the controller with one service call and the status mapping.

Run the same requests before and after each step. The answers must not change; only where the code lives changes.

Mappers and fakes: the two small tools

Here is a service checked with a fake repository and a mapper, in a plain Java test.

Example 3 · A service checked with a fake repository and a mapper

FakeAndMapperDemo.javaJava
import java.math.BigDecimal;import java.util.ArrayList;import java.util.List;import java.util.Optional;
record Product(Long id, String sku, String name, BigDecimal price, int stock) {}
record ProductResponse(Long id, String sku, String name, BigDecimal price, boolean inStock) {}
record AddStockRequest(String sku, int quantity) {}
interface ProductRepository {    Optional<Product> findBySku(String sku);
    Product save(Product product);}
// The mapper: stateless, one direction per methodfinal class ProductMapper {    private ProductMapper() {    }
    static ProductResponse toResponse(Product p) {        return new ProductResponse(p.id(), p.sku(), p.name(), p.price(), p.stock() > 0);    }}
class ProductService {    private final ProductRepository repository;
    ProductService(ProductRepository repository) {        this.repository = repository;    }
    ProductResponse addStock(AddStockRequest request) {        if (request.quantity() < 1) {            throw new IllegalArgumentException("quantity must be at least 1");        }        Product p = repository.findBySku(request.sku()).orElseThrow();        Product updated = new Product(p.id(), p.sku(), p.name(), p.price(), p.stock() + request.quantity());        return ProductMapper.toResponse(repository.save(updated));    }}
// The fake: a list, plus a record of every save so a check can look insideclass FakeProductRepository implements ProductRepository {    final List<Product> saved = new ArrayList<>();    private final List<Product> rows = new ArrayList<>(List.of(            new Product(8L, "ACC-M331", "Logitech M331 Silent Mouse", new BigDecimal("849.00"), 0)));
    public Optional<Product> findBySku(String sku) {        return rows.stream().filter(p -> p.sku().equals(sku)).findFirst();    }
    public Product save(Product product) {        saved.add(product);        rows.removeIf(p -> p.id().equals(product.id()));        rows.add(product);        return product;    }}
public class FakeAndMapperDemo {    static void check(String name, boolean passed) {        System.out.println((passed ? "PASS " : "FAIL ") + name);    }
    public static void main(String[] args) {        FakeProductRepository fake = new FakeProductRepository();        ProductService service = new ProductService(fake);
        ProductResponse response = service.addStock(new AddStockRequest("ACC-M331", 25));        System.out.println(response);        check("restocked mouse is in stock", response.inStock());        check("stock saved as 25", fake.saved.get(0).stock() == 25);
        try {            service.addStock(new AddStockRequest("ACC-M331", 0));            check("quantity 0 is refused", false);        } catch (IllegalArgumentException e) {            check("quantity 0 is refused", true);        }        check("refused request saved nothing", fake.saved.size() == 1);    }}
Output
ProductResponse[id=8, sku=ACC-M331, name=Logitech M331 Silent Mouse, price=849.00, inStock=true]
PASS restocked mouse is in stock
PASS stock saved as 25
PASS quantity 0 is refused
PASS refused request saved nothing

What this code does

  • FakeProductRepository keeps a list of every saved product, so the checks can see that exactly one save happened and that a refused request saved nothing.
  • ProductMapper.toResponse turns stock into an inStock flag; the check reads the DTO the way a client would.

A mapper converts between entities and DTOs and holds no state; a fake repository is a tiny working implementation used in tests. Together they let you test a service in milliseconds: build the service with the fake, call it, then check both the returned DTO and what the fake stored.

Check outcomes, not steps. "The response says in stock" and "exactly one save happened" are good checks; "method X was called before method Y" ties the test to today's code.

Interview drill: explaining your layers

Layering questions come in a few shapes, and each has a short, concrete answer that names your own project. Practise saying them out loud with ShopLite examples: the SKU rule in ProductService, the package-private ProductRepository, ProductMapper adding categoryName.

Good answers state the rule, give the reason in one sentence and add one real consequence: "rules in controllers drift; my PUT would have allowed duplicate SKUs".

  • Why layers? One job per layer, so a rule is written once and every caller gets it.
  • DTO vs entity? Entities are stored rows; DTOs are the API, so internal fields never leak.
  • Why package by feature? A change touches one folder, and internals can be package-private.
  • How do features talk? Through public services, one way, never through another feature's repository.

Finish up

Mark complete & continue

Next: Mini project: ShopLite products, layered