Labs ICT
โญ Pro Login

Defensive Programming

Techniques to make code resilient to unexpected inputs and states.

Defensive Programming

Defensive programming is a technique where you anticipate and handle potential problems before they cause failures. The goal is to write code that is resilient to unexpected inputs, invalid states, and edge cases.

Core Principles


  +---------------------------------------------------------+
  |           DEFENSIVE PROGRAMMING TECHNIQUES               |
  +---------------------------------------------------------+
  |                                                         |
  |   1. Validate All Inputs                                |
  |      - Check every parameter at the boundary            |
  |      - Reject or handle invalid values                  |
  |                                                         |
  |   2. Handle Edge Cases                                  |
  |      - Empty collections, null values, zero             |
  |      - Maximum/minimum values                           |
  |                                                         |
  |   3. Fail Fast                                          |
  |      - Detect errors as early as possible               |
  |      - Don't let invalid data propagate                 |
  |                                                         |
  |   4. Use Assertions for Invariants                      |
  |      - Document and enforce assumptions                 |
  |                                                         |
  |   5. Assume Hostile Environment                        |
  |      - Never trust external data                        |
  |      - Sanitize and validate everything                 |
  |                                                         |
  +---------------------------------------------------------+

Input Validation Example


  // BAD: No validation
  public void setAge(int age) {
      this.age = age;
  }

  // GOOD: Defensive validation
  public void setAge(int age) {
      if (age < 0 || age > 150) {
          throw new IllegalArgumentException(
              "Age must be between 0 and 150, got: " + age
          );
      }
      this.age = age;
  }

Null Safety


  // BAD: Risk of NullPointerException
  public String getUserName(User user) {
      return user.getName();
  }

  // GOOD: Null-safe
  public String getUserName(User user) {
      if (user == null) {
          return "Unknown";
      }
      String name = user.getName();
      return name != null ? name : "Unknown";
  }

Defensive Programming Guidelines

  • Validate all public API inputs at entry points
  • Use immutable objects where possible to prevent accidental modification
  • Apply the principle of least privilege โ€” grant minimum access
  • Log suspicious behavior for later analysis
  • Use bounded loops to prevent infinite iteration

Key Takeaways

  • Never trust input from external sources
  • Validate early, fail fast, and provide clear error messages
  • Handle edge cases explicitly
  • Defensive programming reduces bugs and improves reliability

๐Ÿงช Quick Quiz

What is defensive programming?