Null Object Design Pattern
Aliases π: None
Description π: The Null Object is a mock object that is used to let programmers handle when or how they will handle something null.
For instance, if we fetch records from a database and some have null attributes, we might not want to handle it if we didn't plan to use the nullable attribute.
Advantages β
- Flexibility
Disadvantages π«
- ???
Notes π
- None
Java Implementation
public interface IPerson {
String name();
}
record Person(String name) implements IPerson {
}
public class NullPerson implements IPerson {
@Override
public String name() {
return "John Doe";
}
}
We can code the default behavior however we want:
- throws an exception (ex: unsupported operation)
- returns
false
- returns
0
- returns
null
- returns
undefined
- returns another NullObject
- ...