Common layering mistakes
45 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)Most layering mistakes are shortcuts that work on the day they are written: a quick rule in a controller, a repository call to save a minute, a service that peeks at the request. Each one breaks later, for a caller or a change nobody expected.
Business rules inside controllers
Drift is when the same rule is written in several places and the copies stop matching, so one caller enforces the rule and another does not.
Here is a controller that checks the SKU on POST but forgot the check on PUT. Compare what each request gets.
Example 1 · BadProductController.java: rules and storage in the controller
Runs in: the layer-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.mistakes;
import java.math.BigDecimal;import java.time.LocalDateTime;import java.util.List;
import org.springframework.http.HttpStatus;import org.springframework.http.ResponseEntity;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.PathVariable;import org.springframework.web.bind.annotation.PostMapping;import org.springframework.web.bind.annotation.PutMapping;import org.springframework.web.bind.annotation.RequestBody;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;
import com.shoplite.lab.mapping.LabProduct;import com.shoplite.lab.mapping.LabProductStore;
// Everything in one class: rules, storage calls and entities in the JSON@RestController@RequestMapping("/lab/bad/products")class BadProductController {
private final LabProductStore store;
BadProductController(LabProductStore store) { this.store = store; }
@GetMapping List<LabProduct> list() { return store.findAll(); }
@PostMapping ResponseEntity<?> create(@RequestBody LabProduct body) { if (store.findBySku(body.getSku()).isPresent()) { // rule 1, written here return ResponseEntity.status(HttpStatus.CONFLICT).body("SKU " + body.getSku() + " already exists"); } if (body.getPrice().compareTo(BigDecimal.ZERO) <= 0) { return ResponseEntity.badRequest().body("price must be greater than 0"); } body.setCreatedAt(LocalDateTime.now()); return ResponseEntity.status(HttpStatus.CREATED).body(store.save(body)); }
@PutMapping("/{id}") LabProduct replace(@PathVariable Long id, @RequestBody LabProduct body) { body.setId(id); // rule 1 forgotten: no SKU check here return store.save(body); }}$ curl -i -X POST http://localhost:8080/lab/bad/products -H 'Content-Type: application/json' -d '{"sku":"MOB-RN13","name":"Redmi Note 13 Pro","price":23999.00,"stock":10,"active":true}'
HTTP/1.1 409
Content-Type: text/plain;charset=UTF-8
SKU MOB-RN13 already exists
$ curl -X PUT http://localhost:8080/lab/bad/products/2 -H 'Content-Type: application/json' -d '{"sku":"MOB-RN13","name":"Clean Code","price":499.00,"stock":30,"active":true}'
{"id":2,"sku":"MOB-RN13","name":"Clean Code","price":499.00,"costPrice":null,"stock":30,"active":true,"createdAt":null,"updatedAt":null}What this code does
- The POST checks for a duplicate SKU and is refused with 409. The PUT, written later, has no such check, so product 2 now also has SKU MOB-RN13.
- Because the PUT binds the entity,
costPriceand both timestamps of product 2 are wiped tonullas a bonus. - The fix is the shape ShopLite already has:
ProductControllercallsProductService.createandreplace, and both run the samecheckSkuIsFree.
A business rule in a controller is any "is this allowed?" decision written next to the HTTP code: a duplicate check, a price limit, a stock check. It works for that one endpoint and is invisible to every other caller.
The fix is always the same move: put the rule in one service method and make every endpoint call it. The controller then has nothing left to forget.
Controllers calling repositories directly
A shortcut endpoint is a controller method that calls a repository directly, skipping the service and every rule the service applies.
Here is an endpoint that lists in-stock products straight from the repository, next to a version that asks the service.
Example 2 · A shortcut endpoint that skips the service
import java.util.List;
record Product(Long id, String name, int stock, boolean active) {}
class ProductRepository { List<Product> findAll() { return List.of( new Product(6L, "boAt Airdopes 141", 120, true), new Product(8L, "Logitech M331 Silent Mouse", 0, true), new Product(15L, "boAt Airdopes 131 (old model)", 12, false)); }}
class ProductService { private final ProductRepository repository;
ProductService(ProductRepository repository) { this.repository = repository; }
// The rule lives here: buyers only ever see active products List<String> listForBuyers(boolean inStockOnly) { return repository.findAll().stream() .filter(Product::active) .filter(p -> !inStockOnly || p.stock() > 0) .map(Product::name) .toList(); }}
class ProductController { private final ProductService service; private final ProductRepository repository;
ProductController(ProductService service, ProductRepository repository) { this.service = service; this.repository = repository; }
List<String> list() { return service.listForBuyers(false); }
// Written in a hurry, straight on the repository: the "active only" rule is missing List<String> listInStock() { return repository.findAll().stream().filter(p -> p.stock() > 0).map(Product::name).toList(); }
// The fix: one service call, with the rule applied in one place List<String> listInStockFixed() { return service.listForBuyers(true); }}
public class BypassDemo { public static void main(String[] args) { ProductRepository repository = new ProductRepository(); ProductController controller = new ProductController(new ProductService(repository), repository); System.out.println("list: " + controller.list()); System.out.println("in stock (bypass): " + controller.listInStock()); System.out.println("in stock (fixed): " + controller.listInStockFixed()); }}list: [boAt Airdopes 141, Logitech M331 Silent Mouse] in stock (bypass): [boAt Airdopes 141, boAt Airdopes 131 (old model)] in stock (fixed): [boAt Airdopes 141]
What this code does
list()goes through the service, which hides the inactive old model.listInStock()reads the repository directly and shows it to buyers.listInStockFixed()asks the service withinStockOnlytrue, so both rules (active, in stock) apply. The controller no longer needs the repository at all.
A shortcut usually starts as "just a read, it is harmless". But reads have rules too: buyers see only active products, a customer sees only their own orders. The shortcut returns what the rule hides, and keeps doing so after the rule changes, because it never asked the service.
A controller should have exactly one dependency: its feature's service. If a new endpoint needs a new query, add a service method that calls the repository and applies the rules.
Services that return ResponseEntity or read HttpServletRequest
RequestContextHolder is a Spring class that gives code access to the current web request from anywhere. A service that uses it works only while a web request is running.
Here is a delivery-charge service that reads the city from the web request, and a nightly report that calls it.
Example 3 · DeliveryChargeService.java, NightlyChargeReport.java: a service tied to HTTP
Runs in: the layer-lab practice project (Spring Boot 4.1)
package com.shoplite.lab.mistakes;
import java.math.BigDecimal;
import org.springframework.stereotype.Service;import org.springframework.web.context.request.RequestContextHolder;import org.springframework.web.context.request.ServletRequestAttributes;
import jakarta.servlet.http.HttpServletRequest;
// The mistake: a service that reaches into the current HTTP request@Serviceclass DeliveryChargeService {
BigDecimal chargeFor(BigDecimal orderTotal) { HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes()).getRequest(); String city = request.getHeader("X-City"); if (orderTotal.compareTo(new BigDecimal("499")) >= 0) { return new BigDecimal("0.00"); } return "Bengaluru".equals(city) ? new BigDecimal("29.00") : new BigDecimal("49.00"); }}
package com.shoplite.lab.mistakes;
import java.math.BigDecimal;
import org.springframework.boot.ApplicationArguments;import org.springframework.boot.ApplicationRunner;import org.springframework.stereotype.Component;
// A second caller with no HTTP request: a report that runs at startup@Componentclass NightlyChargeReport implements ApplicationRunner {
private final DeliveryChargeService service;
NightlyChargeReport(DeliveryChargeService service) { this.service = service; }
@Override public void run(ApplicationArguments args) { if (!args.containsOption("nightly-report")) { return; } System.out.println("Charge on a Rs 300 order: " + service.chargeFor(new BigDecimal("300"))); }}$ curl 'http://localhost:8080/lab/bad/delivery-charge?orderTotal=300' -H 'X-City: Bengaluru'
{"deliveryCharge":29.00}
$ java -jar target/layer-lab-0.0.1-SNAPSHOT.jar --nightly-report
...
2026-10-16T10:35:29.759+05:30 ERROR 24772 --- [layer-lab] [ main] o.s.boot.SpringApplication : Application run failed
java.lang.IllegalStateException: No thread-bound request found: Are you referring to request attributes outside of an actual web request, or processing a request outside of the originally receiving thread? If you are actually operating within a web request and still receive this message, your code is probably running outside of DispatcherServlet: In this case, use RequestContextListener or RequestContextFilter to expose the current request.
at org.springframework.web.context.request.RequestContextHolder.currentRequestAttributes(RequestContextHolder.java:130) ~[spring-web-7.0.9.jar!/:7.0.9]
at com.shoplite.lab.mistakes.DeliveryChargeService.chargeFor(DeliveryChargeService.java:17) ~[!/:0.0.1-SNAPSHOT]
at com.shoplite.lab.mistakes.NightlyChargeReport.run(NightlyChargeReport.java:24) ~[!/:0.0.1-SNAPSHOT]
...What this code does
- Through the web endpoint it works: the request carries
X-City: Bengaluru, so a Rs 300 order costs 29.00 to deliver. - The startup report calls the same method with no web request, and
RequestContextHolderthrowsIllegalStateException. The app does not even finish starting. - The trace points at the line that reaches for the request (
DeliveryChargeService.java:17). That line is the design problem, not a bug to catch.
Example 4 · The fix: pass the city in as a parameter
import java.math.BigDecimal;import java.util.Map;
// Service: everything it needs arrives as a parameter, so any caller can use itclass DeliveryChargeService { private static final BigDecimal FREE_FROM = new BigDecimal("499");
BigDecimal chargeFor(BigDecimal orderTotal, String city) { if (orderTotal.compareTo(FREE_FROM) >= 0) { return new BigDecimal("0.00"); } return "Bengaluru".equals(city) ? new BigDecimal("29.00") : new BigDecimal("49.00"); }}
// Controller: reading the header is an HTTP job, so it happens hereclass DeliveryChargeController { private final DeliveryChargeService service;
DeliveryChargeController(DeliveryChargeService service) { this.service = service; }
String get(Map<String, String> headers, String orderTotalParam) { String city = headers.get("X-City"); return "200 {\"deliveryCharge\": " + service.chargeFor(new BigDecimal(orderTotalParam), city) + "}"; }}
// A caller with no HTTP request at allclass NightlyChargeReport { private final DeliveryChargeService service;
NightlyChargeReport(DeliveryChargeService service) { this.service = service; }
void run() { System.out.println("Report: Rs 300 order to Pune costs " + service.chargeFor(new BigDecimal("300"), "Pune")); }}
public class DeliveryChargeFixDemo { public static void main(String[] args) { DeliveryChargeService service = new DeliveryChargeService(); DeliveryChargeController controller = new DeliveryChargeController(service); System.out.println(controller.get(Map.of("X-City", "Bengaluru"), "300")); System.out.println(controller.get(Map.of("X-City", "Bengaluru"), "650")); new NightlyChargeReport(service).run(); }}200 {"deliveryCharge": 29.00}
200 {"deliveryCharge": 0.00}
Report: Rs 300 order to Pune costs 49.00What this code does
chargeFor(orderTotal, city)gets everything as parameters, so it works the same for the controller and for the report.- Reading the
X-Cityheader is now the controller's job. In Spring it would be@RequestHeader("X-City") String cityon the controller method.
A service that knows about HTTP returns ResponseEntity, picks status codes, or reads the request through HttpServletRequest or RequestContextHolder. The moment another caller arrives it breaks: a startup runner, a scheduled job or a unit test has no request, so RequestContextHolder throws IllegalStateException: No thread-bound request found.
The fix: the controller reads headers, parameters and the body, and passes plain values into the service. The service returns plain data or throws a business exception, and the controller (or, later, a global handler) turns that into a status.
Returning entities from controllers
Here is a list response that returns stored entities. Look at what every client now receives.
@GetMappingPageResponse<ProductResponse> list(/* filters, page, size */) { return service.search(filter, page, size); // DTOs in, DTOs out: no entity in sight}Example 5 · Entities in a list response
Runs in: the layer-lab practice project (Spring Boot 4.1)
curl http://localhost:8080/lab/bad/products$ curl http://localhost:8080/lab/bad/products
[{"id":1,"sku":"MOB-RN13","name":"Redmi Note 13 5G","price":17999.00,"costPrice":15200.00,"stock":40,"active":true,"createdAt":"2026-05-01T10:00:00","updatedAt":"2026-05-01T10:00:00"},{"id":2,"sku":"MOB-RN13","name":"Clean Code","price":499.00,"costPrice":null,"stock":30,"active":true,"createdAt":null,"updatedAt":null}]What this code does
- This is the list after the bad PUT of Example 1: two products share MOB-RN13, one has a public cost price, the other has
nullwhere its cost and timestamps used to be. - Every client of this endpoint now sees
active,costPrice,createdAtandupdatedAt. Removing them later is a breaking change, even though nobody meant to publish them.
Returning an entity from a controller makes every field of the stored row part of the API. The Mapping between entities and DTOs lesson showed the leaks: internal fields go out, client JSON overwrites fields coming in.
In a list endpoint it is worse, because one bad row makes every response look wrong: null timestamps, a cost price, "active" instead of isActive. Clients start to depend on these accidents, and then you cannot remove them. Return response records from the service and let controllers pass them through unchanged, as the snippet above does.
Find the bug
Find the layering mistake
Click the line that breaks the layering.
Click the line that puts a business rule in the controller.
Round 1 of 4The god service: splitting a 600-line class step by step
A god service is one service class that does many unrelated jobs, so every change touches it and every test needs all its dependencies.
Here is a god service split into one service per job. A small coordinator only calls them in order.
Example 6 · A god service split into one service per job
import java.math.BigDecimal;import java.math.RoundingMode;import java.util.HashMap;import java.util.Map;
// Before the split, ShopService did all three jobs below in one class.// After the split: one service per job, and a small coordinator that calls them.
class PricingService { private final Map<String, BigDecimal> priceBySku = new HashMap<>(Map.of( "BK-CLEAN", new BigDecimal("499.00"), "ACC-AD141", new BigDecimal("1299.00")));
BigDecimal priceOf(String sku) { return priceBySku.get(sku); }}
class CouponService { BigDecimal discountFor(String code, BigDecimal amount) { if ("FEST10".equals(code)) { return amount.multiply(new BigDecimal("0.10")).setScale(2, RoundingMode.HALF_UP); } return new BigDecimal("0.00"); }}
class SmsTextService { String orderPlaced(String sku, BigDecimal paid) { return "ShopLite: your order for " + sku + " is placed. Paid Rs " + paid + "."; }}
// The coordinator: no rules of its own, it only calls the three services in orderclass CheckoutService { private final PricingService pricing; private final CouponService coupons; private final SmsTextService sms;
CheckoutService(PricingService pricing, CouponService coupons, SmsTextService sms) { this.pricing = pricing; this.coupons = coupons; this.sms = sms; }
String checkout(String sku, String couponCode) { BigDecimal price = pricing.priceOf(sku); BigDecimal paid = price.subtract(coupons.discountFor(couponCode, price)); return sms.orderPlaced(sku, paid); }}
public class SplitServiceDemo { public static void main(String[] args) { CheckoutService checkout = new CheckoutService(new PricingService(), new CouponService(), new SmsTextService()); System.out.println(checkout.checkout("BK-CLEAN", "FEST10")); System.out.println(checkout.checkout("ACC-AD141", "NONE"));
CouponService coupons = new CouponService(); System.out.println("Coupon on Rs 1299.00: " + coupons.discountFor("FEST10", new BigDecimal("1299.00"))); }}ShopLite: your order for BK-CLEAN is placed. Paid Rs 449.10. ShopLite: your order for ACC-AD141 is placed. Paid Rs 1299.00. Coupon on Rs 1299.00: 129.90
What this code does
PricingService,CouponServiceandSmsTextServiceeach hold one job.CheckoutServiceonly calls them in order and has no rules of its own.- The last line uses
CouponServicealone, which was impossible while coupons lived inside a class that also needed prices and SMS templates. - Behaviour did not change: the split is a structure change only, which is why the tests that passed before must pass after.
A ShopService with product prices, coupons, SMS texts, reports and order placement in 600 lines is the typical case: two developers editing it collide. Split it in small, safe steps, running the tests after each one. The order matters: move code first, change callers last, and never change behaviour in the same step as structure.
- Group the methods by job: write down which ones deal with prices, coupons, messages and so on.
- Create one new service per job and move that group's methods and fields into it, unchanged.
- Let the old class call the new services for a while, so its callers keep working.
- Point the controllers and other callers at the new services, one at a time.
- When nothing calls the old class any more, delete it. Keep a thin coordinator only if a flow really needs several services.
Next step
Check your understanding
12 quick questions