The main difference (and probably advantage) of this template is a distinctive feature. Consider the following method definition:
public static int length(String str);
This method calculates the length of the given string. But can the argument be null ? What will this method do? Throw an exception? Return 0? Return -1? We do not know.
Some partial solution can be achieved by writing a good java document. The next and slightly better solution is the JSR305 annotattion @Nullable or @NotNullable , which the developer can ignore.
If you are using a Null object template (for example, optional from guava or java 8), your code looks like this:
public static int length(Optional<String> str);
Therefore, the developer must take care to bind his string to Optional, and therefore understands that this argument may be null. Trying to get a value from Optional, which contains an exception for exceptions, which does not always happen when working with regular null .
Obviously, you are right that using this template leads to some additional processor and memory consumption, which in most cases is not significant.
source share