This question already has answers here:
When to use static method and field?
(6 answers)
Closed 8 years ago.
Until now I wrote my programs by using only static methods. I haven't abused the principles of OOP at all. My question is, when should I start working with objects instead of using static methods? Because it seems to me that using static methods makes my life easier, but I might be wrong.
Static Methods make your live easier, because you dont have to worry about Accessability in different scopes (not talking about private/public Methods - static methods are ALWAYS there, no matter in which context you are). Basically every OOP Method can be converted to a static method, using the object as one of the parameters. Also each Static method, having an object as a parameter could be converted to a method on the object instance.
People have been developing Apps, before any sort of "OOP" was known, so its not a "musst have".
General speaking:
Does your method require "Object Properties"? Use an Object/instance method.
Does your method NOT require Object Properties? Use a static method.
OOP makes your live easier, when you have coupled data (like a person has a certain fore- and surename and an email adress -> create an object with those 3 attributes). Instead of passing 3 Parameters to a method, you could implement a method without parameters on the object, and have access to all 3 values.
You would not run into trouble, swapping forenames or email adresses somewhere. Your Object clearly keeps track of data relation.
You can't write everything using static methods. Just as one example, if you create a JFrame and want to use a control that custom paints itself, you must create a subclass of at least JComponent and override the paint methods.
As long as you don't need any state in your class, static methods are fine. It is also harder to test.
Related
I am looking at other peoples' code.
I see a class with no non-static fields but in which most of the methods are non-static, requiring you to make an object to access methods that effectively operate statically.
Is there a possible reason for this, that I am just not understanding?
EDIT
Someone asked for examples. Here is some more info.
For instance there is a file manager class. The only fields are static and are Comparators. There are some methods to do things like sort files in a list, count files, copy files, move files to an archive folder, delete files older than a certain time, or create files (basically take a base name as string, and return a File with given base name and date/time tacked on the end.)
9 non-static methods
5 static methods
I don't see a particular rhyme reason for the ones that are static vs non.
One particularly odd thing is that there are two methods for removing files. One that removes a file no matter what, and one that only removes it if it is empty. The former is a static method while the latter is not. They contain the same exact code except the later first checks if the file.length is 0.
Another odd one is a class that does encryption - all fields and methods are static but it has a constructor that does nothing. And an init() method that checks if a static variable contains an object of itself and if not instantiates an object of itself into that field that is then never actually used. (It seems this is done with a lot of classes - init methods that check for an object of itself in a static variable and if not instantiate itself)
private static File keyfile;
private static String KEYFILE = "enc.key";
private static Scrambler sc;
It has methods to encrypt and decrypt and some methods for dealing with key and file.
Does this make sense to anyone? Am I just not understanding the purpose for this stuff? Or does it seem weird?
Objects don't have to have state. It's a legitimate use case to create an instance of a class with only behaviour.
Why bother to create an instance ? So you can create one and pass it around e.g. imagine some form of calculator which adheres to a particular interface but each instance performs a calculation differently. Different implements of the interface would perform calculations differently.
I quite often create classes with non-static methods and no members. It allows me to encapsulate behaviour, and I can often add members later as the implementation may demand in the future (including non-functionality related stuff such as instrumentation) I don't normally make these methods static since that restricts my future flexibility.
You can certainly do it that way. You should look carefully at what the instance methods are doing. It's perfectly okay if they're all operating only on parameters passed in and static final static class constants.
If that's the case, it's possible to make all those methods static. That's just a choice. I don't know how the original developers would justify either one. Maybe you should ask them.
Let me rephrase this question a bit,
Even though methods are non-static why would one declare fields as static?
I have taken below quoting from Java Docs,
Sometimes, you want to have variables that are common to all objects. This is
accomplished with the static modifier. Fields that have the static modifier in their declaration are called static fields or class variables. They are associated with the class, rather than with any object. Every instance of the class shares a class variable, which is in one fixed location in memory. Any object can change the value of a class variable, but class variables can also be manipulated without creating an instance of the class.
For example, suppose you want to create a number of Bicycle objects and assign each a serial number, beginning with 1 for the first object. This ID number is unique to each object and is therefore an instance variable. At the same time, you need a field to keep track of how many Bicycle objects have been created so that you know what ID to assign to the next one. Such a field is not related to any individual object, but to the class as a whole.
For Bicycle example, kindly refer the Java Docs.
Making all methods non-static allows you to override them. This makes it a lot easier to use this class in testing, because instead of the actual implementation you can use a mock that behaves as you want it for the tests. Static methods are, in my book, a code smell and should be avoided unless there's a good reason (e.g. quite trivial utility methods).
Also, at some point in the future you might want to change the behaviour of the methods in some situation, e.g. in the form of a strategy.
In the case of your encryption class, you might want to hand your class an instance of the encryption class to handle encrypting/decrypting, but be able to configure the details in some other place. That would allow you to change the algorithm and much more easily test your own code without also having to test the encryption.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 9 years ago.
Improve this question
With the time ...lots of utility method are introduced in java project for more complex and simple task.
When using static methods we introduce tight coupling in our code and it make our code more difficult to test, especially if the utility methods are quite complex.
I am just thinking that it now difficult to manage and test these utilities. please guide me in avoiding these utilities methods and how can i organize existing project to remove all STATIC utilities.
Can you help me avoiding static method ?
There is nothing wrong with having lots of static methods.
Static methods are (or should be, read on) stateless, which makes them the easiest methods to test - there's no setup, just call them.
You don't need mocking, because there is no state to deal with.
Regarding being stateless, technically static methods can be stateful if they use static variables to store state. If this is the case, from a good-design perspective they should be converted to instance methods using instance variables to store state, employing the singleton pattern if required.
To contradict the other answers currently available: Static methods are bad!
They do introduce strong coupling. Yes there are cases where it is acceptable. Yes you can make a seam for inside a static method, by making the strategy used inside exchangeable. But as a rule of thumb static are still bad.
To answer the question, how to get rid of static methods. Simple: put them on a proper Object. All statics are gone. Have we improved our code? not much yet. If we replace
callToStaticMethod()
with
new X().callToNoLongerStaticMethod()
we replaced a static call with a constructor call which is essentially just another static method. But now your X is just another dependency, so you can inject it:
class A{
private final X x;
A(X aX){
x = aX;
}
}
Note: there is no need to use Spring or any other framework for this. If you feel like it provide a constructor which uses the default implementation. If you are a purist, introduce an interface for X.
Testing A without relying on the implementation of X becomes trivial and obvious. Same for replacing X in any way.
Static utility methods are not so bad. You can hide a package-private strategy behind the static call. This can be easily tested (and replaced) given that the test case belongs to the same package. Moreover, it makes the code very readable. Of course, the clients of the static utility method can still only use one implementation in their tests. So here is some inflexibility.
Bohemian is right when talking about state. If your static utilities have state you are doing something wrong.
About your question: If you want to avoid static methods you can use the spring framework and define different implementations of utilities that you use and test in different contexts. In this case, however, access to these objects is not so convenient as you must first obtain a reference to the context that knows your utility object.
Nothing wrong with a set of static utility methods that belong together in a class. See for example java.util.Collections. If every method in that class that operates on a List would be specified in the List interface itself, they would have to be implemented by all subclasses. As long as they can be implemented by the public List methods, there is no problem.
Of course, as soon as you start adding methods to the interface (or in case of a class, making methods public) only to be able to put functionality in static methods instead of the class itself, then you're on the wrong path.
Here is what you need to know to understand the question:
I want to connect a class called SCL to a class called Region.
Now I have many different ways I want to connect a instance of
these 2 classes.
Writing this is Java
There are no global variables in use
So I can either create several classes(about 9) that utilizes polymorphism but then each class has only one method called connect(...) with many different parameter lists. I think this is called a functor class.
For example a class "SCLToRegionOverlapCircleConnect" will have a connect method that looks like
public void connect(SCL scl, Region region, int radius, int overlapPercentage) {...}
while a class "RegionToRegionNonOverlapSquareConnect" will have a connect method that looks like
public void connect(Region bottomRegion, Region topRegion, int sideLength) {...}
OR
I can just make one class called ConnectionTypes and just have 9 different methods each with a different method signature.
What are the PROs and CONs of each implementation? Thanks!
If you use polymorphism, then you're determining the connection method when you instantiate the SCL object. Does that make sense? Or could an SCL class be connected to the Region in various different ways thoughout its life? In that case, polymorphism doesn't make sense. One important aspect that we have no information about is what happens to the parameters of the connect(...) method. Do they need to be stored in the SCL class, in which case with different parameters polymorphism might again make sense so that each class can store the appropriate parameters.
Another thought is, is the act of connecting an SCL class to a region really a method for the SCL class at all, or should it live somewhere else?
I suggest you to use the second.
less classes, so the project is clarelier than in the other way.
you don't need to move 9 classes when you want to use your
methods in another project (ex.), but only one class.
while programming, one rule is not to duplicate the code; using 9 classes,
you have to write 9 times the declaration, and maybe to declare 9
times the same global variables, using a lot more memory than using
one.
overloading, that means that if you have to make one thing
but in multiple ways (ex. you have to print some objects, and the
result will be one string, but you need to write it different for
one type of object, etc., you can use this technique) you can write
9 methods with the same name, same output, but different inputs.
inheritance: if you want to make a class that inherits those
methods, you MUST use only one class, because java does not support
multiple inheritance.
I can't see any CONs, except that you have to reinitialize the global variables to avoid problems.
Let me put two things straight:
You are thinking of the Command pattern, not the Functor pattern. The difference is that the latter also has a method to retrieve the return value, but your connect method is void.
The Functor pattern would not have a different signature for each of your connect methods; instead, each concrete class would have dedicated setters for the parameters (specific to the particular way you want to connect) and the same, parameterless public void connect() method. The latter would be the only method declared in the common Connect supertype.
I can throw in some example code if you want.
Pro: if it makes sense anywhere in your code to work with Connect commands without needing to know which of the 9 ways you're dealing with, then the Command pattern is your friend.
Con: you will have more code, and encapsulating pure functionality can reduce the understandability of your code quite a bit.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Difference between static class and singleton pattern?
Why would one ever require one and only one instance? Same purpose can be achieved using classes with static member variables and static methods.
As far as I can find out, there might be two possible answers to it -
When your class needs to have state and you want only one object of it. From the design point of view, class with static methods & variables are considered to be the Utility classes and shouldn't be keeping any state.
If your class needs to take part in polymorphism and you want only one object of the class(es) which are in the inheritance tree.
It would be really helpful if someone can provide an example from real life scenario or from any Java API where Singleton objects need to participate in Polymorphism / Inheritance?
Collections.emptySet() is a typical example of a singleton that can't be implemented as a static class since, obviously, its goal is to be an instance of the java.util.Set interface. It's not costly to create, but it would be stupid to create a new instance each time an empty set is needed, since the unique instance can be reused.
Classes that perform logging or common access to data bases frequently follow the Singleton pattern. Basically anything that should have instance methods and that is costly to construct.
Scope and behavior are different concerns and should NOT be mixed. You may want your object to be available per use, per thread, per web request, per session or global (Singleton). The reasons for making these adjustments are likely due to resource management and ultimately performance. The behavior inside your class shouldn't have to change if you change its scope.
Singleton is pattern for taking a regular object and controlling its scope with just a little bit of bolt-on code. Ideally though, you really shouldn't really deal with scope at all inside your object and delegate that to a factory or container.
My answer is quite short but it's enough to use exactly common singleton instead of it's static implementation. The answer is:
Popular paradigm (yes it is!)
Threads (synchronization etc.)
Interface implementation (your static class has some restrictions)
Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 4 years ago.
Improve this question
As per my understanding we should go for instance methods only when they are dealing with state of object i.e instance variable . If method does deal with state of object they should always be declared as class methods i.e static. But still in most of the projects
i ihave seen the methods which never not operates on instance variables they are also declared as instance methods(basically what these methods are doing they are using some of the method parametrs and doing some processing on that paremets and calling some other classes).Thats it.
Should not these methods should be declared as class method i.e static ?
It's likely the answer is yes: if you have an instance method that doesn't actually take advantage of the instance state, then it should probably be static, and possibly moved to a helper class depending on what it does.
Note that even if you don't access instance variables, accessing instance methods will also disqualify a method from becoming static. Also, if this method is an instance method in order to future-proof it (in anticipation of using the instance state later,) then changing it wouldn't be advisable either.
Also important is that public non-static methods could be inherited and overriden by a subclass, so making them static could actually break the code in possibly unexpected ways.
Here's a [possibly incomplete] list when you must use instance methods over static ones:
you access instance variables / methods from within the method
the method is an abstract method that you implement
the method is an interface method that you implement
you have doubts about the method staying static in the long-term
you declare it synchronized and don't want to lock on the class, rather on the instance
you get warnings when accessing static methods in a non-static way and you really care about them (sometimes you just can't avoid calling in a non-static way, so your only choice is making them methods non-static)
You could probably go static in all other cases.
Static methods have the disadvantage that they tightly couple callers to the implementation. Instance methods can be overridden or can be one of multiple implementations of an interface method.
In other words, instance methods can promote loose coupling, testability, and reuse.
You cannot expect everyone to follow a path all the time whether it is best practice or not. First, we are all humans. We can choose a way over something different sometimes and that shouldn't be fully correct all the time. Even Frameworks and Libraries and Languages are created by humans so an error shouldn't surprise you or bedazzle you.
For everything else, I concur dlev.
Suppose we're designing a new language and we want Sqrt to be an instance method. So we look at the double class and begin designing. It obviously has no inputs (other than the instance) and returns a double. We write and test the code. Perfection.
But taking the square root of an integer is valid, too, and we don't want to force everyone to convert to a double just to take a square root. So we move to int and start designing. What does it return? We could return an int and make it work only for perfect squares, or round the result to the nearest int (ignoring the debate about the proper rounding method for now). But what if someone wants a non-integer result? Should we have two methods - one that returns an int and one that returns a double (which is not possible in some languages without changing the name). So we decide that it should return a double. Now we implement. But the implementation is identical to the one we used for double. Do we copy-and-paste? Do we cast the instance to a double and call that instance method? Why not put the logic in a library method that can be accessed from both classes. We'll call the library Math and the function Math.Sqrt.