Lesson 5 of 8
Defensive Programming & Guard Clauses
Defensive programming means validating inputs early and explicitly, rather than letting bad data propagate and cause obscure failures deep in your code. Guard clauses validate at the method entry and fail fast with clear error messages.
Guard Clauses & Input Validation
import java.util.Objects;
public class BookService {
// ❌ NO guard clauses - bad data propagates silently
public void addBookBad(String isbn, String title, double price) {
// If isbn is null, NullPointerException somewhere inside - unclear cause
catalog.put(isbn.trim(), new Book(isbn, title, price));
}
// ✅ Guard clauses - fail fast with clear messages
public void addBook(String isbn, String title, double price) {
// Validate first - return/throw before doing any work
Objects.requireNonNull(isbn, "isbn must not be null");
Objects.requireNonNull(title, "title must not be null");
if (isbn.isBlank()) throw new InvalidIsbnException(isbn);
if (title.isBlank()) throw new IllegalArgumentException("title must not be blank");
if (price < 0) throw new IllegalArgumentException("price must be >= 0, got: " + price);
if (catalog.containsKey(isbn)) throw new DuplicateIsbnException(isbn);
// All checks passed - safe to proceed
catalog.put(isbn.trim(), new Book(isbn.trim(), title.trim(), price));
}
// Validate and normalise at the entry point
public Optional<Book> findByIsbn(String isbn) {
if (isbn == null || isbn.isBlank()) return Optional.empty(); // tolerate, don't throw
return Optional.ofNullable(catalog.get(isbn.trim()));
}
// Assertion for internal invariants (not user input)
public double calculateTotalValue() {
double total = catalog.values().stream()
.mapToDouble(Book::getPrice)
.sum();
assert total >= 0 : "Total catalog value should never be negative: " + total;
return total;
}
// Immutable parameter objects prevent invalid state from being passed
public record BorrowRequest(String isbn, String memberId, int daysAllowed) {
public BorrowRequest { // compact constructor validates
Objects.requireNonNull(isbn, "isbn required");
Objects.requireNonNull(memberId, "memberId required");
if (daysAllowed < 1 || daysAllowed > 60)
throw new IllegalArgumentException("daysAllowed must be 1-60");
}
}
}Defensive Programming Principles
- Fail fast - detect errors immediately at the point where bad data enters your system.
- Be explicit - include the invalid value in the error message: 'price must be >= 0, got: -5.0'
- Objects.requireNonNull(obj, message) - standard null check with message (throws NPE)
- Validate parameters at method entry - not deep inside logic where cause is obscure.
- Distinguish between validation (user input) and assertions (programmer invariants).
- Tolerate ambiguity in optional inputs (return empty Optional), but throw for clearly wrong required inputs.
Quick Quiz
Tip
Tip
Practice Defensive Programming Guard Clauses in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.
Visual architecture and concepts for Defensive Programming & Guard Clauses
Practice Task
Note
Practice Task - (1) Write a working example of Defensive Programming Guard Clauses from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.
Common Mistake
Warning
A common mistake with Defensive Programming Guard Clauses is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready java code.
Key Takeaways
- Defensive programming means validating inputs early and explicitly, rather than letting bad data propagate and cause obscure failures deep in your code.
- Fail fast - detect errors immediately at the point where bad data enters your system.
- Be explicit - include the invalid value in the error message: 'price must be >= 0, got: -5.0'
- Objects.requireNonNull(obj, message) - standard null check with message (throws NPE)
Finished this lesson?