End method in normal flow versus exception flow

coding-styleexceptionsjava

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:

public Something fetchSomething(String key) {
    if(!somethingsMap.containsKey(key)) {
        throw new IllegalStateException("key is missing");
    }

    return somethingsMap.get(key);
}

is a fail-fast implementation.

In systems design, a fail-fast system is one that immediately reports at its interface any condition that is likely to indicate a failure. Fail-fast systems are usually designed to stop normal operation rather than attempt to continue a possibly flawed process. Such designs often check the system's state at several points in an operation, so that any failures can be detected early. The responsibility of a fail-fast module is detecting errors, and then letting the next-highest level of the system handle them.

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.

Related Topic