我想知道这种方法是否正确:
public ITask getState()
{
statePredicate[Some predicate definition];
ITask nextRunnable = null;
try {
nextRunnable = Iterables.find((Iterable)queue, statePredicate);
}
catch (NoSuchElementException e)
{}
return nextRunnable;
}
我想知道的是:
感谢您的投入! -
答案 0 :(得分:1)
1)如果谓词总是相同的话,我会把它变成static final
类成员。
2)还有Iterables.find
的版本可以指定默认值(假设您使用的是Google Guava)。那么你根本不需要处理NoSuchElementException
。
3)有理由将queue
投射到Iterable
吗?如果没有必要,那就不要施放。
class MyClass {
private static final Predicate STATE_PREDICATE = new Predicate<ITask>() {
@Override
public boolean apply(ITask input) {
// ... your code here
}
};
public ITask getState() {
return Iterables.find(queue, STATE_PREDICATE, null);
}
}
答案 1 :(得分:0)
如果异常真的是你的方法中的常见情况,那么你应该至少对catch区域发表评论,以便为每个阅读代码的人明确说明它是故意的而不是错误的。在我看来,返回Null是不同的,但有些情况是不可避免的。