Obscur Moirage Obscur Moirage - 13 days ago 6
Java Question

Try-Catch, optional/null, and lambda

Considering the following code :


  • obj is not modified after been intialised by service, but, due to try/catch block, it is not considered as effectively final.
    is there a way to avoid this ?

  • Does Optional might be considered as a universal method to avoid null checking ? In this example, service would throw exception instead or returning null, or always return Optional ?

    //to be used outside try/catch block, object must be initialized as null
    SomeObject obj = null;
    try {
    obj = someService.getSomeObject();
    } catch (ServiceException e) {
    LOG.error("Something nasty happened", e);
    }

    //the service could have returned a null object
    if(obj == null) {
    LOG.error("Obj is null");
    }

    //to be used in a lambda, object must be final
    SomeObject objCopy = obj;
    boolean test = someList.stream()
    .anyMatch(o->o.equals(objCopy));


Answer

Just split the try/catching into a separate method (This is generally good practice as it makes the code more readable. Refer to "Clean Code" by Robert Cecil Martin)

final SomeObject obj = getObjFromService(someService);

...

private Optional<SomeObject> getObjFromService(Service someService) {
    try {
        return Optional.of(someService.getSomeObject());
    } catch (ServiceException e) {
        LOG.error("Something nasty happened", e);
    }
    return Optional.empty();
}

You could also return null from the method getObjFromService, you can still declare the variable final since you-re only assigning it once.

Comments