Performance: Business logic in services
This affects server response time and how quickly the backend can process requests, impacting the overall user experience and perceived page speed.
Jump into concepts and practice - no test required
public User processUserData(User user) {
validateUser(user); // Separate validation
User savedUser = userRepository.save(user); // DB call isolated
int score = calculateScore(savedUser); // Pure logic separated
savedUser.setScore(score);
return savedUser;
}
private void validateUser(User user) {
if (user.getName() == null) {
throw new IllegalArgumentException("Name required");
}
}public User processUserData(User user) {
// Business logic mixed with database calls and validation
if (user.getName() == null) {
throw new IllegalArgumentException("Name required");
}
user.setScore(calculateScore(user));
userRepository.save(user); // Direct DB call inside logic
return user;
}| Pattern | Server Processing Time | Database Calls | Code Complexity | Verdict |
|---|---|---|---|---|
| Mixed logic with DB calls inline | High (slow) | Multiple per request | High | [X] Bad |
| Separated validation, DB, and logic | Low (faster) | Minimal per request | Low | [OK] Good |
@Service annotation marks classes that hold business logic in Spring Boot.@Service to mark service classes that contain business logic.@Service correctly on the class declaration.calculateDiscount(150) is called?public class DiscountService {
public int calculateDiscount(int price) {
if (price > 100) {
return price * 20 / 100;
} else {
return price * 10 / 100;
}
}
}@Service
public class OrderService {
@Autowired
private OrderRepository orderRepository;
public void saveOrder(Order order) {
orderRepository.save(order)
}
}orderRepository.save(order) is missing a semicolon at the end.public class PricingService {
private final DiscountService discountService;
private final TaxService taxService;
public PricingService(DiscountService discountService, TaxService taxService) {
this.discountService = discountService;
this.taxService = taxService;
}
public double calculateFinalPrice(double price) {
// Fill in logic here
}
}