java - 让代码尝试不同的事情直到成功

标签 java heuristics

这是我第二次发现自己编写这种代码,并决定必须有一种更具可读性的方法来完成此任务:

我的代码试图找出一些东西,但定义不明确,或者有很多方法可以实现它。我希望我的代码尝试几种方法来解决问题,直到成功或用完所有策略。但我还没有找到一种方法来使它变得整洁和可读。

我的特殊情况:我需要从接口(interface)中找到特定类型的方法。可以对其进行显式注释,但它也可以是唯一合适的方法(根据其参数)。

所以,我的代码目前是这样的:

Method candidateMethod = getMethodByAnnotation(clazz);
if (candidateMethod == null) {
  candidateMethod = getMethodByBeingOnlyMethod(clazz);
}
if (candidateMethod == null) {
  candidateMethod = getMethodByBeingOnlySuitableMethod(clazz);
}
if (candidateMethod == null) {
  throw new NoSuitableMethodFoundException(clazz);
}

一定有更好的方法……

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

Edit2: 不幸的是,我只能接受一个答案 :(

最佳答案

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

//...
try {
   Method method = MethodFinder.findMethodIn(clazz);
catch (NoSuitableMethodException oops) {
   // handle exception
}

稍后在 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.
}

关于java - 让代码尝试不同的事情直到成功,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4075740/

相关文章:

java - 无法构建 NetBeans/Ant 项目

Java 8 + 安卓?这可能吗?

algorithm - 比 A* 更好的启发式

java - Iterative Deepening A Star (IDA*) 解决 Java 中的 n-puzzle(滑动拼图)

algorithm - 如果我使用 4xManhattan 距离作为 15-Puzzle 的启发式算法,为什么 A* 更快

java - Spring boot JPA不使用findById返回现有结果

java - 我如何将我的数据库连接到我的 Android 应用程序

java - 将对应的值按降序排列

c# - .Net 中的遗传算法 - 可变染色体 - 外星飞船场景

python - 传送旅行者,随着时间的推移优化利润问题