Search code examples
javaexceptionfinal

final Entity with try catch in Java


This is my code:

    SomeResult result = null;

    try {
        if(isOK) {
            result = service.getOK();
        }
    } catch (Exception e) {
        //logging
    }

    if(result == null) {
        result = service.getKO();
    }

    return result;

I want to make SomeResult result final like this:

final SomeResult result;

It is possible with one exit-point?


Solution

  • This could be done with a library like vavr, which implements the Try monad (i.e. turning the try-catch statement into an expression):

    public SomeResult getResult() {
        final SomeResult result;
        result = isOK ? Try.of(service::getOK).getOrElse(service::getKO) : service.getKO();
        return result;
    }
    

    But then, what's the point of assigning the value to a local variable? It would be just the same as returning it immediately:

    public SomeResult getResult() {
        return isOK ? Try.of(service::getOK).getOrElse(service::getKO) : service.getKO();
    }
    

    ... in case of which, you might want to prefer Joop's answer with multiple return statements after all, which doesn't rely on a third party library.