gpt4 book ai didi

java - 字符串 Java 代码检查

转载 作者:行者123 更新时间:2023-12-02 02:15:45 24 4
gpt4 key购买 nike

我想优化Java源代码。我实现了此文件下载代码:

if (!file.exists())
{
response.sendError(HttpServletResponse.SC_NOT_FOUND, "No file " + reportPath);
return;
}

if (!file.canWrite())
{
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Can't write in file " + reportPath);
return;
}

if (!file.canRead())
{
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Can't read file " + reportPath);
return;
}

如何使其更加紧凑?

最佳答案

您可以交换到 if-else,然后利用方法范围末尾的隐式返回。

public void doThing(Object response) {
if (!file.exists()) {
response.sendError(HttpServletResponse.SC_NOT_FOUND, "No file " + reportPath);
} else if (!file.canWrite()) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Can't write in file " + reportPath);
} else if (!file.canRead()) {
response.sendError(HttpServletResponse.SC_UNAUTHORIZED, "Can't read file " + reportPath);
} else {
doStuff();
}
// Implicit return
}

关于java - 字符串 Java 代码检查,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49333888/

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