Home > Enterprise >  Use Optional instead of null check
Use Optional instead of null check

Time:08-09

I have to check if an attribute of an object is null or not. Depending on the above check I have to update another attribute in the same object. Is it possible to use Optional class and its methods to replace null checks?

if(userData.getSubscription()==null){
    userData.setFees(Enum.ZERO);
} else {
    userData.setFees(Enum.HUNDRED);
}

Let me know if this can be replaced with a single line using Java 8 Optional class or other features.

CodePudding user response:

You could do something like

Optional::ofNullable(userData.getSubscription()).map(any -> Enum.HUNDRED).orElse(Enum.ZERO);

However I don't see much benefit to that over @T.J. Crowder's suggestion from the comments

userData.getSubscription() == null ? Enum.ZERO : Enum.HUNDRED

CodePudding user response:

Maybe you want: userData.setFees(Objects.isNull(userData.getSubscription()) ? Enum.ZERO : Enum.HUNDRED)

CodePudding user response:

The main use of Optional is to prevent you from forgetting to check for null. Thus, it would only be useful if the Optional type was returned from getSubscription(). Then you could do:

userData.setFees(userData.getSubscription().map(x -> Enum.HUNDRED).orElse(Enum.ZERO));

But if you can't or don't want to change getSubscription() to return Optional, then there is no point in using Optional here. Just do this:

userData.setFees(userData.getSubscription() == NULL ? Enum.ZERO : Enum.HUNDRED);

By the way, if Enum.ZERO and Enum.HUNDRED are just names representing 0 and 100, then that's not a good idea. The words "ZERO" and "HUNDRED" are just as much a "magic number" as the numbers 0 and 100 themselves. You should name your enums something descriptive like "FREE_OF_CHARGE" and "FULL_PRICE".

  • Related