patternjavaMinor
Optional Consumer for ifNotPresent
Viewed 0 times
optionalifnotpresentconsumerfor
Problem
As Optional have only ifPresent and not have another function to be run in false case so I did the below class for that, please check it and give me your feedback:
}
Then :
public class OptionalConsumer {
private Optional optional;
private OptionalConsumer(Optional optional) {
this.optional = optional;
}
public static OptionalConsumer of(Optional optional) {
return new OptionalConsumer<>(optional);
}
public OptionalConsumer ifPresent(Consumer c) {
optional.ifPresent(c);
return this;
}
public OptionalConsumer ifNotPresent(Runnable r) {
if (!optional.isPresent())
r.run();
return this;
}}
Then :
Optional o = Optional.of(...);
OptionalConsumer.of(o).ifPresent(s ->System.out.println("isPresent "+s))
.ifNotPresent(() -> System.out.println("! isPresent"));Solution
Two things:
-
Your class only provides a
-
Okay then, three things:
-
Your class only provides a
if-else statement, really. If it would also provide all the features in the existing java.util.Optional, it would have been slightly more useful.-
private Optional optional; should definitely be marked with finalOkay then, three things:
- Your factory method takes an existing
Optional, but you don't provide a getter or anything for theOptional, which means that you could also provide an ordinaryOptionalConsumer ofNullable(T value)
Context
StackExchange Code Review Q#105428, answer score: 2
Revisions (0)
No revisions yet.