Pure Functions and Statelessness in Utility Classes
You'll learn why utility methods should depend only on their inputs, making them predictable and reliable.
What Does "Stateless" Mean?
A stateless method doesn't rely on or modify any stored information (fields). It acts purely on what you pass into it. Every time you call it with the same inputs, you get the same output—no surprises, no hidden dependencies.
Think of a stateless method like a vending machine formula: "2 quarters + 3 dimes = 80 cents." The answer is always the same for those inputs. The machine doesn't "remember" your last transaction or change its behavior based on how many times it's been used today.
Pure Functions: Input In, Output Out
A pure function is a method that:
- Returns a result based only on its parameters
- Doesn't modify any external state (no side effects)
- Always produces the same output for the same input
public class MathUtils {
private MathUtils() {} // prevents instantiation
// Pure, stateless method
public static int add(int a, int b) {
return a + b; // only uses parameters
}
// Pure, stateless method
public static double calculateArea(double radius) {
return 3.14159 * radius * radius; // only uses parameter
}
}
Notice how these methods don't access any fields—they compute results entirely from what you give them.
Why This Matters for Utility Classes
Utility classes should be tools, not objects with state. When methods are pure and stateless, they're:
- Predictable: No hidden behavior
- Testable: Easy to verify with different inputs
- Thread-safe: Multiple parts of your program can use them simultaneously without conflicts
Key Takeaway: Utility methods should be pure functions that depend only on their parameters, ensuring predictable, reliable behavior every time they're called.