2

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");
}
Oliveira
  • 1,281
  • 1
  • 11
  • 19

3 Answers3

6

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.

Holger
  • 285,553
  • 42
  • 434
  • 765
  • 1
    I like the `filter` idea, but I think that checking `isPresent()` would be more readable. `if (accountType.requiresCode() && !code.filter(x->!empty(x)).isPresent()) { ... }` – Paolo Fulgoni Feb 12 '15 at 11:14
1

You could use

if (accountType.requiresCode() && code.map(this::empty).orElse(true))

but I'm not sure it makes the code more readable.

JB Nizet
  • 678,734
  • 91
  • 1,224
  • 1,255
  • Isn’t this what `Optional.filter` is for? E.g. `code.filter(s -> !empty(s)).isPresent()`; using `map` and `orElse` with `boolean`s feels so wrong… – Holger Feb 12 '15 at 10:54
  • Using filter is indeed another solution. I just didn't think about it. I agree it's cleaner. But I'm still not sure it makes the code more readable. – JB Nizet Feb 12 '15 at 11:00
  • I guess, in this case none of these lambda using variants make the code more readable… – Holger Feb 12 '15 at 11:02
0

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");
}
Community
  • 1
  • 1
Łukasz Rzeszotarski
  • 5,791
  • 6
  • 37
  • 68