Java 带有try/catch的风格要点
我想知道这种方法是否正确:Java 带有try/catch的风格要点,java,coding-style,predicate,Java,Coding Style,Predicate,我想知道这种方法是否正确: public ITask getState() { statePredicate[Some predicate definition]; ITask nextRunnable = null; try { nextRunnable = Iterables.find((Iterable)queue, statePredicate); } catch (NoSuchElementException e) {} return nex
public ITask getState()
{
statePredicate[Some predicate definition];
ITask nextRunnable = null;
try {
nextRunnable = Iterables.find((Iterable)queue, statePredicate);
}
catch (NoSuchElementException e)
{}
return nextRunnable;
}
我想知道的是:
- 谓词是否应该缓存为类的成员
- 我对捕获物不做任何处理,我甚至不记录它,因为它是 我的应用程序找不到任何东西是正常的
- t返回null,因为我执行最终返回
-如果异常在您的方法中确实是常见的情况,那么您应该在捕获区域中至少添加一条注释,以便让所有阅读代码的人都清楚这是故意的,而不是错误。在我看来,返回Null是不同的,但它在某些情况下是无法避免的。1)如果谓词总是相同的,我会使它成为
静态final
类成员
2) 还有一个版本的Iterables.find
,您可以指定默认值(假设您使用的是谷歌番石榴)。然后您根本不需要处理NoTouchElementException
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);
}
}
class-MyClass{
私有静态最终谓词状态_Predicate=新谓词(){
@凌驾
公共布尔应用(ITask输入){
//…您的代码在这里
}
};
公共ITask getState(){
返回Iterables.find(队列,状态\谓词,null);
}
}
我不确定这是否是一个严肃的问题。你肯定知道接受一个例外是一个错误吗?是的,我知道:),这正是我问的原因:我不应该接受它,然而,在我的情况下,提出这个例外是很常见的。Jesper的解决方案看起来很有希望,我会看看它(因为是的,我用的是番石榴)。非常感谢你的想法。我确实删除了cast-on队列,因为它是无用的,并且将我的谓词定义为final,还使用了Guava find的重载:)