Sitemap

Member-only story

đźš« Stop Writing Fat Controllers: Follow the Controller-Service-Repository Pattern

4 min readApr 12, 2025

In a typical Spring Boot project, it’s easy to let your controller classes grow out of control. You start by handling a simple request, then add a bit of business logic, maybe some database access — and before you know it, your controller has become a bloated, untestable mess.

If your controller methods are more than 10–15 lines, or if they contain database logic, conditionals, and exception handling — you’re likely writing a fat controller.

The solution? Follow the Controller-Service-Repository (CSR) pattern — a clean and proven way to structure Spring Boot applications that keeps your code readable, testable, and maintainable.

💣 What’s a Fat Controller?

A “fat controller” refers to a controller class that does too much:

  • Handles request mapping
  • Contains business logic
  • Talks to the database
  • Manages error handling
  • Performs input validation
  • Builds complex response objects

Let’s look at an example:

@RestController
@RequestMapping("/products")
public class ProductController {

@Autowired
private ProductRepository productRepository;

@PostMapping
public ResponseEntity<String> createProduct(@RequestBody Product product) {
if (product.getPrice() < 0) {
return ResponseEntity.badRequest().body("Invalid price");
}

product.setCreatedAt(LocalDateTime.now());
productRepository.save(product);

return ResponseEntity.ok("Product created");
}
}

This might look fine — but it mixes:

  • Input validation
  • Business logic
  • Persistence logic
  • Response formatting

It’s hard to test, hard to extend, and violates the Single Responsibility Principle.

✅ The Clean Approach…

--

--

No responses yet