Correct use of static imports in java [duplicate] - java

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
What is a good use case for static import of methods?
I rarely ever see a static import in java like this:
import static java.lang.Math.*;
Then you could access PI without having to call Math.PI.
Since you don't see this that often, does that mean it is a bad design to do this?

I prefer not to use them, simply because I want to see where each constant is defined. If your classes and your constants are named appropriately, it helps readability a lot.
Then again, if you're using a lot of constants from the same class and it's obvious where they come from, you're better off with a wildcard import.

It is not bad design, but in my opinion Math.PI is clearer for maintaneinance than just PI.

Sometimes yes. When you use a static import, the fields and methods from the class you statically imported might "look like" they come from your class.
This does impact understandability, IMHO.
That said, I use it all the time in JUnit tests!

It's not bad. It's just usually not necessary. I personally use it whenever my program uses a lot of calls to java.lang.Math.
Most people also don't know about it since it's so infrequently used. Same thing goes to other constructs like static constructors.

Math was around before import static which is why most developers would tend to use the older form.

Related

Static import Long.parseLong in Java

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?
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.

What is more efficient in importing in Java?

I am a novice high school Java programmer and I am having an internal conflict as to which of the following methods is more efficient in Java. If you are importing a single class in Java, is it more efficient to import it as per usual, e.g., import java.util.Scanner; or to use that import statement as part of the Scanner's declaration, as in java.util.Scanner scan = new java.util.Scanner(System.in);.
I know the first is more common and looks nicer, but what if you only need one scanner object? I am sorry if this question is a duplicate; I did not know how to properly word this question in my searches to see if it already existed.
import statements create a compiler-time alias to the symbol imported. That is, it's just a shortcut for typing the full name out - it has no effect on the program while it's running. The compiled code is identical in both cases.
There is no added expense to importing a class, so it makes sense to put all of your imports in the header where anyone looking at your code can easily see what classes are utilized in the program. If you decide later that you want to have more than one scanner object or more than one class from java.util you can use import java.util.* as well.
Pick the more readable of the two. There is no difference in performance, at the end of the day they both get compiled to exactly the same bytecode.
The efficiency lies in how often you might need to write out the package/class/symbol path to the type. If you are certain that you will use it only once, not using an import would work.
But, that is the only upside. There are multiple downsides to avoiding an import statement, including readability, ease of seeing which classes are used in this code file, and extra typing if adding more references becomes necessary. The compiler is completely neutral in all of it, as source either way will compile to the same JVM code.

Is using a static method cheaper than importing the whole class?

I have a small static method mymethod inside a relatively big (library) class com.package.pirulo. I can do one of two things: Either I import com.package.pirulo and then I just use pirulo.mymethod(...), or I can use direclty the method with com.package.pirulo.mymethod(...).
Which is cheaper from a resources/speed point of view? It looks like the second option is cheaper , but since mymethod can call other methods in com.package.pirulo maybe the whole library is always somehow imported anyway...
And: is the first option as expensive (same POV) as instantiating a pirulo object?
Importing makes absolutely no difference at runtime, and only a negligible (at most) difference at compile-time.
There is no difference in performance with calling a static import vs using a fully qualified name.
There is very little difference between the two different methods of importing.
There are probably very few cases were you should really worry that much about object creation.
In the extreme micromanagement perspective, it is better to not make an object, but its not noticable typically.
Import the class you need to use from the package.
The only time when you import a single method is on static imports, which no, don't save you time, and if they do, it's negligible, and you shouldn't be doing it for that reason anyway.
That said, sometimes static imports improve readability. For example, java.lang.String.format.
The import statements only make code readable and easy to be written. After code has been compiled, all the references are replaced by fully qualified name and unused imports are ignored. String s;" will become java.lang.String s; automatically so its does not matter.

what do these statements mean and is this style recommended ?

Recently i cam across a statements :
import static java.lang.System.out;
import static java.lang.System.exit;
I read these statements in some tutorial. Are these statements O.K ?
If the statements are alright what do they mean and should they be used regularly while writing code ?
They are called static imports. The effect is to allow you to use the names out and exit in your program as if they were defined in the current scope; so you can write exit(0) instead of System.exit(0).
Now, are they a good idea? Sometimes, when used sparingly, they are a good way to reduce clutter. But most of the time, they actually just make your code harder to understand. The reader will ask "Where is this out defined?" and "Where does exit() come from?" In general, you should avoid them.
But if you're writing a class that's all about processing SomeReallyLongName objects, and SomeReallyLongName defines a bunch of FINAL_CONSTANTS, importing them with static imports will save a lot of typing and a lot of clutter, and it will be pretty clear where those constants are coming from.
They are static imports. It allows you to do something like exit(0) instead of System.exit(0).
I do not recommend this for well known Java classes because it can be confusing to some. But sometimes it is useful for utility classes like Guava.
Iterables.filter(list, SomeClass.class)
is very verbose but you can make it easier to read with static imports: filter(list, SomeClass.class)
You should check with your team to see what they code guidelines are and try to be consistent.
Yes,it is perfectly alright .
This is known as static import.This allows members defined in class as static and
public to be used without specifying the class in which the field is defined.
This feature was defined in J2SE 5.0.
For example :
import static java.lang.Math.*;
import static java.lang.System.out;
// in main
out.print( max(100,200) ); // prints 200.You didn't have to use Math.max(.,.)
I think it may not be a good idea to use static imports as it'll make your code hard to read.
Yes, these statements are referred to as static imports and are perfectly valid. Take a look at the javase guide on static imports for more information.
With respect to usage, the guide states:
So when should you use static import? Very sparingly! Only use it when
you'd otherwise be tempted to declare local copies of constants, or to
abuse inheritance (the Constant Interface Antipattern). In other
words, use it when you require frequent access to static members from
one or two classes. If you overuse the static import feature, it can
make your program unreadable and unmaintainable, polluting its
namespace with all the static members you import. Readers of your code
(including you, a few months after you wrote it) will not know which
class a static member comes from. Importing all of the static members
from a class can be particularly harmful to readability; if you need
only one or two members, import them individually. Used appropriately,
static import can make your program more readable, by removing the
boilerplate of repetition of class names.
Static imports are a new feature added in Java 1.5
The static import construct allows unqualified access to static members without inheriting from the type containing the static members. Instead, the program imports the members, either individually
There is nothing wrong with your example if you want easy access to out and exit so that you can call them directly as out.println() for example. There is nothing syntactically incorrect about it nor from a style aspect though some may argue it is "confusing" and hard to figure out where out came from, but any modern IDE can help them figure that out.
These are static import concept.These are like simple imports but having different type of concept.See here you import one function exit() and one field out and both are static in their corresponding classes(in case both here Systen is their class).After this instead of writing System.out.println() you can simply write out.println().Similarly instead of System.exit(),you can write exit().

Is it wrong to have static and non-static methods in the same class?

Is it wrong to have static and non-static methods in the same class?
Not really in regular java programming.
But if you're working extensively with dependency injection you probably have few or no static methods at all. In such a context it's fairly common to have only a few utility classes with static methods, and no other static methods.
No, it's not wrong. For example, a common use is to have static factory methods in a class definition.
I think it's fine to create static utils classes, especially when you're not really sure (yet) what the design should be, because you're still learning about the problem domain.
Staticness is a "yet to designed properly" marker. Often the static solution is perfectly adequate; but sometimes, as the project progresses, you find you do have to rewrite that "whole part", but you have (at that later stage) a far more complete understanding of the problem domain, and are therefore in a position to actually design a "proper solution" to those problems.
I think us programmers hammer ourselves unfairly about "rework". You need to do the work in order to understand the work well enough to do the work properly. I see no way past this catch 22;
I can cite many examples of static from the core API. java.lang.Math, java.util.Arrays, java.util.Collections. BUT please note that these classes are "utils classes" which exist only to provide a bunch of static methods. IMHO, The presence of static methods in a "stateful object" is just begging to be refactored.
I'll betcha that todays API designers would love to be able to split-down Integer (and the other wrapper classes)... BUT they're well and truly stuck with what they've got. Which is a warning in itself... that static implies final, and there's a darn good reason that (unlike C++) java methods can be overridden by default. Static is inherently more "binding" than non-static... down the trick you CAN NOT adapt implementations to different situations, contexts, etc, etc, etc.
Cheers. Keith.
I believe its a bad idea to have static and non-static methods in the same class with the same name. This can be very confusing. I would suggest trying to make the names different in this case.
Similarly, don't make methods with the same name but different case, or methods with the same name as the class in the same class. Both are legal, and even occur in the JDK, but are confusing IHMO.
I guess not especially when dealing with singletons.

Categories

Resources