Skip to main content
Source Link
200_success
  • 144.2k
  • 22
  • 188
  • 473

First, let's acknowledge that this is a subjective question. However, in my opinion, it is constructive enough to be on topic for this site.

I would treat the standard Java library differently than your own packages or third-party packages. Everyone recognizes classes from the standard Java library, such as BufferedReader, PrintWriter, and IOException. There is therefore no value in importing those individually; it just clutters the code. Everyone who has worked with Java will know that those classes belong to the java.io package, unambiguously. Anyone who writes classes whose names conflict with those well known classes will be soundly beaten up, so name conflicts with java. classes just don't happen in practice.

With third-party libraries, it makes sense to import more specifically. Programmers encountering those classes could use some help to figure out which packages they belong to. Name clashes could happen. That said, star imports for third-party libraries would be a judgement call. I would suggest importing individual classes up to some number of classes (around 4) per package; beyond that, a star import might be sensible. I would try to avoid star-importing more than one such package, though, to mitigate against the documentation-searching and name clash concerns. (If you feel the urge to star-import multiple packages, your class is probably doing too much anyway and should be split up.)

With code that you have written yourself for the same or a closely related project, go ahead and star-import related packages, judiciously. If you're working with the source code, you'll be familiar with the related code in neighbouring packages anyway. If it fails to compile because of a name clash, you can fix it yourself.

Post Made Community Wiki by 200_success