user1950349
user1950349

Reputation: 5146

Best way to return null from a method?

I need to get the hostname of the machine where the code is running. I have a method like this:

private static final String getHostName() {
    try {
        return InetAddress.getLocalHost().getCanonicalHostName().toLowerCase();
    } catch (UnknownHostException ex) {
        logger.logError("error = ", ex);
    }

    // this looks pretty odd to me, are there any better options?
    // like with guava or apache commons?
    return null;
}

And this is the way I am using above getHostName() method

private static String findData() {
    String host = getHostName();
    if(host != null) {
        // do something
    }
    // otherwise do something else
}

My question is - returning null looks pretty odd to me. Are there any other options with Guava or Apache Commons that I can use here?

Upvotes: 2

Views: 7854

Answers (4)

Fritz Duchardt
Fritz Duchardt

Reputation: 11870

Guava provides the Optional class exactly for the purpose of not having to return null.

However, if you are already using Java 8, please note that this also comes with an Optional class and you might prefer to use that one (for the sake of being independent from an external library).

Upvotes: 1

Mick Mnemonic
Mick Mnemonic

Reputation: 7956

If you don't want to throw an Exception and want to clearly handle cases where the value is missing, you can return an Optional

private static final Optional<String> getHostName() {
    try {
        return Optional.of(
            InetAddress.getLocalHost().getCanonicalHostName().toLowerCase());
    } catch (UnknownHostException ex) {
        logger.logError("error = ", ex);
        return Optional.absent();
    }
}

The client code would look like this:

private static String findData() {
    Optional<String> optionalHost = getHostName();
    if (optionalHost.isPresent()) {
        String host = optionalHost.get();
        // do something
    } else {
        // otherwise do something else
    }
}

More info about avoiding and handling null here.

Upvotes: 7

oopexpert
oopexpert

Reputation: 755

That returning null looks odd to you shows that you have the right feeling. Never return null because you have to handle the return value (if x == null ...). So throw the exception and catch it at the proper place. If you don't want it to be signature relevant catch it early wrap it in a runtime exception and rethrow it. After that catch it at the proper place... did I already mentioned it?

Upvotes: 1

ruakh
ruakh

Reputation: 183270

If you are expecting callers to handle this case, then you can either use Optional (either from Guava or from JDK 8), or else simply let the exception bubble up (with or without logging it first).

If you are not expecting this case to ever arise, and you don't expect callers to handle it, but you're simply trying to satisfy the "catch or specify" requirement, then you can wrap it in an unchecked exception and raise that.

Upvotes: 3

Related Questions