Best Practices for Variable Capture
You'll learn idiomatic patterns for managing captured variables in lambdas and when to refactor for clarity.
Now that you understand how variable capture works and its restrictions, let's explore how to write clean, maintainable lambda expressions that handle captured state elegantly.
Core Principles
Keep capture minimal. The fewer variables your lambda captures, the easier it is to understand and test. If your lambda needs many external variables, consider refactoring it into a named method or separate class.
Prefer parameters over capture. When possible, pass data as parameters rather than capturing from the enclosing scope:
// Less clear: captures threshold
Predicate<Integer> test = n -> n > threshold;
// Better: explicit parameter
BiPredicate<Integer, Integer> test = (n, threshold) -> n > threshold;
Avoid workarounds when they obscure intent. Arrays and wrappers let you mutate captured "variables," but they signal complexity. If you need mutable state, a traditional class may be clearer:
// Code smell: using array to bypass effectively final
int[] counter = {0};
list.forEach(item -> counter[0]++);
// Consider: use a Stream reduction instead
long count = list.stream().count();
When to Refactor
If your lambda captures multiple variables or uses workarounds, extract it to a method or create a dedicated class. This improves testability and makes the logic explicit.
For instance variables, remember that this references are fine to capture—lambdas naturally work with the enclosing object's state.
Key Takeaway: Keep lambdas simple by minimizing variable capture; when complexity grows, refactor to named methods or classes for better clarity and maintainability.