从方法返回null的最佳方法?

use*_*349 1 java apache-commons guava

我需要获取运行代码的机器的主机名.我有这样的方法:

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;
}
Run Code Online (Sandbox Code Playgroud)

这就是我使用上述getHostName()方法的方式

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

我的问题是 - 返回null看起来很奇怪.我可以在这里使用Guava或Apache Commons的其他选项吗?

Mic*_*nic 6

如果您不想抛出异常并希望清楚地处理缺少值的情况,则可以返回 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

客户端代码如下所示:

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

有关在此处避免和处理null的更多信息.