1. Guard Clause(조기 반환)
// Bad
public void process(Order order) {
if (order != null) {
if (order.getItems() != null && !order.getItems().isEmpty()) {
if (order.getStatus() == PENDING) {
// 실제 로직
}
}
}
}
// Good
public void process(Order order) {
if (order == null) throw new IllegalArgumentException("order is null");
if (CollectionUtils.isEmpty(order.getItems())) throw new IllegalStateException("empty items");
if (order.getStatus() != PENDING) return;
// 실제 로직 (들여쓰기 1단계)
}
2. 생성자에서 불변식 보장
public class Money {
private final long amount;
private final Currency currency;
public Money(long amount, Currency currency) {
if (amount < 0) throw new IllegalArgumentException("음수 불가");
this.amount = amount;
this.currency = Objects.requireNonNull(currency);
}
}
// 객체가 존재한다 = 항상 유효하다. 이후 검증 불필요
3. 계층별 검증 분리
// Controller: 형식 검증
@PostMapping("/orders")
public ResponseEntity<?> create(@Valid @RequestBody OrderRequest req) { ... }
// Service: 비즈니스 규칙 검증
public Order create(OrderCommand cmd) {
User user = userRepository.findById(cmd.userId())
.orElseThrow(() -> new UserNotFoundException(cmd.userId()));
if (user.isBlocked()) throw new BlockedUserException();
if (!stockService.hasStock(cmd.items())) throw new OutOfStockException();
...
}
// Domain: 불변식 검증 (위 Money 예시)
4. Null 대신 Optional / 빈 컬렉션
// Bad
public List<Order> findByUser(Long id) {
if (id == null) return null; // 호출자가 NPE 지뢰밟음
public Optional<User> findByEmail(String email) { ... }
// Good
public List<Order> findByUser(Long id) {
if (id == null) return Collections.emptyList();
}
public Optional<User> findByEmail(String email) { ... }
5. 예외에 컨텍스트 담기
// Bad
throw new IllegalArgumentException("잘못된 값");
// Good
throw new InvalidOrderException(
String.format("주문 금액 초과: orderId=%s, amount=%d, limit=%d",
orderId, amount, LIMIT)
);
6. 원자성 확보 - 검증 후 실행