Code review: Static imports are great but underused
Published in
2 min readMay 25, 2018
Static imports must be one of the easiest way to make your code a bit more concise and readable. Still most developers don’t seem to use it almost at all. I hope to inspire some more usage of if so let’s jump right into some examples.
Assertions.assertThat (1).isEqualTo(2); // Without static importassertThat(1).isEqualTo(2); // With static import
Having the Assertions class name here doesn’t give us any information so we’re better of without it. This is one example where almost everyone agrees and uses.
List<Integer> numbers = Arrays.asList(1, 2, 3);List<Integer> numbers = asList(1, 2, 3);
Same thing here, the method name asList is enough for us to understand what happens.
LocalDate.now().with(TemporalAdjusters.next(DayOfWeek.FRIDAY));LocalDate.now().with(next(FRIDAY)); // Much more readable!
Java time package has a few use cases where static import should be used. Enums can generally be statically imported as well.
integers.stream()
.filter(i -> i < 2)
.collect(Collectors.toList());integers.stream()
.filter(i -> i < 2)
.collect(toList());