Consider the two following examples:
public Something fetchSomething(String key) {
if(somethingsMap.containsKey(key)) {
return somethingsMap.get(key);
}
throw new IllegalStateException("key is missing");
}
versus
public Something fetchSomething(String key) {
if(!somethingsMap.containsKey(key)) {
throw new IllegalStateException("key is missing");
}
return somethingsMap.get(key);
}
Is there any general consensus which is considered "better"/more clean/preferred. Ending in normal flow or ending in exception flow.
Or is this solely opinionated?
Best Answer
Rephrased this question is make exception the de facto behaviour or make happy path the de facto behaviour the method implement.
This:
is a fail-fast implementation.
from wikipedia.
If the question is just about the code style then it should be answered by the code style guide lines the team follows 'cause once decided after a while either way of writing the code is readable, clean, preferred.