如何按照Bob叔叔的规则(建议)正确使用一个尝试块,以一种方法正确地使用一种方法?
例如,我有一个方法
void process(String userId) {
if(userId == null) throw new IlligalArgumentException("User ID is required");
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
try {
DataResponse response = analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
//logic
} catch(AnalyticsAPIException e) {
//logic
}
}
illigalArgumentException
是未检查 exceptionusernotfoundexception
是 未检查的例外aNalyticsapiexception
/code>是检查例外,
我读到,从尝试结束的方法开始使用该方法是一种最佳实践,而不是在一种方法中乘以try-catch块。
更喜欢异常而不是错误代码,我们更喜欢异常而不是错误代码 因为它们更明确。在处理尝试 /捕获时,我们 不应该在函数中添加比尝试 /捕获块更多的逻辑,因此 该功能有一件事:处理错误。建议:不要使用 嵌套的尝试 /捕获。< / p>
这样的事情:
void process(String userId) {
try {
if(userId == null) throw new IlligalArgumentException("User ID is required");
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
DataResponse response = analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
// logic
} catch(AnalyticsAPIException e) {
//logic
}
}
但是看起来很奇怪。我在TryCatch块的内部抛出了一个例外,并希望它不会在捕获量中处理。我希望它将被投入到称为该方法的服务上。
我可以接下来:
public void process(String userId) {
if(userId == null) throw new IlligalArgumentException("User ID is required");
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
DataResponse response = callApi(userId, user.getDob(), user.getFirstName());
//logic
}
private DataResponse callApi(String userId, Date dob, String firstName){
try {
return analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
} catch(AnalyticsAPIException e) {
//logic
}
}
但这并不总是有效。那么,什么越好?
For example, I have a method
void process(String userId) {
if(userId == null) throw new IlligalArgumentException("User ID is required");
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
try {
DataResponse response = analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
//logic
} catch(AnalyticsAPIException e) {
//logic
}
}
IlligalArgumentException
is the unchecked exceptionUserNotFoundException
is the unchecked exceptionAnalyticsAPIException
is the checked exception
I read that it is a best practice to start the method from try and finish with a catch instead of multiplying try-catch blocks in the one method.
Prefer exceptions to error codes We prefer exceptions to error codes
because they are more explicit. When dealing with try / catch, we
should not add more logic in a function than the try / catch block, so
that function does one thing: handle errors. Recommendation: don’t use
nested try / catch.
Something like this:
void process(String userId) {
try {
if(userId == null) throw new IlligalArgumentException("User ID is required");
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
DataResponse response = analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
// logic
} catch(AnalyticsAPIException e) {
//logic
}
}
But it looks strange. I throw an exception inside of the try-catch block and hope that it won't be handled in the catch. I expect that it will be thrown upper to the service which called that method.
I can do next:
public void process(String userId) {
if(userId == null) throw new IlligalArgumentException("User ID is required");
User user = userService.findUserById(userId);
if(user == null) throw new UserNotFoundException("User with ID: "+ userId +" not found");
DataResponse response = callApi(userId, user.getDob(), user.getFirstName());
//logic
}
private DataResponse callApi(String userId, Date dob, String firstName){
try {
return analyticsAPI.loadAnalytics(userId, user.getDob(), user.getFirstName());
} catch(AnalyticsAPIException e) {
//logic
}
}
But it doesn't work always. So, what is the better?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
叔叔提出的是,您没有尝试或捕获块中的语句列表。相反,您应该将“正常”情况与异常情况分开。目标是分开不同级别的抽象。
为了避免姓名碰撞,我经常将“正常”案例与“ try”单词前缀。
我也经常以自己的方法将尝试/捕捉以保持专注。例如,
“过程”方法应集中在处理用户(用户ID)的含义上。这是一个抽象级别,如果您将其与其他方法分开,则更容易阅读和理解。
GetusById仅关注您要通过ID来获得用户时所需的逻辑。
要了解“过程”方法,不必理解
加载分析可能会导致特殊状态,甚至会导致其处理方式。
但是,当您深入研究LoadAnalytics方法时,您想知道它的工作原理。现在,您可以立即看到加载分析可能会导致异常状态。该方法专注于异常处理,因为它仅包含尝试/捕获,您还专注于可能发生的例外。
我经常使用“尝试”前缀来避免名称碰撞,并清楚地表明方法可能会失败。
与“正常”情况一样,异常处理也分开,因此您可以专注于如何处理特定异常。
What unclebob proposes is that you don't have a list of statements in the try or catch block. Instead you should separate the "normal" case from the exception case. The goal is to separate different levels of abstraction.
To avoid name collisions I often prefix the "normal" case with the "try" word.
I also often separate the try/catch in an own method to keep things focused. E.g.
The "process" method should focus on what "to process a user (userId)" means. It is one level of abstraction and if you separate it from the other methods it is easier to read and understand.
The getUserById focuses only on the logic that is required when you want to get a user by it's id.
To understand the "process" method it is not necessarry to understand
that loading analytics can cause exceptional states or even how they are handled.
But when you dive into the loadAnalytics method you want to know how it works. Now you can immediately see that loading analytics might cause exceptional states. The method is focused on the exception handling, because it only contains the try/catch and you also focus on the kind of exceptions that can occur.
I often use the "try" prefix to avoid name collisions and to make clear that a method might fail.
Like the "normal" case the exception handling is separated so that you can focus on how a specific exception is handled.