I am wondering what is the best way of checking potentially null method arguments.
First reasonable approach is with guava:
String validatedValue= Optional.fromNullable(input).or("defaultValue");
Second reasonable approach is with regular java. It might have advantage of being easy to understand for someone who does not know guava. However it still shows "low-level" code.
String validatedValue= input !=null ? input : "empty";
Or third approach. On the one hand looks nice in main method. On the other it potentially spawns a lot of small private methods.
String validatedValue = getValidatedValue(input); //this private method will contain option two
For now it seems that second or third approach is better and Optional should not be used in this case. Could someone tell what is best practice in this case?
Although I would not call this "validation", the preferred method for supplying deafult if null is similar to #2 (if not #2 itself) - using Guava's Objects.firstNonNull
(since Guava 18 it's placed in MoreObjects
):
String value = Objects.firstNonNull(input, "empty"); // MoreObjects since 18.0
which internally does:
return first != null ? first : checkNotNull(second);
With static import it's just:
String nonNullValue = firstNonNull(input, "empty");
but which one will you use is just a matter of preference.
P.S. I'd use Optional
only in one case - if you want lazy evaluated default, but with strings it isn't a case. Private method only for null check is overkill, but if you have other assumptions about value, it's generally considered a good practice to use small private methods with meaningful names for this (see Clean Code by Uncle Bob).