Avoid violation of DRY with ternary?

徘徊边缘 提交于 2021-01-28 02:06:43

问题


Here's what I have.

Map data = new HashMap<>(); // assume this has been populated

public int getLastestVersion() {
    // data.get("PATH_TO_DESIRED_POINT") would be an integer
    return data.get("PATH_TO_DESIRED_POINT") == null ? 0 : (int)data.get("PATH_TO_DESIRED_POINT");
}

I'm trying to avoid violating DRY, but I want to be able to keep the simplicity of the ternary. Is there something I can do?


回答1:


If you are using Java8, you can use getOrDefault method:

return data.getOrDefault("PATH_TO_DESIRED_POINT", 0);



回答2:


You could assign the result to a final local variable. That way the compiler is free to inline it, and you don't have to repeat the calls to get in your Map<String, Integer> data. In Java 8+, something like

final Integer v = data.get("PATH_TO_DESIRED_POINT");
return v != null ? v : 0;


来源:https://stackoverflow.com/questions/33358468/avoid-violation-of-dry-with-ternary

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