问题
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