본문 바로가기

개발기술/설계|디자인패턴

Code Structuring Technique

Early Return Pattern

  • used to exit a function as early as possible when a condition is not met, preventing unnecessary computations.
  • Why Use It?
    • Improves readability by handling edge cases first.
    • Avoids unnecessary processing when conditions are not met.
    • Reduces the depth of nested logic.

Example Without Early Return (Deep Nesting)

public void processUser(UserDto dto) {
    if (dto != null) {
        if (dto.getAuthId() != null) {
            if (dto.getCompanyId() != null) {
                // Proceed with user creation...
            }
        }
    }
}

 

Refactored With Early Return

public void processUser(UserDto dto) {
    if (dto == null) return;
    if (dto.getAuthId() == null) return;
    if (dto.getCompanyId() == null) return;

    // Proceed with user creation...
}

 

 

 

Sequential Processing Pattern" (Inline Processing)

  • The Sequential Processing Pattern (or Inline Processing) ensures that all logic flows in a structured way without early exits, handling conditions inline as they appear
  • Why Use It?
    • Ensures all related logic is executed in a predictable order.
    • Reduces abrupt exits, making the flow easier to follow.
    • Keeps return statements centralized at the end.
public void processOrder(Order order) {
    validateOrder(order);  // Step 1
    reserveStock(order);   // Step 2
    processPayment(order); // Step 3
    shipOrder(order);      // Step 4
}