HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Optional Consumer for ifNotPresent

Submitted by: @import:stackexchange-codereview··
0
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:

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 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 final

Okay then, three things:

  • Your factory method takes an existing Optional, but you don't provide a getter or anything for the Optional, which means that you could also provide an ordinary OptionalConsumer ofNullable(T value)

Context

StackExchange Code Review Q#105428, answer score: 2

Revisions (0)

No revisions yet.