GCX-HCI/grandcentrix-AndroidCodeStyle

No star (*) imports

passsy opened this issue · 1 comments

No star imports in production code

Java has two different ways to import classes. Explicit or with a wildcard.

// class import
import android.app.Activity;
// import using wildcard
import android.app.*;

Actually there is not a big difference. Imports are handled by the IDE and collapsed by IntelliJ. Autocompletion doesn't benefit from wildcard imports.
The main reason why we don't use wildcard imports is that they hide which explicit class or static method is used in code reviews. This problem gets bigger with Kotlins extensions functions which also have to be imported.

Without an IDE it's impossible to know where a extension method is defined.

// Guess the class where this method is defined

fun String.isValidUsername() {
    // ...
}
import net.grandcentrix.*
import net.grandcentrix.utils.*
import com.github.kotlinutils.auth.*

// ...

fun login(username: String, password: String) {
    if (username.isValidUsername() && password.isValidPassword()) {
        userManager.login(username, password)
    }
}

This makes code reviews harder because you really want to know if the method is defined in a third party library or is part of the project.

Therefore we don't use star imports
...except for test.

Star imports in tests

Testing libraries such as Mockito or AssertJ have tons of static helper methods. If you use one of them it's very likely you want to use all of them without explicitly importing the function. Without star imports you have to write Mockito.<method> for every new method and then import the static method manually. For a simple test this is a lot of typing.

// no star imports
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.never;
import static org.mockito.Mockito.verify;
import static org.mockito.Matchers.anyInt;
import static org.mockito.Matchers.anyString;

@Test
public void checkLoggerDoesntLog() throws Exception {
    // ...
    // this line requires 4 manual static imports
    verify(logger, never()).log(anyInt(), anyString(), anyString());
}

With star imports you have to import org.mockito.Mockito.* once and then all other methods are available via autocompletion.

// star imports in tests
import static org.mockito.Mockito.*;

@Test
public void checkLoggerDoesntLog() throws Exception {
    // ...
    // once verify was imported all other methods are available, too
    verify(logger, never()).log(anyInt(), anyString(), anyString());
}

Libraries with star imports

Java

Kotlin

Implemented

  <option name="CLASS_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />
  <option name="NAMES_COUNT_TO_USE_IMPORT_ON_DEMAND" value="999" />