nus-cs2103-AY2223S2 / forum

12 stars 0 forks source link

Import vs Import Static #272

Closed lhy-hoyin closed 12 months ago

lhy-hoyin commented 1 year ago

Is there a preference/rule/standard on when to use import xxx vs when to use import static xxx.yyy?

For example, in AddCommandTest

import static java.util.Objects.requireNonNull;
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertFalse;
import static org.junit.jupiter.api.Assertions.assertTrue;
import static seedu.address.testutil.Assert.assertThrows;

import java.nio.file.Path;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.function.Predicate;

// more imports below

public class AddCommandTest {

    @Test
    public void constructor_nullPerson_throwsNullPointerException() {
        assertThrows(NullPointerException.class, () -> new AddCommand(null));
    }

    // more tests

}

I believe that if import seedu.address.testutil.Assert is used instead, then the test would look like this

@Test
    public void constructor_nullPerson_throwsNullPointerException() {
        Assert.assertThrows(NullPointerException.class, () -> new AddCommand(null));
    }
jiasheng59 commented 1 year ago

I think as long as the imported method name doesn't conflict with any method name within the class, it's fine to use import static... I also wonder when will one choose one over another 🤔

jiasheng59 commented 1 year ago

The reason I can think of is that import static could be used as a shorthand for constants and methods that are used many times within the class you are working with.

dohaduong commented 1 year ago

agree, i think import static is mostly used to access static members (constants, etc) of other classes/interfaces, so it's up to you which one you prefer