I really like how the guava library allows simple single-line installations to check for null:
public void methodWithNullCheck(String couldBeNull) { String definitelyNotNull = checkNotNull(couldBeNull);
Unfortunately, for a simple argument check, you need at least two lines of code:
public void methodWithArgCheck(String couldBeEmpty) { checkArgument(!couldBeEmpty.isEmpty()); String definitelyNotEmpty = couldBeEmpty;
however, you can add a method that could check the argument and return a value if the test was successful. The following is an example of verification and how to implement it:
public void methodWithEnhancedArgCheck(String couldBeEmpty) { String definitelyNotEmpty = EnhancedPreconditions.checkArgument(couldBeEmpty, !couldBeEmpty.isEmpty()); //... } static class EnhancedPreconditions { public static <T> T checkArgument(T reference, boolean expression) { if (!expression) { throw new IllegalArgumentException(); } return reference; } }
I just wondered what the design is and if it is worth putting a function request for this.
EDIT : @ Nice, yes, method checks can be awkward. However, the checks in the constructors for zeros look really good and save a lot of time debugging NPEs:
public class SomeClassWithDependency { private final SomeDependency someDependency; public SomeClassWithDependency(SomeDependency someDependency) { this.someDependency = checkNotNull(someDependency); }
EDIT . I accept the answer to Nizet because I agree with him on the side effects and consistency. Also, if you look at the Xaerxess comment, this seems to be perplexing among other developers.
source share