Is import static a good practice? [closed]

最后都变了- 提交于 2021-01-28 05:12:33

问题


I was asking my self while coding in Java, does the import static com.example.method is a good the to do or is it better to import the whole class.


回答1:


Depends on the context, not exist an explicit rule to use in all the cases. But the most common use is when you do a test and need to import classes like Assert.* or Mockito.*, in order to no-repeat Assertion.assertEquals a lot of times a good idea is to do something like this:

import org.junit.jupiter.api.Test;

import static org.junit.jupiter.api.Assertions.assertAll;
import static org.junit.jupiter.api.Assertions.assertEquals;

class ErrorsControllerImplTest {

    @Test
    void should_return_all_the_errors_types() {
        ErrorsController controller = new ErrorsControllerImpl();

        assertAll(
                () -> assertEquals(58, controller.getAllErrors().size()),
                () -> assertEquals("BadRequestStatus {code=4000509, message='Site must have a value'}",
                        controller.getAllErrors().get(0)));
    }
}

As another user said, the idea is that the code will be readable and remove duplicates parts.




回答2:


It's a mehh... feature, to be sincere.

import static java.util.List.*; 
import static java.lang.String.*;
import static java.lang.Math.*;
...
of(1);                        //of 1...wat
valueOf(mother);              //really..
random();                     //i'm scared
valueOf(E);

The only real useful scenario would be when you need to constantly use constants from other class. Such as in the example above, if the class was some kind of specific MathUtils class for your project that must call Math's methods in almost all of its code.

Or as in the top answer's scenario, when running test classes such as Mockito.



来源:https://stackoverflow.com/questions/65452714/is-import-static-a-good-practice

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!