What is a good use case for static import of metho

2019-01-02 22:24发布

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. So in middle of the business logic I had a da activity that apparently seemed to belong to the current class:

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.

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. But if abs and getAlpha are not ambiguous I don't see why readEmployee is. As in lot of programming choices, I think this too is a personal preference thing.

Thanks for your response guys, I am closing the question.

16条回答
Anthone
2楼-- · 2019-01-02 23:23

Static imports are the only “new” feature of Java that I have never used and don’t intend to ever use, due to the problems you just mentioned.

查看更多
smile是对你的礼貌
3楼-- · 2019-01-02 23:23

I use 'import static java.lang.Math.*' when porting math heavy code from C/C++ to java. The math methods map 1 to 1 and makes diffing the ported code easier without the class name qualification.

查看更多
该账号已被封号
4楼-- · 2019-01-02 23:23

You need to use them when:

  • you wish to use a switch statement with enum values
  • you wish to make your code difficult to understand
查看更多
萌系小妹纸
5楼-- · 2019-01-02 23:26

Talking about unit tests: most people use static imports for the various static methods that mocking frameworks provide, such as when() or verify().

import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;

And of course, when using the one and only assert you should be using `assertThat() it comes in handy to statically import the required hamcrest matchers, as in:

import static org.hamcrest.Matchers.*;
查看更多
登录 后发表回答