让代码尝试不同的东西,直到它成功,整洁

Hen*_*aul 6 java heuristics

这是我第二次发现自己编写这种代码,并决定必须有一种更易读的方法来实现这一点:

我的代码试图找出一些东西,它没有很好地定义,或者有很多方法可以实现它.我希望我的代码尝试几种方法来解决它,直到它成功,或者它用完了策略.但我还没有找到一种方法来使这个整洁和可读.

我的具体情况:我需要从界面中找到特定类型的方法.它可以注释为显式,但它也可以是唯一合适的方法(根据其参数).

所以,我的代码目前如下所示:

Method candidateMethod = getMethodByAnnotation(clazz);
if (candidateMethod == null) {
  candidateMethod = getMethodByBeingOnlyMethod(clazz);
}
if (candidateMethod == null) {
  candidateMethod = getMethodByBeingOnlySuitableMethod(clazz);
}
if (candidateMethod == null) {
  throw new NoSuitableMethodFoundException(clazz);
}
Run Code Online (Sandbox Code Playgroud)

必须是一个更好的办法?

编辑:如果找到,方法返回一个方法,null否则.我可以将其切换为try/catch逻辑,但这几乎不会使它更具可读性.

编辑2:不幸的是,我只接受一个答案:(

And*_*s_D 6

对我来说,这是可读和可理解的.我只是简单地将代码的丑陋部分提取到一个单独的方法(遵循"Robert C.Martin:Clean Code"中的一些基本原则)并添加一些javadoc(并在必要时道歉,如下):

//...
try {
   Method method = MethodFinder.findMethodIn(clazz);
catch (NoSuitableMethodException oops) {
   // handle exception
}
Run Code Online (Sandbox Code Playgroud)

后来在 MethodFinder.java

/**
 * Will find the most suitable method in the given class or throw an exception if 
 * no such method exists (...)
 */
public static Method findMethodIn(Class<?> clazz) throws NoSuitableMethodException {
  // all your effort to get a method is hidden here,
  // protected with unit tests and no need for anyone to read it 
  // in order to understand the 'main' part of the algorithm.
}
Run Code Online (Sandbox Code Playgroud)