静态导入方法的好用例是什么? - What is a good use case for static import of methods?

2021/12/04 11:17
阅读数 0

问题:

Just got a review comment that my static import of the method was not a good idea.刚刚收到评论评论说我对方法的静态导入不是一个好主意。 The static import was of a method from a DA class, which has mostly static methods.静态导入是来自 DA 类的方法,该类主要包含静态方法。 So in middle of the business logic I had a da activity that apparently seemed to belong to the current class:因此,在业务逻辑中间,我有一个 da 活动,显然似乎属于当前类:

import static some.package.DA.*;
class BusinessObject {
  void someMethod() {
    ....
    save(this);
  }
} 

The reviewer was not keen that I change the code and I didn't but I do kind of agree with him.审阅者并不热衷于我更改代码,我也没有,但我确实同意他的观点。 One reason given for not static-importing was it was confusing where the method was defined, it wasn't in the current class and not in any superclass so it too some time to identify its definition (the web based review system does not have clickable links like IDE :-) I don't really think this matters, static-imports are still quite new and soon we will all get used to locating them.给出的不静态导入的一个原因是它在定义方法的地方令人困惑,它不在当前类中也不在任何超类中,因此识别其定义需要时间(基于 Web 的审查系统没有可点击的IDE 之类的链接 :-) 我真的不认为这很重要,静态导入仍然很新,很快我们都会习惯于定位它们。

But the other reason, the one I agree with, is that an unqualified method call seems to belong to current object and should not jump contexts.但我同意的另一个原因是不合格的方法调用似乎属于当前对象,不应跳转上下文。 But if it really did belong, it would make sense to extend that super class.但如果它真的属于,扩展那个超类是有意义的。

So, when does it make sense to static import methods?所以,当是有意义的静态导入的方法呢? When have you done it?你什么时候做过? Did/do you like the way the unqualified calls look?你喜欢不合格电话的样子吗?

EDIT: The popular opinion seems to be that static-import methods if nobody is going to confuse them as methods of the current class.编辑:流行的观点似乎是静态导入方法,如果没有人会将它们混淆为当前类的方法。 For example methods from java.lang.Math and java.awt.Color.例如来自 java.lang.Math 和 java.awt.Color 的方法。 But if abs and getAlpha are not ambiguous I don't see why readEmployee is.但是如果 abs 和 getAlpha 没有歧义,我不明白为什么 readEmployee 是。 As in lot of programming choices, I think this too is a personal preference thing.与许多编程选择一样,我认为这也是个人喜好。


解决方案:

参考: https://stackoom.com/en/question/1lSx
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
返回顶部
顶部