Using Java8, this could be done:
Optional.ofNullable(realResult).orElse(mockResult);
instead of:
if(realResult == null)
return mockResult;
return realResult;
Question: Could we adobt Booleans to java8? or in other words, can we write something like that:
Boolean.valueOf(boolVar).ifTrue(trueResult).orElse(falseResult);
instead of:
if(boolVar)
return trueResult;
return falseResult;
Edit #1 Thanks for suggesting ternary operations, still wondering if we can?
How about using the terniary operator that's already included in the language?
boolVar ? trueResult : falseResult
EDIT: that's how it would look like if you really want such a class:
public class Conditional<T> {
private final boolean condition;
private T valueWhenTrue;
public static Conditional valueOf(boolean condition) {
return new Conditional(condition);
}
private Conditional(boolean condition) {
this.condition = condition;
}
public Conditional ifTrue(T valueWhenTrue) {
this.valueWhenTrue = valueWhenTrue;
return this;
}
public T orElse(T valueWhenFalse) {
return condition ? valueWhenTrue : valueWhenFalse;
}
}
Usage:
Conditional.valueOf(boolVar).ifTrue(trueResult).orElse(falseResult)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With