Validating inputs using Optional

风格不统一 提交于 2019-12-12 11:02:33

问题


I have a CreateOrder instance which has some String, Integer and Double states in it. When I create an object for CreateOrder in my JUnit test and send it over, I am able to validate String attributes but not Integer using Optional API as follows -

String aoid = Optional.ofNullable(createOrder.getAltorderid()).orElse("");

int quantity = Integer.parseInt(each.getQty());
double amount = Double.parseDouble(each.getPrice().getAmount());

Like for aoid, I also want to user ofNullable() for integer but not able to figure it out how. My intention behind this is to make my code safe from NullPointerExceptions and hence I want to make the user of powerful Optional for Integer and Double. I am fairly new to Java 8 and getting confused if I should use OptionalInt or Optional<Integer>? If Optional<Integer>, how to use it like I have used for String?


回答1:


Try this

Optional.ofNullable(each.getQty()).map(Integer::valueOf).orElse(0)



回答2:


Integer.parseInt(each.getQty())

is safe enough since if each.getQty is null, you would end up getting a NumberFormatException and that should be the behavior when you're trying to parse a String to an Integer and are not certain of it.

On the other hand still, you can default to 0 for the value being null as :

int quantity = Optional.ofNullable(each.getQty())
                       .map(Integer::parseInt)
                       .orElse(0);

similarily for amount

double amount = Optional.ofNullable(each.getPrice().getAmount())
        .map(Double::parseDouble)
        .orElse(Double.NaN);



回答3:


First of all I think you're misunderstanding the purpose of Optional.

The main point of Optional is to provide a means for a function returning a value to indicate the absence of a return value. See this discussion. This allows the caller to continue a chain of fluent method calls.

Stuart Marks, Java and OpenJDK developer

So in order to use Optional API properly you need to rethink your code. Assuming your each has nullable aoid your .getAltOrderId() method should be implemented like this:

Optional<String> getAltOrderId() {
    return Optional.ofNullable(this.aoid);
}  

Then you can use it as follows:

String aoid = createOrder.getAltOrderId().orElse("");

Please read this post for more detailed explanation.

Assuming you modified your .getQty() method to return Optional<String>, this should do what you need:

int quantity = each.getQty()
                   .map(Integer::valueOf)
                   .orElse(0);


来源:https://stackoverflow.com/questions/54124427/validating-inputs-using-optional

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!