有多少逻辑是“正确的”? 放入 Callable 中?
我经常使用可调用对象,并且偶然发现了一个让我恼火的问题:
可以说,要运行函数 foo() ,需要首先进行一些检查。
你应该 1. 将检查作为 Callable 的一部分插入:
class A implements Callable<Long> {
...
public Long call() {
check1();
check2();
return (run());
}
- 或者,将所有这些逻辑插入到另一个类 (ALogic) 中,并将 Callable 用作执行器的纯粹外壳? <代码> A 类实现 Callable {
...
公共长调用(){
ALogic aLogic = new ALogic();
返回 (aLogic.run());
}
您认为优点和缺点是什么? 你通常更喜欢什么?
I'm using callables quite often , and I've stubled upon a question that irritates me:
Lets say that to run function foo() , one needs to do a couple of checks first.
Should you
1. Insert the checks as part of the Callable :
class A implements Callable<Long> {
...
public Long call() {
check1();
check2();
return (run());
}
- OR , insert all this logic into another class (ALogic) and use the Callable a mere shell for the executor?
class A implements Callable {
...
public Long call() {
ALogic aLogic = new ALogic();
return (aLogic.run());
}
What do you think are the pro's and con's? What do you usually prefer?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
在实现回调 [Java 关键字] 接口时,我的一般建议是集中精力使 [非 Java 关键字] 接口适合被调用的类型。 匿名内部类(或其他类)中通常不应该有那么多,而不仅仅是转发调用。
另外,构造一个对象然后只调用一个方法通常是不好的。 使其成为静态方法(也许可以通过私有构造函数创建一个对象并运行它)。
My general advice when implementing callback [Java keyword] interfaces is concentrate on making the [non-Java keyword] interface appropriate for the called type. There generally shouldn't be that much in the anonymous inner class (or whatever), but more than just forwarding call.
Also, it's generally not good to have an object that is constructed and then only has a single method called on it. Make it a static method (which may, perhaps, in turn create an object through a private constructor and run that).
您觉得哪个更简单或更清晰?
我建议你这样做。
Which do you feel is simpler or clearer?
I suggest you do that.
我通常更喜欢简单地将回调转发到封闭类上的私有方法。 这消除了仅指向匿名内部类的“this”引用,这是非常无用的。
I usually prefer to simply forward the callback to a private method on the enclosing class. This eliminates the "this" reference that simply points to the anonymous inner class, which is pretty useless.