-
Enhancement
-
Resolution: Not an Issue
-
P5
-
None
-
None
Objects.requireNonNull() does convenient argument checking against null. There should be something similar that does argument checking against a predicate. The signature would be something like:
T require(T obj, Predicate<T> pred)
The object would be checked against the predicate. If the predicate returns true, the object is returned. If the predicate returns false, IllegalArgumentException is thrown. Overloads could be provided such as
T require(T obj, Predicate<T> pred, String message)
T require(T obj, Predicate<T> pred, Supplier<String> messageSupplier)
similar to the overloads of Objects.requireNonNull().
For example, suppose an object's constructor requires a string argument whose length must be exactly 1. This would be written today as:
MyObject(String arg) {
if (arg.length() != 1) {
throw new IllegalArgumentException("arg must be length 1");
}
field = arg;
}
It would be nice to rewrite this as
MyObject(String arg) {
field = Objects.require(arg, s -> s.length() == 1, "arg must be length 1");
}
This would also have to play nicely with null-checking of arguments, something like
MyObject(String arg) {
field = Objects.require(arg, s -> Objects.requireNonNull(s).length() == 1, "arg must be length 1");
}
For checking of primitive arguments (for example, int) something could be added to java.lang.Integer like:
static int require(int i, IntPredicate pred)
and possibly also for Long and Double. (Since those are the types we have functional interfaces for.)
T require(T obj, Predicate<T> pred)
The object would be checked against the predicate. If the predicate returns true, the object is returned. If the predicate returns false, IllegalArgumentException is thrown. Overloads could be provided such as
T require(T obj, Predicate<T> pred, String message)
T require(T obj, Predicate<T> pred, Supplier<String> messageSupplier)
similar to the overloads of Objects.requireNonNull().
For example, suppose an object's constructor requires a string argument whose length must be exactly 1. This would be written today as:
MyObject(String arg) {
if (arg.length() != 1) {
throw new IllegalArgumentException("arg must be length 1");
}
field = arg;
}
It would be nice to rewrite this as
MyObject(String arg) {
field = Objects.require(arg, s -> s.length() == 1, "arg must be length 1");
}
This would also have to play nicely with null-checking of arguments, something like
MyObject(String arg) {
field = Objects.require(arg, s -> Objects.requireNonNull(s).length() == 1, "arg must be length 1");
}
For checking of primitive arguments (for example, int) something could be added to java.lang.Integer like:
static int require(int i, IntPredicate pred)
and possibly also for Long and Double. (Since those are the types we have functional interfaces for.)