I am creating an application in Java which performs data movement task (like copy, move, etc.)
At the higher level, I can provide these operations on object level.
Sample code:
public class DataSource {
public boolean copy(DataSource dsDestination);
public boolean copy(DataSource dsDestination, Filter filter);
public boolean move(DataSource dsDestination);
public boolean exists();
// some other 10-15 methods
}
Or I can provide a utility with static methods:
public class DataSourceUtil {
public static boolean copy(DataSource dsSource, DataSource dsDestination);
public static boolean copy(DataSource dsSource, DataSource dsDestination, Filter filter);
public static boolean move(DataSource dsSource, DataSource dsDestination);
public static boolean exists(DataSource dsSource);
// some other 10-15 methods
}
Which one is better approach in terms of memory management?
The golden rule is: static is an abnormality within good OO design. You only use it if there are good reasons to do so.
You see, static leads to direct coupling between your classes. And it makes testing harder. Of course, the static methods themselves can be easily tested, but what would happen if you want to test a method that calls those static methods (and you have the need to influence what the static method is doing)? Then you might be tempted to turn to Powermock in order to mock those static calls. Which is not really a great idea.
If you insist on separating functionality, you better use interfaces, like:
public class DataSource {
... ctor, equals, ... methods
}
public interface DataSourceCopyAbility {
public void copy(DataSource source, DataSource destintion);
plus corresponding impl class.
EDIT: of course, convenience can be a valid reason to use static methods; for example I am using Objects.requireNonNull() all the time in code. But: those are standard API calls. When I am using them in my code, I really dont mind them to be running. I know that will never ever want to "mock" around such kind of static method invocations!
Finally: I assume you want to return true when your operations passed. Bad idea: booleans should only be used to distinguish between true and false. They are not return codes!
If such a complex operation as copying a DataSource fails - then throw an exception! Or if you really want to go without exceptions, define your own specific ReturnCode class that gives you insight into failing operations!
Forget about memory management.
No matter which method you use, you are still going to create two DataSource objects to call copy or move. There is little difference in memory usage.
What you should focus on instead, is readability and aesthetics :).
Compare these two:
someData.copy(otherData);
DataSourceUtils.copy(someData, otherData);
The second one is more verbose. Also, it seems that we need some other stuff (DataSourceUtils) to help with copying data. It would be less code to write and make more sense if we let the data copy itself (first one).
Another point that I want to point out is that you can add a To in the first one to make it a lot more readable:
someData.copyTo(otherData);
You can't do this with the second method.
I agree with #Jon Skeet , as all the operations need source object which is Datasource itself, then they should be instance methods. They are similar to equals in Object class.
From testable point-of-view instance methods are easy to test.
It depends on the functionality that you are writing in these methods..If the functionality is not using any object specific field values then using static methods would be the correct option.
i.e. make sure the variable information that you are using is not specific to object and data is common to class level
Memory management point of view, by the way, they are equivalent. The functions are share their compiled codes which is stored into the read only memory area. Only the difference between those two are the this pointer context. So it should not occupy any more space if you choose static or non static. Most of the compiled languages are following same manner.
the difference:
dataSource.copy();
copy is not my responsibility and it is a responsibility of DataSource.
DataSourceUtil.copy();
copy is my responsibility,but source code has been written in a utility class to avoid duplication.
Drawing from the experience of Apache Commons Lang library and java.lang.Objects, the advantage of static methods is that they can provide protection from NullPointerException
It is quite common to see something like this in Java code:
if (x != null && a.equals(otherX)) ...
or the practice of putting the literal on the left side:
if ("literal".equals(str)) ...
These are all NPE-protection ways. This is one of the reasons for the abovementioned liberary, and the case for static methods:
if (ds.copy(dest) == true) ... // may throw NPE
if (DataSourceUtil.copy(ds, dest) == true) ... // NPE protection
Related
I have more than 20 commonly used methods in my application. I would like to move that 20 methods into a common class.
Here my doubt is, define all the methods are static or normal method and create a global object to access that normal methods.
class Common {
public String method1() {........}
public String method2() {........}
public String method3() {........}
public String method4() {........}
public String method5() {........}
...
}
Creating object.
class CommonService {
private static Common common;
public static Common getCommon() {
if(null == common) {
common = new common();
}
return common;
}
}
If we create all the methods using static means, all 20 methods are stored in PermGen section of the heap.
But if we follow above method means, only one object can be created and stored in java heap.
Please clarify which one is the best way.
If we create all the methods using static means, all 20 methods are stored in PermGen section of the heap.
Methods are not data, but code. Where code is stored does not depend on whether a method accepts an implicit this parameter or not. If you use the singleton approach, method code will still occupy storage and additionally there will be an instance on the heap.
However, all of the above is irrelevant and you are focusing on a completely wrong aspect of your design. What matters is how the decision will affect the code which uses these methods:
static methods are simple and a great choice for pure functions (which don't depend on any external state);
singletons allow polymorphism, therefore make the methods easier to mock for testing.
You should think about the "best" way in terms of design.
If the methods are used for general purposes, making them static is preferable, as you won't have any state to store and you'll save memory this way.
You should consider other things before deciding if you want to use static methods in your utility class or not. On one hand the utility class will be very easy to test, and it's highly accessible. On the other hand, it's very hard to mock static methods in your test.
If I have a utility class, I would write it as follows:
public final class Common {
private Common() { }
public static int method1() { }
public static int method2() { }
// ...
}
"Common functions" is not quite accurate. It really depends on what you want to do, for example when I make some string utils I make StringUtils class and it has what I need. Whether to make it static or not depends on data to be processed, if one information might be used more than once for a call then answer is simple - use instances.
That depends on what the methods do.
If those methods are just helper methods, that do not alter state then static is probably better because that way you do not have to create an object every time you want to use one of the methods. You can just call Common.method()
However, if the object has state then you should rater use object methods and create a new object when you want to use the methods.
Hope this helps.
If sense of this method is "execute pure function" like mathematical sin(x), cos(x) etc static method is the best.
They belongs to one domain? (range of themats) or to different? (then create more "utility classes" with correct name)
If have state (like many people say) maybe better is singleton.
Shape of the question "i have 20 method in application" and name Common suggest previous (older) design problem, I say "procedural thinking", poor vision of OOP.
Hard to say without code.
I was prefer using static methods in my java code, since I think they are "functional""stateless" and has less side-effect. So there may be some helper classes and methods like this:
public class MyHelper {
public static Set<String> array2set(String[] items) { ... }
public static List<String> array2list(String[] items) { ...}
public static String getContentOfUrl(String url) {
// visit the url, and return the content of response
}
}
public class MyApp {
public void doSomething() {
String[] myarray = new String[]{ "aa","bb"};
Set<String> set = MyHelper.array2set(myarray);
String content = MyHelper.getContentOfUrl("http://google.com");
}
}
But my friend says we should avoid defining such static utility methods, since we call them directly in our code, it will be hard to mock them or test them if they have external dependencies. He thinks the code should be:
public class ArrayHelper {
public Set<String> array2set(String[] items) { ... }
public List<String> array2list(String[] items) { ...}
}
public class UrlHelper {
public String getContentOfUrl(String url) {
// visit the url, and return the content of response
}
}
public class MyApp {
private final ArrayHelper arrayHelper;
private final UrlHelper urlHelper;
public MyApp(ArrayHelper arrayHelper, UrlHelper urlHelper) {
this.arrayHelper = arrayHelper;
this.urlHelper = urlHelper;
}
public void doSomething() {
String[] myarray = new String[]{ "aa","bb"};
Set<String> set = arrayHelper.array2set(myarray);
String content = urlHelper.getContentOfUrl("http://google.com");
}
}
In this way, if we want to write unit tests for MyApp, we can just mock the ArrayHelper and UrlHelper and pass them to the constructor of MyApp.
I agree totally about the UrlHelper part of his opinion, since the origin static code make MyApp untestable.
But I have a little confused about the ArrayHelper part, since it doesn't depend on any external resources and the logic will be very simple. Shall we avoid using static methods at this case too?
And when to use static methods? Or just avoid using it as much as possible?
update:
We are using "TDD" in our development, so the testability of a class often is the most important concern for us.
And I just replace the word "functional" with "stateless" in the first sentence since the that's real what I meant.
You'll probably never want to mock a method that converts an array to a list (or set), and this method doesn't need any state and doesn't depend on any environment, so a static method looks fine to me.
Just like the standard Arrays.asList() (which you should probably use).
On the other hand, accessing an external URL is typically the sort of thing that you want to be able to mock easily, because not mocking it would
make the test an integration test
require to have this external URL up every time you run your tests, which you probably can't guarantee
require to have this external URL return exactly what you want it to return in your test (including errors if you want to test the event of an error).
Just beware of one disease very common amongst Java "experts": overengineering.
In your specific example, you either do or don't have a mockability issue. If you had an issue, you wouldn't be asking general questions, therefore I conclude you don't have an issue at the moment.
The general argument is that static methods are simpler and therefore the preferred choice, whenever there is a choice. A would-be instance method must first prove itself of needing to be an instance method.
If this was my project, I would defer any makeovers into instance methods until such a moment where the need for that became clear and present.
Static means you can call the method without instantiating the class. Its good if you want to package your code into a class and you have a function that just does some logic or something basic.
Just don't use a static function to try and edit member variables in the class (obviously).
Personally I think its fine to use the static function, since it is stateless.
Static methods should be used by answering the question "is this method a functionality of a specific instance?".
You shouldn't decide about a static method according to tests, you should do it according to design. Your examples doesn't need an instance because it makes no sense. So static is the better choice. You can always wrap these methods inside specific tester classes to do your tests.
The only situation in which a self-contained functionality is not static is just when you want to provide multiple implementation, so that you are forced to avoid static because you need inheritance.
I often use static methods:
for factory methods (explicitly named constructors)
to provide a functional layer above an object-oriented layer, to compose the objects
and sometimes for general-purpose functions (Apache Commons has many good examples of this)
I never use "singletons" (static objects) and methods that refer to static objects because they are a complete headache to test and reuse. I also avoid hardcoding anything into a static method that could feasibly need to be changed. Sometimes I will provide multiple methods - one with all the dependencies as parameters and others, with fewer parameters, that call the more flexible method with some default (hardcoded) values.
java.lang.Math is static which is a good example. I thought statics are not beeing garbage collected and should be avoided if possible.
No.
As mentioned by Peter Lawrey in the comment for the question, Java is all about object oriented programming. While certain functional aspects are doable and being put into eg. Java 8, at its core Java is not functional. static breaks so much of the benefits of learning how to do modern Java - not to mention all kinds of not-fun-at-all scoping problems - that there's no purpose to use them unless you're some kind of a Java wizard who really knows what happens when you use that magical keyword.
You are not a wizard. Java is not functional. If you want to be a wizard, you can learn. If you want to program in functional fashion, look into hybrid languages such as Scala or Groovy or alternatively explore the fully functional world, eg. Clojure.
I was examining the StringTokenizer.java class and there were a few questions that came to mind.
I noticed that the public methods which are to be used by other classes invoked some private method which did all of the work. Now, I know that one of the principles of OOD is to make as much as you can private and hide all of the implementation details. I'm not sure I completely understand the logic behind this though.
I understand that it's important to make fields private to prevent invalid values being stored in them (just one of many reasons). However, when it comes to private methods, I'm not sure why they're as important.
For example, in the case of the StringTokenizer class, couldn't we just have put all of the implementation code inside the public methods? How would it have made a difference to the classes which use these methods since the API for these methods (i.e. the rules to call these public methods) would remain the same? The only reason I could think of why private methods are useful is because it helps you from writing duplicate code. For example, if all of the public methods did the same thing, then you can declare a private method which does this task and which can be used by the public methods.
Other question, what is the benefit of writing the implementation in a private method as opposed to a public method?
Here is a small example:
public class Sum{
private int sum(int a, int b){
return a+b;
}
public int getSum(int a, int b){
return sum(a,b);
}
}
Vs...
public class Sum{
public int getSum(int a, int b){
return a+b;
}
}
How is the first sample more beneficial?
In order to add something, a private method can ALWAYS be changed safely, because you know for sure that is called only from the own class, no external classes are able to call a private method (they can't even see it).
So having a private method is always good as you know there is no problem about changing it, even you can safely add more parameters to the method.
Now think of a public method, anyone could call that method, so if you add/remove a parameter, you will need to change also ALL the calls to that method.
The only reason I could think of why private methods are useful is because it helps you from writing duplicate code.
In addition to consolidating duplicate code (often expressed as "Don't Repeat Yourself" or "DRY"), use of private methods can also help you to structure and document your code. If you find yourself writing method which does several things, you may wish to consider splitting it into several private methods. Doing so may make it clearer what the inputs and outputs for each piece of logic are (at a finer granularity). Additionally, descriptive method names can help supplement code documentation.
When writing clean code in Java or any other object-oriented language, in general the cleanest most readable code consists of short concise methods. It often comes up that the logic within a method could be better expressed in separate method calls to make the code cleaner and more maintainable.
With this in mind, we can envision situations where you have many methods performing tasks towards a single goal. Think of a class which has only one single complex purpose. The entry point for that single goal may only require one starting point (one public method) but many other methods which are part of the complex operation (many private helping methods).
With private methods we are able to hide the logic which is not and should not be accessible from anywhere outside of the class itself.
Public methods are generally code that other classes which implement that class will want to use. Private methods are generally not as useful outside the class, or don't(alone) serve the purpose of what the class is meant to accomplish.
Say you're in your IDE of choice, and you implement a some class A. Class A is only designed to do one thing, say document generation. Naturally you will have some mathematical and byte operation methods in Class A that are required to do document generation, but people trying to use Class A are not going to need these other methods, because they just want a document. So we make these methods private to keep things simple for any future users of our class.
The purpose of declaring a method private is to
hide implementation details
exclude the method from being listed as public API
make sure the logic behind the code is not used/misused externally
most of the time your method's execution depends on other methods being run before it; then you can also be sure that you control the correct sequence of using your method
Use private for your methods unless you intend for your method to be safely used outside of the context of your class.
Making functions private gives you advantage in following cases :
Making function private gives JVM compiler the option of inlining the function and hence boosting up the application performance
If the class is inheritable and you extend it from a child class, then in case if you want to hide the functions from child class then you can do this (you can extend StringTokenizer).
If a piece of code has to be used in multiple functions the you move that code in private utility method
An advantage and also a good reason to use private methods inside public classes is for security and bug prevention. Methods that are declared as private are only accessible by the class they are part of. This means that your private method can't be accidentally called from else where within the program reducing bugs and other complications. If you declare your method as public it can be accessed by the whole problem and can cause complications.
You may have a number of methods that work on a certain piece of data that you don't want any other part of the program to be able to interfere with. Using data encapsulation via private methods and/or variables helps to prevent this and also makes your code easier to follow and document.
I am a little confused here with this findbugs warning in eclipse.
public class MyClass {
public static String myString;
}
public class AnotherClass {
public void doSomething() {
MyClass.myString = "something";
}
}
This gives me a findbugs warning "write to static field from instance method", however this does not give me a warning:
public class MyClass {
public static String myString;
}
public class AnotherClass {
public void doSomething() {
doAnotherThing();
}
public static doAnotherThing() {
MyClass.myString = "something";
}
}
How is this any different?, and why is writing to a static variable from an instance method a bad practice?, I assume it has to do with synchronization, but it is still not clear to me.
I know this looks like the variable should be final, but I am loading the value from a properties file.
Its a form of aliasing, which may be counter-intuitive. Counter-intuitive code hampers ease of maintenance.
Logically, we expect instance methods to affect that instance's data. We expect static methods to affect static data.
Let's rename doSomething to initialize:
...
a.initialize();
...
b.initialize();
...
The reader of this code may not immediately realize that the instances of a and b are actually affecting the same data. This may be a bug since we're initializing the same memory twice, but its non-obvious since it seems reasonable that we may need to call initialize on each instance.
However, the the code were:
...
MyClass.initialize();
...
MyClass.initialize();
...
In this case, its more intuitive that we're likely affecting the same static data and this is likely a bug.
This is similar to the common version of aliasing where two variables in the same scope point to the same instance.
For your last example,
an instance calls a static method
The fact that an instance method is calling a static method isn't expected to raise flags. The examples were this is useful far outweigh where its likely a problem.
a static method of one class affects another class' static data
In one sense, it should generate a different, but similar warning: that one class is messing with the data of another class. However, by making the static variable public is a way of tacitly approving of this, so such a warning isn't necessary.
Keep in mind that FindBugs is simply trying to flag potential likely problems, not every possible problem, in your code. Your first example is likely a potential maintenance issue that you need to examine whether its a real problem. Your second example is likely not a problem or it is a real problem that is too similar to use cases where it is not a problem.
There aren't many use cases for why you would want to change a static field.
Remember that if you set this field to a new value that this value has changed for all instances of this class.
This might get you into trouble in a multi-threaded environment, where more than one thread is calling doSomething(). Proper synchronisation is required.
In 99% of all cases, you want your instance methods to change the non-static fields only, which is why findbugs warns you.
And findbugs isn't clever enough to find out about your instance method indirectly changing the field in your second example :)
This is what FindBugs has to say about this: http://findbugs.sourceforge.net/bugDescriptions.html#ST_WRITE_TO_STATIC_FROM_INSTANCE_METHOD
This is my take, so take it with a grain of salt. You mentioned synchronization issues, which are a major reason for this warning, but more importantly, the two cases are fundamentally operating on different conceptual "levels" of data. Instance methods are "owned" by objects and modify data that describes individual instances. Class methods are generic operations and state that, while related to the class, are not related to individual objects. Thus, modifying that state from within each instance would probably (but not necessarily) be a poor design decision.
Because changing a static field changes it for all instances, causing untold problems if not properly synchronised.
If you're reading in a properties file to set shared fields, then do it in a static method. Alternatively, refactor the fields into a separate singleton instance that the other class can only read from. If you're only going to have one instance, then use a singleton pattern and make the fields non-static.
Static methods should only affect static data, and instance methods should only affect instance data.
I don't think synchronization (mentioned in several answers) has any bearing on this. After all, static methods can be called from multiple threads just as easily as can instance methods.
The reason for the warning (not very well explained by the FindBugs documentation) is, I think, hinted at by a couple of answers: it's suspicious and possibly a mistake. Like Jochen Bedersdorfer said, there aren't all that many use cases where you want to assign to a static variable in one class from an instance method in another. Just like
while (x = y) {
// ...
}
isn't technically an error (and actually legal Java if x and y are boolean), it's almost always a mistake. Similarly, the authors of FindBug felt the same about the subject case.
Lets assume that a rule (or rule of thumb, anyway), has been imposed in my coding environment that any method on a class that doesn't use, modify, or otherwise need any instance variables to do its work, be made static. Is there any inherent compile time, runtime, or any other disadvantage to doing this?
(edited for further clarifications)
I know the question was somewhat open ended and vague so I apologize for that. My intent in asking was in the context of mostly "helper" methods. Utility classes (with private CTORs so they can't be instantiated) as holders for static methods we already do. My question here was more in line of these little methods that HELP OUT the main class API.
I might have 4 or 5 main API/instance methods on a class that do the real work, but in the course of doing so they share some common functionality that might only be working on the input parameters to the API method, and not internal state. THESE are the code sections I typically pull out into their own helper methods, and if they don't need to access the class' state, make them static.
My question was thus, is this inherently a bad idea, and if so, why? (Or why not?)
In my opinion, there are four reasons to avoid static methods in Java. This is not to say that static methods are never applicable, only to say that they should generally be avoided.
As others have pointed out, static methods cannot be mocked out in a unit test. If a class is depending on, say, DatabaseUtils.createConnection(), then that dependent class, and any classes that depend on it, will be almost impossible to test without actually having a database or some sort of "testing" flag in DatabaseUtils. In the latter case, it sounds like you actually have two implementations of a DatabaseConnectionProvider interface -- see the next point.
If you have a static method, its behavior applies to all classes, everywhere. The only way to alter its behavior conditionally is to pass in a flag as a parameter to the method or set a static flag somewhere. The problem with the first approach is that it changes the signature for every caller, and quickly becomes cumbersome as more and more flags are added. The problem with the second approach is that you end up with code like this all over the place:
boolean oldFlag = MyUtils.getFlag();
MyUtils.someMethod();
MyUtils.setFlag( oldFlag );
One example of a common library that has run into this problem is Apache Commons Lang: see StringUtilsBean and so forth.
Objects are loaded once per ClassLoader, which means that you could actually have multiple copies of your static methods and static variables around unwittingly, which can cause problems. This usually doesn't matter as much with instance methods, because the objects are ephemeral.
If you have static methods that reference static variables, those stay around for the life of the classloader and never get garbage collected. If these accumulate information (e.g. caches) and you are not careful, you can run into "memory leaks" in your application. If you use instance methods instead, the objects tend to be shorter-lived and so are garbage-collected after a while. Of course, you can still get into memory leaks with instance methods too! But it's less of a problem.
Hope that helps!
The main disadvantage is that you cannot swap, override or choose method implementations at runtime.
The performance advantage is likely negligible. Use static methods for anything that's not state dependent. This clarifies the code, as you can immediately see with a static method call that there's no instance state involved.
Disadvantage -> Static
Members are part of class and thus remain in memory till application terminates.and can't be ever garbage collected. Using excess of static members sometime predicts that you fail to design your product and trying to cop of with static /procedural programming. It denotes that object oriented design is compromised.This can result in memory over flow.
I really like this question as this has been a point I have been debating for last 4 years in my professional life. Static method make a lot of sense for classes which are not carrying any state. But lately I have been revised my though somewhat.
Utility classes having static methods is a good idea.
Service classes carrying business logic can be stateless in many cases. Initially I always added static methods in them, but then when I gained more familiarity with Spring framework (and some more general reading), I realized these methods become untestable as an independent unit as u cannot inject mock services easily into this class. E.g. A static method calling another static method in another class, there is no way JUnit test can short circuit tis path by injecting a dummy implementation at run time.
So I kind of settled to the thought that having utility static methods which do not need to call other classes or methods pretty much can be static. But service classes in general should be non static. This allows you to leverage OOPs features like overriding.
Also having a singleton instance class helps us to make a class pretty much like a static class still use OOPs concepts.
It's all a question of context. Some people have already given examples where static is absolutely preferable, such as when writing utility functions with no conceivable state. For example, if you are writing a collection of different sort algorithms to be used on arrays, making your method anything but static just confuses the situation. Any programmer reading your code would have to ask, why did you NOT make it static, and would have to look to see if you are doing something stateful to the object.
public class Sorting {
public static void quiksort(int [] array) {}
public static void heapsort(int[] array) { }
}
Having said that, there are many people who write code of some kind, and insist that they have some special one-off code, only to find later that it isn't so. For example, you want to calculate statistics on a variable. So you write:
public class Stats {
public static void printStats(float[] data) { }
}
The first element of bad design here is that the programmer intends to just print out the results, rather than generically use them. Embedding I/O in computation is terrible for reuse. However, the next problem is that this general purpose routine should be computing max, min, mean, variance, etc. and storing it somewhere. Where? In the state of an object. If it were really a one-off, you could make it static, but of course, you are going to find that you want to compute the mean of two different things, and then it's awfully nice if you can just instantiate the object multiple times.
public class Stats {
private double min,max,mean,var;
public void compute(float data[]) { ... }
public double getMin() { return min; }
public double
}
The knee jerk reaction against static is often the reaction of programmers to the stupidity of doing this sort of thing statically, since it's easier to just say never do that than actually explain which cases are ok, and which are stupid.
Note that in this case, I am actually using the object as a kind of special-purpose pass by reference, because Java is so obnoxious in that regard. In C++, this sort of thing could have been a function, with whatever state passed as references. But even in C++, the same rules apply, it's just that Java forces us to use objects more because of the lack of pass by reference.
As far as performance goes, the biggest performance increase of switching from a regular method is actually avoiding the dynamic polymorphic check which is the default in java, and which in C++ is specified manually with virtual.
When I tried last there was a 3:1 advantage of calling a final method over a regular method, but no discernible for calling static functions over final.
Note that if you call one method from another, the JIT is often smart enough to inline the code, in which case there is no call at all, which is why making any statement about exactly how much you save is extremely dangerous. All you can say is that when the compiler has to call a function, it can't hurt if it can call one like static or final which requires less computation.
The main problem you may face is, you won't be able to provide a new implementation if needed.
If you still have doubts ( whether your implementation may change in the future or not ) you can always use a private instance underneath with the actual implementation:
class StringUtil {
private static StringUtil impl = new DefaultStringUtil();
public static String nullOrValue( String s ) {
return impl.doNullOrValue();
}
... rest omitted
}
If for "some" reason, you need to change the implementation class you may offer:
class StringUtil {
private static StringUtil impl = new ExoticStringUtil();
public static String nullOrValue( String s ) {
return impl.doNullOrValue(s);
}
... rest omitted
}
But may be excessive in some circumstances.
No, actually the reason for that advice is that it provides a performance advantage. Static methods can be called with less overhead so any method that doesn't need a reference to this ought to be made static.
No there is no disadvantages, rather when you are not accessing any instance members in the method then there is no meaning of having it as an instance method. It is good programming skill to have it as a static method.
and adding to that you don't have to create any instances to access these methods and thus saving a memory and garbage collecting time.
In order to call the static methods you don't need to create class objects. The method is available immediately.
Assuming the class is already loaded. Otherwise there's a bit of a wait. :-)
I think of static as a good way to separate the functional code from procedural/state-setting code. The functional code typically needs no extension and changes only when there are bugs.
There's also the use of static as an access-control mechanism--such as with singletons.
One disadvantage is if your static methods are general and distributed in different classes as far as usage is concerned. You might consider putting all static methods that are general in a utility class.
There shouldn't be any disadvantages--there may even be a slight advantage in performance (although it wouldn't be measurable) since the dynamic lookup can be avoided.
It's nice to tag functions as functions instead of having them look like Methods--(and static "Methods" ARE functions, not methods--that's actually by definition).
In general a static method is a bad OO code smell--it probably means that your OO model isn't fully integrated. This happens all the time with libraries that can't know about the code that will be using it, but in integrated non-library code static methods should be examined to evaluate which of it's parameters it's most closely associated with--there is a good chance it should be a member of that class.
If a static method just takes native values, then you're probably missing a handful of classes; you should also keep passing native variables or library objects (like collections) to a minimum--instead containing them in classes with business logic.
I guess what I'm saying is that if this is really an issue, you might want to re-examine your modeling practices--statics should be so rare that this isn't even an issue.
As others have said, it provides a slight performance advantage and is good programming practice. The only exception is when the method needs to be an instance method for overriding purposes, but those are usually easily recognised. For example if a class provides default behaviour of an instance method, that happens not to need instance variables, that clearly can't be made static.
In general:
You should be writing your software to take advantage of interfaces and not implementations. Who's to say that "now" you won't use some instance variable, but in the future you will? An example of coding to interfaces...
ArrayList badList = new ArrayList(); //bad
List goodList = new ArrayList(); //good
You should be allowed to swap implementations, especially for mocking & testing. Spring dependency injection is pretty nice in this respect. Just inject the implementation from Spring and bingo you have pretty much a "static" (well, singleton) method...
Now, those types of APIs that are purely "utility" in purpose (i.e., Apache Commons Lang) are the exception here because I believe that most (if not all) of the implementations are static. In this situation, what are the odds that you will want to ever swap Apache Commons out for another API?
Specifically:
How would you elegantly handle the "staticness" of your implementation when you're targeting, say, a Websphere vs. Tomcat deployment? I'm sure there would be an instance (no pun intended) of when your implementation would differ between the two...and relying on a static method in one of those specific implementations might be dangerous...