gpt4 book ai didi

java - 从方法返回 null 的最佳方式?

转载 作者:行者123 更新时间:2023-11-29 09:47:31 26 4
gpt4 key购买 nike

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

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;
}

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

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

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

最佳答案

如果你不想抛出一个Exception并且想清楚地处理缺失值的情况,你可以返回一个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();
}
}

客户端代码如下所示:

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

关于避免和处理 null here 的更多信息.

关于java - 从方法返回 null 的最佳方式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30281179/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com