Is it bad to import unused packages? - java

For instance when you work in a team at the same file and have only a partial understanding of the different packages imported needed for the code to work. You change some code in this file and find out some code become redundant because of that. You delete that part and now do not know if the whole code still depends on all packages or not.
[Of course bad can be objectified in many ways: speed, read-abilty etc.]

Yes. For a couple of reasons:
It can be confusing for a human looking at the code seeing imports that may or may not be used.
There may be import conflicts with several classes imported with the same name. This will require all but one of the similar class names to be referenced by their full qualified name in the code.
For these reasons, java will emit warnings if an import statement isn't needed and IDEs have ways to automatically delete unused imports.
Note, I didn't mention speed or performance changes, I think javac is smart enough to know not to use any unneeded imports so the compiled class will be just as if you didn't import it.

You should always only use as few of the imports as necessary, and don't use complete package imports like java.util.*. Today's IDE's usually support this with an "Organize Imports" operation during which unused imports are removed.
If you have bunch of unused imports and you modify the code, there is a chance you will add/change code that refers to classes which are covered by the unused imports. Then you won't notice that you accidentally utilized them even though that might not be your intent.
If you only have the minimum imports, if you add code that refers to a new class, the compiler will immediately notify you by showing errors, and giving you the possibility to choose which class you intend to use.
Also if you use imports beyond what is currently referenced in your program, you increase the chance to break your program for future releases of Java or the libraries you use.
Example: If your program only uses java.util.HashSet but you still import java.util.* and you use another 3rd party library from where you import com.mylib.*, your code might compile. If in a future release the 3rd party library adds a class named com.mylib.HashSet, you're code might not compile anymore because the compiler might not be able to tell which class you wanted to use (e.g. java.util.HashSet or com.mylib.HashSet).
Have you imported only java.util.HashSet only and e.g. com.mylib.SomeUtil in the first place, your code would still compile with the new version of the 3rd party lib.

Importing unused packages would NOT affect your speed, as explained here
However...it does make it more difficult to read your code if you have useless packages imported. If you are using NetBeans, you can always remove unused imports with Ctrl + Shift + I.

Related

Is it more efficient for Java to import java.math.* or java.math.BigInteger and java.math.BigDecimal? [duplicate]

It is much more convenient and cleaner to use a single statement like
import java.awt.*;
than to import a bunch of individual classes
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
What is wrong with using a wildcard in the import statement?
The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:
You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
When you compile your code, there is no com.mycompany.calendar.Event, but when they later add one, your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.
Here's a vote for star imports. An import statement is intended to import a package, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. java.sql.Date vs java.util.Date) are easily remedied by other means, not really addressed by specific imports and certainly do not justify insanely pedantic imports on all classes. There is nothing more disconcerting than opening a source file and having to page through 100 import statements.
Doing specific imports makes refactoring more difficult; if you remove/rename a class, you need to remove all of its specific imports. If you switch an implementation to a different class in the same package, you have to go fix the imports. While these extra steps can be automated, they are really productivity hits for no real gain.
If Eclipse didn't do specific class imports by default, everyone would still be doing star imports. I'm sorry, but there's really no rational justification for doing specific imports.
Here's how to deal with class conflicts:
import java.sql.*;
import java.util.*;
import java.sql.Date;
Please see my article Import on Demand is Evil
In short, the biggest problem is that your code can break when a class is added to a package you import. For example:
import java.awt.*;
import java.util.*;
// ...
List list;
In Java 1.1, this was fine; List was found in java.awt and there was no conflict.
Now suppose you check in your perfectly working code, and a year later someone else brings it out to edit it, and is using Java 1.2.
Java 1.2 added an interface named List to java.util. BOOM! Conflict. The perfectly working code no longer works.
This is an EVIL language feature. There is NO reason that code should stop compiling just because a type is added to a package...
In addition, it makes it difficult for a reader to determine which "Foo" you're using.
It's not bad to use a wild card with a Java import statement.
In Clean Code, Robert C. Martin actually recommends using them to avoid long import lists.
Here is the recommendation:
J1: Avoid Long Import Lists by Using
Wildcards
If you use two or more classes from a
package, then import the whole package
with
import package.*;
Long lists of imports are daunting to
the reader. We don’t want to clutter
up the tops of our modules with 80
lines of imports. Rather we want the
imports to be a concise statement
about which packages we collaborate
with.
Specific imports are hard
dependencies, whereas wildcard imports
are not. If you specifically import a
class, then that class must exist. But
if you import a package with a
wildcard, no particular classes need
to exist. The import statement simply
adds the package to the search path
when hunting for names. So no true
dependency is created by such imports,
and they therefore serve to keep our
modules less coupled.
There are times when the long list of
specific imports can be useful. For
example, if you are dealing with
legacy code and you want to find out
what classes you need to build mocks
and stubs for, you can walk down the
list of specific imports to find out
the true qualified names of all those
classes and then put the appropriate
stubs in place. However, this use for
specific imports is very rare.
Furthermore, most modern IDEs will
allow you to convert the wildcarded
imports to a list of specific imports
with a single command. So even in the
legacy case it’s better to import
wildcards.
Wildcard imports can sometimes cause
name conflicts and ambiguities. Two
classes with the same name, but in
different packages, will need to be
specifically imported, or at least
specifically qualified when used. This
can be a nuisance but is rare enough
that using wildcard imports is still
generally better than specific
imports.
Performance: No impact on performance as byte code is same.
though it will lead to some compile overheads.
Compilation: on my personal machine, Compiling a blank class without importing anything takes 100 ms but same class when import java.* takes 170 ms.
It clutters your namespace, requiring you to fully specify any classnames that are ambiguous. The most common occurence of this is with:
import java.util.*;
import java.awt.*;
...
List blah; // Ambiguous, needs to be qualified.
It also helps make your dependencies concrete, as all of your dependencies are listed at the top of the file.
It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.
It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.
It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.
The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.
Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.
I prefer specific imports, because it allows me to see all the external references used in the file without looking at the whole file. (Yes, I know it won't necessarily show fully qualified references. But I avoid them whenever possible.)
In a previous project I found that changing from *-imports to specific imports reduced compilation time by half (from about 10 minutes to about 5 minutes). The *-import makes the compiler search each of the packages listed for a class matching the one you used. While this time can be small, it adds up for large projects.
A side affect of the *-import was that developers would copy and paste common import lines rather than think about what they needed.
In DDD book
In whatever development technology the implementation will be based on, look for ways of minimizing the
work of refactoring MODULES . In Java, there is no escape from importing into individual classes, but you
can at least import entire packages at a time, reflecting the intention that packages are highly cohesive units
while simultaneously reducing the effort of changing package names.
And if it clutters local namespace its not your fault - blame the size of the package.
Here are the few things that I found regarding this topic.
During compilation, the compiler tries to find classes that are used in the code from the .* import and the corresponding byte code will be generated by selecting the used classes from .* import. So the byte code of using .* import or .class names import will be same and the runtime performance will also be the same because of the same byte code.
In each compilation, the compiler has to scan all the classes of .* package to match the classes that are actually used in the code. So, code with .* import takes more time during the compilation process as compared to using .class name imports.
Using .* import helps to make code more cleaner
Using .* import can create ambiguity when we use two classes of the same name from two different packages. Eg, Date is available in both packages.
import java.util.*;
import java.sql.*;
public class DateDemo {
private Date utilDate;
private Date sqlDate;
}
The most important one is that importing java.awt.* can make your program incompatible with a future Java version:
Suppose that you have a class named "ABC", you're using JDK 8 and you import java.util.*. Now, suppose that Java 9 comes out, and it has a new class in package java.util that by coincidence also happens to be called "ABC". Your program now will not compile on Java 9, because the compiler doesn't know if with the name "ABC" you mean your own class or the new class in java.awt.
You won't have that problem when you import only those classes explicitly from java.awt that you actually use.
Resources:
Java Imports
Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not require an IDE for reading it.
For the record:
When you add an import, you are also indicating your dependencies.
You could see quickly what are the dependencies of files (excluding classes of the same namespace).
There is no runtime impact, as compiler automatically replaces the * with concrete class names. If you decompile the .class file, you would never see import ...*.
C# always uses * (implicitly) as you can only using package name. You can never specify the class name at all. Java introduces the feature after c#. (Java is so tricky in many aspects but it's beyond this topic).
In Intellij Idea when you do "organize imports", it automatically replaces multiple imports of the same package with *. This is a mandantory feature as you can not turn it off (though you can increase the threshold).
The case listed by the accepted reply is not valid. Without * you still got the same issue. You need specify the pakcage name in your code no matter you use * or not.
Forget about cluttered namespaces... And consider the poor soul who has to read and understand your code on GitHub, in vi, Notepad++, or some other non-IDE text editor.
That person has to painstakingly look up every token that comes from one of the wildcards against all the classes and references in each wildcarded scope... just to figure out what in the heck is going on.
If you're writing code for the compiler only - and you know what you're doing - I'm sure there's no problem with wildcards.
But if other people - including future you - want to quickly make sense of a particular code file on one reading, then explicit references help a lot.
Why is using a wild card with a Java import statement bad?
If you're using an IDE (which you should be doing), and there are more code owners than just you, using wildcard imports is bad because it:
conceals information from the rest of the team
provides only false benefits (things which are better-solved using IDE functionality than with wildcard imports) to you as an individual
Most of the "use wildcards" proponents have a focus on the individual: I don't want to maintain the list, I don't want see the clutter, etc. Here are several of the common examples:
maintenance is harder – when you want to introduce a new class into your source code, you have to manually add the import statement
refactoring is more difficult – if code is moved around, then import statements have to be updated
reduce clutter, tidy up file contents – goal here is something along the lines of "removing distractions"
These arguments were more convincing before IDEs did all of that automatically. If you're using a plain text editor instead of an IDE, then these arguments have some merit. But if you're using a plain text editor, you are already subjecting yourself to a number of other much more significant inefficiencies, and managing import statements is just one among many things that you should stop doing by hand. IDEs offer automatic management of imports, powerful refactoring tools, and folding (hiding) of any parts of the code you don't want to see.
For the "avoid wildcards" proponents, there are many examples, but I'll point out only one:
clarity – specifically, when someone new enters the codebase. They will arrive with questions, and continue to discover new questions as they explore the code. For this new code contributor, wildcard import statements do not answer any questions, and at worst can produce confusion, misunderstanding, new questions. In contrast, with explicit imports (and using an IDE) the worst case is neutral: no new info provided; at best, it not only reduces ambiguity but it can also provide answers.
At the end of the day, it helps the entire team to reduce (albeit in a small way) code complexity, to reduce confusion, to add clarity.
Importing all the classes in a package is considered a blind approach. A major reason for this is that it clutters the class namespace and could lead to conflicts between classes in different packages with the same name.
Specifically populating the necessary classes avoids that problem and clearly shows which versions were wanted. This is good for code maintainability.

Java Imports, Assembly (Krakatau), and Source Code

So here's my situation:
I am running a Java Client/Server architecture that has high CPU usage and I'm trying to reduce the lag time on the main "server" thread. I have been profiling the server with YourKit to identify the CPU-hogging code.
The problem is:
I am using someone else's code, and because of the way it is written, it is impossible to decompile, then recompile without using a special obfuscator which I do not have access to (no I am not violating any copyrights or anything).
What I am currently doing:
To modify the class files without worrying about obfuscation, I have been using Storyyeller's amazing Krakatau decompiler (https://github.com/Storyyeller/Krakatau) to disassemble class files into assembly files.
I manually edit the .j assembly files while looking at a Jasmin reference page (which takes FOREVER and I often mess up), then reassemble them into class files and run them again.
What I want to do:
Instead of painstakingly editing the assembly, I was wondering, does anyone know of a way to convert .java Source Code to .j Assembly code?
Also, if I simply decompile the .class files, is it possible for me to simply recompile them even though the packages for the imports do not exist?
import com.bazinga.*;
public class MainThread{}//compile this even though package com.bazinga doesn't exist?
If anyone knows ANY WAY I could do this, I would really appreciate it!
Instead of painstakingly editing the assembly, I was wondering, does anyone know of a way to convert .java Source Code to .j Assembly code?
Yes and no. The obvious answer is that you can just compile your code and then disassemble the resulting classes. However, this is not always helpful, because compilation can be context dependent (such as inlining static final constants, or handling of nested classes). Additionally, if you plan to add your code into an existing method, you have to be careful to not use existing local variable slots or clobber the operand stack.
My best advice is to try to isolate your modifications as much as possible. For example, if you want to add code to the jar, instead of inserting it into an existing class, just write the code you want to add in Java, compile it and add the classfiles in. Then modify the target class to call into your own class.
As for imports, you can compile against stubs. Just create a dummy class with the name you want, and optionally dummy methods for anything you need to call. The implementations can just be {throw null;} or similar, since you won't actually be executing them ever, they just need to exist to satisfy the compiler during compilation.

What is the typical convention for importing Java packages?

In my programming classes in college, we would just import an entire package even if we just used one class from it. This may have been because we were supposed to use IDEs that did not offer autocompletion or anything fancy like that, so it would just make it easier to code in general.
However, now that I'm more of an experienced programmer, is it more conventional to import Java packages as a whole or just the classes from those packages that you would need?
For example, instead of:
import java.util.*;
Is it conventional to say:
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
etc.?
Does importing an entire package compared to select classes use more memory?
It's not so much a memory issue, but rather that you run the risk of inadvertently importing the wrong class if you use the * notation. Generally it's not a problem, but if the * matches a class that you meant to pull in from another package it's a hard bug to find.
I've seen IDE's use the rule that specific class imports are replaced by a single '*' import statement if you're importing three or more classes from that package. I prefer to call out each imported class by name.
This Wildcard type-import-on-demand declarations as you have given like import java.util.*; must NOT be used directly in code; use only required class name instead like import java.util.ArrayList;
The following and many other reasons are there:
The important reason is that a new unexpected class file can be added to the same package. This new class can conflict with a type you are using from another package, thereby turning a previously correct program into an incorrect one without touching the program itself.
Explicit class imports clearly convey to a reader the exact classes that are being used (and which classes are NOT being used).
Explicit class imports provide better compile performance. While type-import-on-demand declarations are convenient for the programmer and save a little bit of time initially, this time is paid for increased compile time every time the file is compiled.
For more regarding coding conventions refer: http://geosoft.no/development/javastyle.html#
Often, memory consumption will be similar, as the class you import will probably end up using other classes in the same package due to inheritance and functionality logic.
In my school (high school junior year), they currently make us import the entire package. This is mainly due to the fact that our IDE (BlueJ), offers the bare minimum of auto complete, and hence it'd be quite a pain to have to hand import every single class we use.
Personally though, I use Eclipse and IDEA for my work, and import each class manually. This prevents conflicts between same names classes in different packages, which is a great help to me since Android has equivalent classes for a lot of the Java framework, but in a different package.
From the performance point of view, there is a slight overhead when compiling, but no difference during runtime.
#Chris Gerken has a good point.
But it is not just bugs. Wild-card imports can lead to problems if you recompile against an updated library that (in the new version) adds a new class with the same name as one you are already using. So wild-card imports tend to make your code more fragile in the long term.

No java imports in smali?

I was doing some experiments today in android source.
Let me tell the complete thing,
I compiled framework.jar from android source and decompiled it and generated smali source and kept it aside. Then from CyanogenMod repo I added the commits of a feature to android source and compiled framework.jar again and again decompiled smali source to see the changes in terms of smali so that I can port them over to my ROM.
The feature I am porting requires importing of certain classes e.g import dalvik.system.VMRuntime and extra coding for utilization of those imported classes. So now my problem is, I am only able to see the extra coding i.e utilization of those classes in the smali code but not those imports. So when I port only the smali code I get java.lang.NoSuchMethodError in logcat which shows that it is unable to find that method. The reason is clear because the necessary class is not imported then how to do it in smali code? i see no way to do that in smali and due to which the newly introduced methods don't work.
Any feasible solution to this?
The only thing an import does in java is make it so that you can mention a class without having to specify the full package name. In smali, there are no imports - everything always uses the fully qualified class name that includes the package.
As such, your problem is definitely not related to imports. It sounds like you are trying to use a method that simply doesn't exist on the device.
You can disassemble the framework jars from your device and find the definition of the dalvik.system.VMRuntime and see what methods are available. Or alternately add some reflection calls and log the info to logcat.
It's worth noting that VMRuntime is not part of the public API, and it may not be present or consistent on all devices or future versions of Android.
(I don't know smali, so there may be a much better solution)
No Java program ever requires any import statement. To use e.g. ArrayList you need to either import it or refer to it in full, as java.util.ArrayList.
There is a significant difference between e.g. a C++ #include and a Java import. A C++ #include directly inserts code in your program, typically the declaration for a class you are using. The process of getting the declarations is divided into two stages in Java. First the compiler determines the fully qualified class name, then it uses its own library and the classpath to find the declaration for that name. Java import is used only in calculating the fully qualified class name, and so is not needed for any class that is only referred to by its fully qualified name.
Perhaps you could pre-process the code you are adding to replace e.g. VMRuntime with dalvik.system.VMRuntime etc. so that you can compile it with no imports.
Here is an example of a short program that uses java.util classes, in different ways, without any import:
public class Test {
public static void main(String[] args) {
java.util.List<String> list = new java.util.ArrayList<String>();
list.add("bbb");
list.add("aaa");
java.util.Collections.sort(list);
System.out.println(list);
}
}

Why is using a wild card with a Java import statement bad?

It is much more convenient and cleaner to use a single statement like
import java.awt.*;
than to import a bunch of individual classes
import java.awt.Panel;
import java.awt.Graphics;
import java.awt.Canvas;
...
What is wrong with using a wildcard in the import statement?
The only problem with it is that it clutters your local namespace. For example, let's say that you're writing a Swing app, and so need java.awt.Event, and are also interfacing with the company's calendaring system, which has com.mycompany.calendar.Event. If you import both using the wildcard method, one of these three things happens:
You have an outright naming conflict between java.awt.Event and com.mycompany.calendar.Event, and so you can't even compile.
You actually manage only to import one (only one of your two imports does .*), but it's the wrong one, and you struggle to figure out why your code is claiming the type is wrong.
When you compile your code, there is no com.mycompany.calendar.Event, but when they later add one, your previously valid code suddenly stops compiling.
The advantage of explicitly listing all imports is that I can tell at a glance which class you meant to use, which simply makes reading the code much easier. If you're just doing a quick one-off thing, there's nothing explicitly wrong, but future maintainers will thank you for your clarity otherwise.
Here's a vote for star imports. An import statement is intended to import a package, not a class. It is much cleaner to import entire packages; the issues identified here (e.g. java.sql.Date vs java.util.Date) are easily remedied by other means, not really addressed by specific imports and certainly do not justify insanely pedantic imports on all classes. There is nothing more disconcerting than opening a source file and having to page through 100 import statements.
Doing specific imports makes refactoring more difficult; if you remove/rename a class, you need to remove all of its specific imports. If you switch an implementation to a different class in the same package, you have to go fix the imports. While these extra steps can be automated, they are really productivity hits for no real gain.
If Eclipse didn't do specific class imports by default, everyone would still be doing star imports. I'm sorry, but there's really no rational justification for doing specific imports.
Here's how to deal with class conflicts:
import java.sql.*;
import java.util.*;
import java.sql.Date;
Please see my article Import on Demand is Evil
In short, the biggest problem is that your code can break when a class is added to a package you import. For example:
import java.awt.*;
import java.util.*;
// ...
List list;
In Java 1.1, this was fine; List was found in java.awt and there was no conflict.
Now suppose you check in your perfectly working code, and a year later someone else brings it out to edit it, and is using Java 1.2.
Java 1.2 added an interface named List to java.util. BOOM! Conflict. The perfectly working code no longer works.
This is an EVIL language feature. There is NO reason that code should stop compiling just because a type is added to a package...
In addition, it makes it difficult for a reader to determine which "Foo" you're using.
It's not bad to use a wild card with a Java import statement.
In Clean Code, Robert C. Martin actually recommends using them to avoid long import lists.
Here is the recommendation:
J1: Avoid Long Import Lists by Using
Wildcards
If you use two or more classes from a
package, then import the whole package
with
import package.*;
Long lists of imports are daunting to
the reader. We don’t want to clutter
up the tops of our modules with 80
lines of imports. Rather we want the
imports to be a concise statement
about which packages we collaborate
with.
Specific imports are hard
dependencies, whereas wildcard imports
are not. If you specifically import a
class, then that class must exist. But
if you import a package with a
wildcard, no particular classes need
to exist. The import statement simply
adds the package to the search path
when hunting for names. So no true
dependency is created by such imports,
and they therefore serve to keep our
modules less coupled.
There are times when the long list of
specific imports can be useful. For
example, if you are dealing with
legacy code and you want to find out
what classes you need to build mocks
and stubs for, you can walk down the
list of specific imports to find out
the true qualified names of all those
classes and then put the appropriate
stubs in place. However, this use for
specific imports is very rare.
Furthermore, most modern IDEs will
allow you to convert the wildcarded
imports to a list of specific imports
with a single command. So even in the
legacy case it’s better to import
wildcards.
Wildcard imports can sometimes cause
name conflicts and ambiguities. Two
classes with the same name, but in
different packages, will need to be
specifically imported, or at least
specifically qualified when used. This
can be a nuisance but is rare enough
that using wildcard imports is still
generally better than specific
imports.
Performance: No impact on performance as byte code is same.
though it will lead to some compile overheads.
Compilation: on my personal machine, Compiling a blank class without importing anything takes 100 ms but same class when import java.* takes 170 ms.
It clutters your namespace, requiring you to fully specify any classnames that are ambiguous. The most common occurence of this is with:
import java.util.*;
import java.awt.*;
...
List blah; // Ambiguous, needs to be qualified.
It also helps make your dependencies concrete, as all of your dependencies are listed at the top of the file.
It helps to identify classname conflicts: two classes in different packages that have the same name. This can be masked with the * import.
It makes dependencies explicit, so that anyone who has to read your code later knows what you meant to import and what you didn't mean to import.
It can make some compilation faster because the compiler doesn't have to search the whole package to identify depdencies, though this is usually not a huge deal with modern compilers.
The inconvenient aspects of explicit imports are minimized with modern IDEs. Most IDEs allow you to collapse the import section so it's not in the way, automatically populate imports when needed, and automatically identify unused imports to help clean them up.
Most places I've worked that use any significant amount of Java make explicit imports part of the coding standard. I sometimes still use * for quick prototyping and then expand the import lists (some IDEs will do this for you as well) when productizing the code.
I prefer specific imports, because it allows me to see all the external references used in the file without looking at the whole file. (Yes, I know it won't necessarily show fully qualified references. But I avoid them whenever possible.)
In a previous project I found that changing from *-imports to specific imports reduced compilation time by half (from about 10 minutes to about 5 minutes). The *-import makes the compiler search each of the packages listed for a class matching the one you used. While this time can be small, it adds up for large projects.
A side affect of the *-import was that developers would copy and paste common import lines rather than think about what they needed.
In DDD book
In whatever development technology the implementation will be based on, look for ways of minimizing the
work of refactoring MODULES . In Java, there is no escape from importing into individual classes, but you
can at least import entire packages at a time, reflecting the intention that packages are highly cohesive units
while simultaneously reducing the effort of changing package names.
And if it clutters local namespace its not your fault - blame the size of the package.
Here are the few things that I found regarding this topic.
During compilation, the compiler tries to find classes that are used in the code from the .* import and the corresponding byte code will be generated by selecting the used classes from .* import. So the byte code of using .* import or .class names import will be same and the runtime performance will also be the same because of the same byte code.
In each compilation, the compiler has to scan all the classes of .* package to match the classes that are actually used in the code. So, code with .* import takes more time during the compilation process as compared to using .class name imports.
Using .* import helps to make code more cleaner
Using .* import can create ambiguity when we use two classes of the same name from two different packages. Eg, Date is available in both packages.
import java.util.*;
import java.sql.*;
public class DateDemo {
private Date utilDate;
private Date sqlDate;
}
The most important one is that importing java.awt.* can make your program incompatible with a future Java version:
Suppose that you have a class named "ABC", you're using JDK 8 and you import java.util.*. Now, suppose that Java 9 comes out, and it has a new class in package java.util that by coincidence also happens to be called "ABC". Your program now will not compile on Java 9, because the compiler doesn't know if with the name "ABC" you mean your own class or the new class in java.awt.
You won't have that problem when you import only those classes explicitly from java.awt that you actually use.
Resources:
Java Imports
Among all the valid points made on both sides I haven't found my main reason to avoid the wildcard: I like to be able to read the code and know directly what every class is, or if it's definition isn't in the language or the file, where to find it. If more than one package is imported with * I have to go search every one of them to find a class I don't recognize. Readability is supreme, and I agree code should not require an IDE for reading it.
For the record:
When you add an import, you are also indicating your dependencies.
You could see quickly what are the dependencies of files (excluding classes of the same namespace).
There is no runtime impact, as compiler automatically replaces the * with concrete class names. If you decompile the .class file, you would never see import ...*.
C# always uses * (implicitly) as you can only using package name. You can never specify the class name at all. Java introduces the feature after c#. (Java is so tricky in many aspects but it's beyond this topic).
In Intellij Idea when you do "organize imports", it automatically replaces multiple imports of the same package with *. This is a mandantory feature as you can not turn it off (though you can increase the threshold).
The case listed by the accepted reply is not valid. Without * you still got the same issue. You need specify the pakcage name in your code no matter you use * or not.
Forget about cluttered namespaces... And consider the poor soul who has to read and understand your code on GitHub, in vi, Notepad++, or some other non-IDE text editor.
That person has to painstakingly look up every token that comes from one of the wildcards against all the classes and references in each wildcarded scope... just to figure out what in the heck is going on.
If you're writing code for the compiler only - and you know what you're doing - I'm sure there's no problem with wildcards.
But if other people - including future you - want to quickly make sense of a particular code file on one reading, then explicit references help a lot.
Why is using a wild card with a Java import statement bad?
If you're using an IDE (which you should be doing), and there are more code owners than just you, using wildcard imports is bad because it:
conceals information from the rest of the team
provides only false benefits (things which are better-solved using IDE functionality than with wildcard imports) to you as an individual
Most of the "use wildcards" proponents have a focus on the individual: I don't want to maintain the list, I don't want see the clutter, etc. Here are several of the common examples:
maintenance is harder – when you want to introduce a new class into your source code, you have to manually add the import statement
refactoring is more difficult – if code is moved around, then import statements have to be updated
reduce clutter, tidy up file contents – goal here is something along the lines of "removing distractions"
These arguments were more convincing before IDEs did all of that automatically. If you're using a plain text editor instead of an IDE, then these arguments have some merit. But if you're using a plain text editor, you are already subjecting yourself to a number of other much more significant inefficiencies, and managing import statements is just one among many things that you should stop doing by hand. IDEs offer automatic management of imports, powerful refactoring tools, and folding (hiding) of any parts of the code you don't want to see.
For the "avoid wildcards" proponents, there are many examples, but I'll point out only one:
clarity – specifically, when someone new enters the codebase. They will arrive with questions, and continue to discover new questions as they explore the code. For this new code contributor, wildcard import statements do not answer any questions, and at worst can produce confusion, misunderstanding, new questions. In contrast, with explicit imports (and using an IDE) the worst case is neutral: no new info provided; at best, it not only reduces ambiguity but it can also provide answers.
At the end of the day, it helps the entire team to reduce (albeit in a small way) code complexity, to reduce confusion, to add clarity.
Importing all the classes in a package is considered a blind approach. A major reason for this is that it clutters the class namespace and could lead to conflicts between classes in different packages with the same name.
Specifically populating the necessary classes avoids that problem and clearly shows which versions were wanted. This is good for code maintainability.

Categories

Resources