【发布时间】:2022-11-25 04:31:03
【问题描述】:
所以我遇到了一个问题,我必须在一个函数中抛出很多异常,它占据了 90% 的代码,这使得它不干净并且通常难以阅读。 有什么方法可以让它看起来/功能更好?
语境: 在我的案例中,使用其他函数来检查这些案例是不可行的,因为它通常非常具体,并且会占用 70% 的服务。
例子:
public void problematicFunction(String string1, String string2, String string3, String string4) throws GenericException {
if(String1.someLogicHere) {
throw new GenericException("error_code", "something is wrong with" + string1)
}
if(String2.someLogicHere) {
throw new GenericException("error_code", "something is wrong with" + string2)
}
if(String2.someOtherLogicHere) {
throw new GenericException("error_code", "something else is wrong with" + string2)
}
if(String3.someLogicHere) {
throw new GenericException("error_code", "something is wrong with" + string3)
}
if(String4.someLogicHere) {
throw new GenericException("error_code", "something is wrong with" + string4)
}
mainlogic(string1,string2,string3,string4)
}
【问题讨论】:
-
有关上下文和细节(包括真实代码)的更多信息可能会有所帮助
-
这些检查没有任何共同点,因此很难对其进行重构。您可以将条件压缩到 Function/Supplier<Boolean> 中,然后创建一个方法来执行检查和抛出。但是您仍然必须多次调用该方法。