Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 692
mkUltra Avatar asked Jul 16 '26 00:07

mkUltra


2 Answers

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.

like image 199
Lukas Eder Avatar answered Jul 18 '26 14:07

Lukas Eder


Instead of assigning to result, substitute result = with return. In effect removing result.

That semantically is actually a kind of "finally."

like image 32
Joop Eggen Avatar answered Jul 18 '26 14:07

Joop Eggen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!