Static import Long.parseLong in Java - 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.

Related

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().

Correct use of static imports in java [duplicate]

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.

Homegrown utility methods

Static utility methods are generally frowned up by OO purists.
I was wondering however what people feel about utility methods that are used to avoid something simple like a null check throughout the application.
String.trim() throws a NPE when invoked on a null String. So I have to do:
if(str!=null)
setValue(str.trim());
else
setValue("");
What if I create a utility method that checks for the null?
setValue(myTrim(str));
public static String myTrim(String str) {
if(str==null) return ""
else return str.trim();
}
The one problem I have encountered with methods like these is that some developers on the team might not like/not know this utility and might be doing staight calls after doing a null comparison.
Is this something that you do your framework too? If yes, what are the other common utility general use methods that people have created and are using in their applications?
What do you feel are the pros and cons of either approach?
I'd be inclined to replace the homegrown uses when an existing library (like Apache Commons Blah Blah Blah) already has written it. Code you can offload to someone else lets you focus on the important parts of the software that truly differentiate your work from everyone else's. But yes, utility classes with static methods are great, if they need to be written by you at all.
FYI, take a look at StringUtils.trimToEmpty(). Good luck.
some developers on the team might not like/not know this utility
That's what communication is good for. And I don't mean e-mail.
Talks about these kind of functions, probably other team members are doing the same and by not communitating you're duplicating code and efforts.
You may find a way to use these utility methods or even some more experienced developer migth have already develop a more mature lib or used a 3rd party.
But by all means, communicate with your team
I'm not an OO purist. So i love stuff like this. Anything that makes it easier to write code that reflects my intentions without getting bogged down in irrelevant details.
Write it. Use it yourself. Don't be shy - demonstrate how much cleaner it makes your code. Worst case, at least there'll be a bit less repetition in your code...
In terms of a design principle, there are some things that are just more logically static methods. If the utility class that you're writing doesn't really have any "state", and it feels more logical to make it uninstantiable with a bunch of static methods, then do it like that. But make sure your class is genuinely uninstantiable (give it a private constructor; I've seen people declare the class as abstract, but that's no good because people can override it).
The problem that you then get into is that if your class is project-wide, you need to treat it as a library class. And writing libraries is different from writing general code:
in general code, you should profile rather than prematurely optimising; but in a library method, you can't predict how people will use your call in the future;
you need to be very careful to document or clearly name what your method does;
you need to give it generic behaviour, and not be blinded by some specific feature that you need at that moment (e.g. if you have a method to "tokenise a string", what do you do with empty tokens? if you need to ignore them, will other callers to your method?)
I have a few classes that just contain fave static methods - they do make sense to have. You can put together extensive unit tests checking any and all boundary conditions.
In the case you described though - wouldn't it be better to make the setValue method accept any string sent to it? The method could then apply a default null string, trim it or even throw an exception if the value was incorrect.
The JavaDoc on that routine can then clearly state what inputs are valid/invalid and what happens to invalid inputs.
Not saying this is right - just another viewpoint
I use a lot of utility functions. There are some things that just don't need "objects", but I don't like the particular example you have of trim().
A reference to string that is null is very different from an empty string. Unless the app is very simple, and you know you always want to read a null reference as "", I wouldn't do it. For this case, I prefer:
setValue((str != null) ? str.trim() : "")
For me, an uncaught NPE is a good indication that there's a major error going on in the application!

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