How can I do this with Java 8 Lambdas:
Optional<String> code;
if (accountType.requiresCode() && (!code.isPresent() || empty(code.get()))) {
new IllegalArgumentException("Account type " + accountType + " requires code");
}
How can I do this with Java 8 Lambdas:
Optional<String> code;
if (accountType.requiresCode() && (!code.isPresent() || empty(code.get()))) {
new IllegalArgumentException("Account type " + accountType + " requires code");
}
You can rewrite the code as
Optional<String> code;
if (accountType.requiresCode()) code.filter(x->!empty(x)).orElseThrow(
() -> new IllegalArgumentException("Account type " + accountType + " requires code")
);
or, assuming that your empty(code.get())
actually meant code.get().isEmpty()
:
Optional<String> code=Optional.empty();
if (accountType.requiresCode()) code.filter(x->!x.isEmpty()).orElseThrow(
() -> new IllegalArgumentException("Account type " + accountType + " requires code")
);
But it doesn’t really add to readability. Lambdas aren’t always better than ordinary code.
You could use
if (accountType.requiresCode() && code.map(this::empty).orElse(true))
but I'm not sure it makes the code more readable.
According to this question Valid usage of Optional type in Java 8 Optional is not a good choice here, though technically possible.
You can rewrite using StringUtils to the much nicer:
final String code = getCodeFromSomething();
if (accountType.requiresCode() && StringUtils.isEmpty(code)) {
new IllegalArgumentException("Account type " + accountType + " requires code");
}