简体   繁体   中英

Using Optional<T> from java SE 8

Hi I want to know how I can use Optional in java SE 8 in the function below.

public URL getAuthenticatedURL() throws MalformedURLException {
    if (log != null){
        log.writeINFOToLog("Fetching authentication URL...");
    }
    else{
        Log.initLog();
        log.writeINFOToLog("Fetching authentication URL...");
    }
    try{
        String url = String.format("%s://%s%s?username=%s&password=%s",getProtocol(), getHost(), getPath(), getUsername(), getPassword());
        URL returnURL = new URL(url);
        return returnURL;
    }
    catch (MalformedURLException ex){
        log.writeExceptionToLog(ex);
        return null;
    }
}

I want to be able to handle the scenario where values involved in constructing the URL is null or empty.

I think it is more reasonable to use Supplier than Optional , because getAuthenticatedURL() has no argument and generates an Object(URL).

It looks like:

Supplier<URL> supplier = () -> {
    ...
    try {
        return new URL(...);
    } catch (MalformedURLException e) {
        return null;
    }
};
URL url = supplier.get();

After some research, I think its best that I avoid nulls, since it does not make much sense to have a null.

Here is my code snippet of the same function once I have used Optional<URL>

public Optional<URL> getAuthenticatedURL() throws MalformedURLException {
    if (log != null){
        log.writeINFOToLog("Fetching authentication URL...");
    }
    else{
        Log.initLog();
        log.writeINFOToLog("Fetching authentication URL...");
    }
    String url = String.format("%s://%s%s?username=%s&password=%s",getProtocol(), getHost(), getPath(), getUsername(), getPassword());
    return Optional.ofNullable(new URL(url));
}

So when I call the function the code will be something like this.

if(getAuthenticatedURL.isPresent()){
  URL val = getAuthenticatedURL.get();
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM