2

Today in private method I used Long.parseLong() (just once in whole class) with some String as value. At peer review colleague wrote that this method should be static import and then called without Long.. I asked why because as I know and what is in https://stackoverflow.com/a/421127/4952262 in such case we should just go with Long.parseLong() instead of trying to save 5 characters. The answer was that parseLong method is just in Java.lang.Long package and it's safe because this method was, is and will be just in this package. Is it good way? Does it really make a code more readable?

Michu93
  • 5,058
  • 7
  • 47
  • 80
  • 5
    I'm not sure there's an industry position on this issue; it's mostly a style and/or preference decision. The "correct" answer typically is this: be consistent within the codebase – Gus Oct 10 '19 at 13:04
  • 1
    There is some redundancy because parseInt, ParseLong, parseDouble reside exactly in Int, Long and Double respectively, and it could shorthen arithmethic expressions. However I have never used it, or (I admit) seen it. Whereas I have seen many static imports in unittests. – Joop Eggen Oct 10 '19 at 13:08
  • 1
    Static imports should indeed be used very sparingly, but `parseLong` is _probably_ ok unless there is any risk your company might write their own parseLong method to do something else. As an antipattern example, I've worked at a place where it was a guideline to statically import _everything_. We had code that said `of(...)` and we couldn't tell if it was Stream.of, Date.of, Instant.of, List.of, or anything. It made me puke every time I saw that. – DodgyCodeException Oct 10 '19 at 15:51

1 Answers1

1

It depends how do you infer it, I have read a lot about it that static imports increase the code readability. But let's think of a scenario where you have two classes namely Class A and B. Think that both the classes have similar static fields/method that you want to use in some third Class C.
Now how does it increase the readability of code ?

Again i am not arguing where its wrong or correct to use static imports but yes i do believe in some of the cases it sounds good to do so in other it might not.

Note : Anyways it does not make any difference when it comes to performance as much as i know.

Ashutosh
  • 917
  • 10
  • 19