Performance: Why service layer matters
This concept affects the organization of backend logic which indirectly impacts frontend load speed and responsiveness by controlling data flow and processing efficiency.
Jump into concepts and practice - no test required
public class UserService { @Autowired private UserRepository userRepository; public User getUser(Long id) { // Business logic centralized here return userRepository.findById(id).orElse(null); } } @RestController public class UserController { @Autowired private UserService userService; @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { return userService.getUser(id); } }
public class UserController { @Autowired private UserRepository userRepository; @GetMapping("/users/{id}") public User getUser(@PathVariable Long id) { // Directly accessing repository in controller return userRepository.findById(id).orElse(null); } }
| Pattern | Backend Logic Organization | Code Duplication | Response Time Impact | Verdict |
|---|---|---|---|---|
| Controller directly accesses repository | Mixed in controller | High duplication risk | Slower API responses | [X] Bad |
| Business logic in service layer | Centralized in service | Low duplication | Faster, consistent responses | [OK] Good |
getDiscountedPrice(100)?
public double getDiscountedPrice(double price) {
if (price > 50) {
return price * 0.9;
}
return price;
}@Service
public class UserService {
public void saveUser(User user) {
userRepository.save(user);
}
}