Null Object Pattern
In many systems, we constantly check for null before calling a method:
if (service != null) {
service.execute();
}
This leads to repetitive null checks scattered across the codebase ❌.
The Null Object Pattern solves this by providing a default "do nothing" object instead of using null.
🔹 Problem
Suppose you have a logging system:
Sometimes, you may want no logging at all. Instead of returning null and forcing clients to check, what if we return a NullLogger that does nothing?
🔹 Solution – Null Object Pattern
We create a special class that implements the same interface but with empty behavior. Now, the client can call methods without worrying about null.
🔹 Example in Java
// Logger interface
interface Logger {
void log(String message);
}
// Concrete implementations
class ConsoleLogger implements Logger {
public void log(String message) {
System.out.println("Console: " + message);
}
}
class FileLogger implements Logger {
public void log(String message) {
// pretend to write in file
System.out.println("File: " + message);
}
}
// Null Object
class NullLogger implements Logger {
public void log(String message) {
// Do nothing
}
}
// Client
public class Main {
public static void main(String[] args) {
Logger logger = getLogger("NONE");
logger.log("This will not crash or require null checks!");
}
static Logger getLogger(String type) {
if (type.equals("CONSOLE")) return new ConsoleLogger();
if (type.equals("FILE")) return new FileLogger();
return new NullLogger(); // instead of null
}
}
Benefits
✅ Eliminates repetitive null checks
✅ Provides a default safe behavior
✅ Keeps client code clean and focused
✅ Great for optional services (logging, caching, analytics)
🔹 Real-world use cases
💡 The Null Object Pattern turns “nothing” into a real object, making your code more elegant, clean, and error-free.