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.
Related
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.
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 9 years ago.
Improve this question
I am working on a java class for parsing HTML and generating RDF (which I think I will eventually split into two classes - one for parsing and one for generating RDF).
At the moment I am creating a lot of methods for checking HTML data and converting it into a more uniform representation. Some of the methods I have created so far are:
public boolean isInteger(String str) { }
public boolean isTime(String str) { }
public boolean isDate(String str) { }
public String dateConverter(String[] date) { } //Converts a Norwegian date into mmddYYYY
Should I put methods like these into a util class? At the moment they are only being used by this specific class, but I think that they might need to be use them by more than this one class at a later point in time.
Well, yes, the methods you listed look like good candidates for public static methods in a util class. (The last 2 or 3 would fit nicely in a class called "DateUtils", for example.)
Of course, if you only use them in one place, they can just as well remain "private helpers" there, but as soon as you have multiple places using them, a util class makes sense.
(Edit: overuse of static methods can be problematic, but I think these methods could well be static utils because they are pure functions.)
They seem generic enough to be appropriate to put in a util class. I would, at the very least. Basically any class that parses String in your code would need to use those methods. I would make them static before adding them to the class though to avoid unnecessary construction.
Decomposition is a good habit to get into. If you are unsure about whether or not you need to use them, then go ahead and do so. It will give you practice with using utility classes.
It is a good practice to collect such methods in a utility class. Even if they are called from a single class at the moment, these kind of methods will be potentially reused by other clients in a near feature.
However, you must pay attention to make this utility class easy to be reused. To do this, the method signatures, actually their arguments, must be as generic as possible. They should not take inputs specific to a class.
Another advice of mine is dividing this utility class into more than one classes, if it begins to contain many incoherent methods. You can do this by grouping the relevant methods in a separate class. For example, methods you wrote can be moved to TypeUtils class and you can collect conversion related methods in Html2RdfUtils class for instance.
Finally, if you feel that these utility classes can be benefical to your other projects, you can collect them in a distinct library.
if you eventually want to split them into two classes, you may want to define the baseclass as interface or abstract class.
Base on your requirement, abstract class should be the right choose.
Put something in common from the child class to the abstract class.(You can implement method in the abstract class)
from another answer, I want to ask a question?
the answer suggest putting static in front of the method to avoid unnecessary construction, it very make sense.
I know the abstract class does not require to be instantiated to call its method.
it also can avoid construction.
There is the question?
Which way is more legit? or better? or just same.
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.
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Why does this() and super() have to be the first statement in a constructor?
I just learned that at school, but the teacher doesn't know why.
I can think of some good reasons, but I think there are cases when the initializing can be done later in the constructor- before you use the variables form the mother class, for example. OK, the variables should be initialized from the start, but that's not always necessary.
I"m guessing there are a more reasons for that why must super() be placed in the first line of the constructor.
So, why must I write super() in the first line of the constructor, when I'm inheriting a class?
The class you're inheriting from needs to be able to complete its construction, before you have start working on your own class.
Without doing this you could do lots of "bad" things, e.g.
Pass this to another method somewhere else, which uses the base class, before its constructor has run. That would break lots of assumptions
Call polymorphic functions that haven't been "set up" correctly yet. As well as anything done by the class itself the implementation possibly uses the constructor call to handle implementation internals too.
Accessing an object before it's been constructed is bad, in the same way that fried chicken "is-a" chicken you really don't want to access (eat) that chicken before it's been fried.
Access protected/public member variables of the base class which the base class was trying to promise would always be initialised to some state.
It's perfectly reasonable for a class to make a promise that any instances of it will always be in some given state. If you get a chance to do things before the constructor has been called then there's no way to honour promises like that. Essentially the "is-a" relationship wouldn't actually hold if the thing that it "is" isn't actually that thing yet!
In addition to awoodlands answer: You dont have to write super(), since the Java-Compiler will automatically call all the default constructors up the hierarchy.
Exception: If you dont have a default constructor in the base class, you would have to call your custom constructor using super(ConstructorArgs args).