Lets say I have a Helper class like with a few methods
public class SomeClassesHelperClass(){
public List removeDuplicatesFromTheGivenList(List someList){
// code here
}
public int returnNumberOfObjectsThatHaveSomeSpecialState(List someList){
// code here
}
}
What are the advantages / disadvantages of making the methods in this class static? Which is the better practice?
If your class provides only utility methods (like yours), I believe it's better to:
make the class final (there's no point to extend it)
define а private constructor to avoid any attempt to create an instance of the class
make all the methods static.
If you decide to make all the methods static then you need to be aware of the impact that that will have on your ability to test other classes that depend up on it.
It severely limits your options for mocking ( or at least makes it more painful )
I don't think there is a right answer to our question - it depends on what the methods do. For example, it's easy to envisage a stateless data access object - if you make all its methods static then you are building a dependency on the data source in to your test cycle, or making your mocking code much uglier
Make them static when they use no state from an object. Most of it are helper classes like Math. http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html
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.
When the Gang of four introduced the singleton pattern, they also had to explain, why not to use static class fields and method instead. The reason was: the possibility to inherit. For Java it had sense - we cannot normally inherit the class fields and methods.
Later the "Effective Java" book appeared. And we know now that the existence of reflection destroys the singularity of the singleton class with private constructor. And the only way to make a real SINGLEton is to make it as a single item of an enumeration. Nice. I had done some myself this way.
But a question remains: While we cannot inherit from enumeration, what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Edit. Thanks to the #bayou.io I see that in https://softwareengineering.stackexchange.com/a/204181/44104 there is a code that can trick the enum, too, and create again two exemplars of the enum singleton. The other problems are mentioned there, too. So, there is no need to use enum instead of the usual singleton class pattern, too? BTW, all enum pluses that are mentioned here till now, work for singleton classes, too.
what is the use of this singleton? Why we don't use these old good static/class fields and methods?
Because enum is an object so it can not only be passed around but also implement interfaces.
Also since we are making a class, we can use the different public/private options available to all kinds of classes.
So in practice, we can make a singleton that implements an interface and then pass it around in our code and the calling code is non the wiser. We can also make the enum class package private but still pass it around to other classes in other packages that expect the interface.
If we used the static methods version, then the calling class would have to know that this object is a singleton, and our singleton class would have to be public so the other classes can see it and use it's methods.
There's nothing particularly wrong with the "good old fashioned singleton", enum "singletons" are just convenient - it saves you the need to muck around with boiler-plated code that looks the same in every singelton.
To me, a singleton makes sense wherever you want to represent something which is unique in its kind.
As an example, if we wanted to model the Sun, it could not be a normal class, because there is only one Sun. However it makes sense to make it inherit from a Star class. In this case I would opt for a static instance, with a static getter.
To clarify, here is what I'm talking about :
public class Star {
private final String name;
private final double density, massInKg;
public Star(String name, double density, double massInKg) {
// ...
}
public void explode() {
// ...
}
}
public final class Sun extends Star {
public static final Sun INSTANCE = new Sun();
private Sun() { super("The shiniest of all", /**...**/, /**...**/); }
}
Sun can use all the methods of Star and define new ones. This would not be possible with an enum (extending a class, I mean).
If there is no need to model this kind of inheritance relationships, as you said, the enum becomes better suited, or at least easier and clearer. For example, if an application has a single ApplicationContext per JVM, it makes sense to have it as a singleton and it usually doesn't require to inherit from anything or to be extendable. I would then use an enum.
Note that in some languages such as Scala, there is a special keyword for singletons (object) which not only enables to easily define singletons but also completely replaces the notion of static method or field.
ENUM singletons are easy to write. It will occupy very less code, which is clean & elegant if you compare with implementation of lazy singleton with double synchronized blocks
public enum EasySingleton{
INSTANCE;
}
Creation of ENUM instance is thread safe.
ENUM singletons handled serialization by themselves.
conventional Singletons implementing Serializable interface are no longer remain Singleton because readObject() method always return a new instance just like constructor in Java. you can avoid that by using readResolve() method and discarding newly created instance by replacing with Singeton
private Object readResolve(){
return INSTANCE;
}
Have a look at this article on singleton
I am trying to refactor a project in which there are same methods which are spread across various classes. To reduce code duplication, should I move the common code to an abstract superclass or should I put it in a static method in a utility class?
EDIT
Some of the methods are for generic stuff which I believe can be made static. While there are others which refer to attributes of the class, in which case I think it makes more sense to make it as an abstract super class.
Well, I follow a rule: Don't use base class to remove code duplication, use utility class.
For inheritance, ask question to yourself: Does Is-A relationship exist?
Another rule, which most of the times is correct, is: Prefer composition over inheritance
using static utility class is NOT true composition but it can be called a derivation of it.
Apply these rules to your secenrios and take a decision keeping in mind maintanence and scalability. However it will be good if you could add more details to your quesiton.
It depends on what your code is doing. Are they utility methods? Are they specific/specialized class methods? Is this a heavy multithreaded application?
Keep in mind that if you make them static and your application is multithreaded, you will have to protect them w locks. This, in turn, reduces concurrency. In this case, depending on how many threads call that same piece of code, you might consider moving it (the code) to a super class.
Another point to consider may be the type of work these functions do. If that is scattered, you should create a facade / helper / util class with static methods.
As others have mentioned the answer to this depends on the context of the problem and the duplicated code.
Some things to consider
Does the duplicated code mutate the instance of the object. In this case a protected method in a common abstract class
Instead of Static utility class consider a singleton, Static methods can be problematic for pure unit testing although testing frameworks are getting better at this.
Inheritance can be tricky to get right, think about if these objects from the different classes are really related and require some OO re-factoring ? or are they disjoint pieces of domain logic that happen to require similar bits of code.
If it does not use any class members you might do it static!
But you should do it in a abstract class or mother class
If the methods use many fields or methods of the class they should not be static.
If they are something that a subclass might want to modify they should not be static.
If the methods should be part of an Interface they cannot be static.
Otherwise it's your call and you will probably change your mind later. :-)
At first glance, I would say that it would be better to make the common code as a public static method in a public class. This will make the method useful to any class just by using
UtilityClassName.methodName();
This is better then making it a concrete method in an abstract super-class because then you will always need to extend this super-class in all the classes where you want to use this one single method.
But now, as you said that the method's behavior depends on some variables. Now, if it depends on the instance variables of different classes, then better add this method in an interface and let all your classes implement this interface and have their own implementation of the same.
But again if these variables are constant values, then have these constant values in an interface. Implement these interface in your utility class. And again make it a static method in that utility class which will directly use these constants.
For e.g. Consider foll. common code of returning area of a circle.
public interface TwoDimensional{
double PI = 3.14;
}
public class MyUtility implements TwoDimensional{
public static double getCircleArea(double radius){
return PI*radius*radius;
}
}
Here, you can see that method getCircleArea() depends on the radius which will be different for different classes but still I can pass this value to the static method of myUtility class.
So I consider myself a junior java/android developer
I've always come across these but never really liked them and concidered them as dirty code
class herp{
private class derp extends OnclickListener{
...
}
private class gerp AsyncTask{
...
}
}
so should I try to avoid these? or even make sure I never use these?
What is and isn't dirty code is highly subjective.
What can be said is that nested classes can be very useful. Often times they don't need to be nested like that, as they could just as easily be anonymous classes in all likelihood.
The idea is that: you want as few other classes as necessary to access your little class there. You wouldn't want to make your own package, because you really belong in the package you're already in. Instead, you make a private class. Now only you can use it, which is good because it's tailored just for your class.
Now, how many derp instances will you have? Chances are you'd have one. So instead of doing that, I would do this:
OnClickListener derp = new OnClickListener() {
// fill in methods to override here
}
It does basically the same thing, but I can't reuse the class for anything, which is good - no one should be reusing the one-shot class!
What is and isn't clean code is often times personal preference based upon experience. Nesting classes isn't messes per say, however you should be certain that it is an appropriate situation.
If you desperately need some specific functionality for a class which extends something like the OnClickListener in your question, then it is a question of how many times do you need this class? If the answer is once, then an anonymous class would be a cleaner solution. If the answer is in every single method in the class, then a nested class clearly makes more sense.
More or less every feature in Java has a time and place in which it is considered appropriate. Private nested classes such as the ones you have in your question should be reserved in my mind for cases where you satisfy two conditions:
a) you absolutely have to have a separate class that will only be used in this class and no where else
AND
b) you will need to use that class in multiple locations within the class.
At the end of the day, nested private classes are not inherently dirty or hard to maintain, but as with any other feature of an programming language, make sure you need them.
There is no fixed answer on this question. It mainly comes down to your own coding style, preferences, and your team's coding conventions.
Private inner classes are useful for many reasons. You can use them to provide an implementation of an interface (e.g. a List implementation might define its own Iterator implementation as a private inner class) without making the concrete class visible. It protects the implementation, and allows you to provide just enough details to a user of your API/class so he can use it correctly, without cluttering your documentation with useless details (your concrete class).
You can also use private inner classes as a implementation for listeners, even though some might disagree with this philosophy. I do prefer using private inner classes to anonymous classes when the listener has some complex logic.
You might want to use them also to separate code logic into separate classes, but don't wish to expose those classes outsite your outer class.
Keep in mind that every solution using a private inner class can also be implemented without using them. And as with many things in life, using private inner classes isn't a bad practice per se, but abuse is a bad practice.
It's fine. You may consider making them static inner classes, otherwise you'll need an instance of herp to create one (although that might be what you want):
class herp {
private static class derp extends OnclickListener{
...
}
private static class gerp AsyncTask{
...
}
}
The difference demonstrated is:
public static void main(String[] args) {
// With static:
new derp();
// Without static:
new herp().new derp();
}
Currently i`m interesting in play framework because this framework promise faster development.
When i see the code, there are so many static code. even the controller declared as static function. Thus all the code that called inside static function must be static right?
My question is, is this approach is right? are there any side effect of using to many static function?
This question has been asked in a similar way previously. The simple answer is that Play uses statics where it is sensible.
The HTTP model is not an OO model. HTTP requests themselves are stateless, and therefore, static methods allow access to controllers as functional requests from client code.
The Model classes on the other hand are pure OO, and as a result are not static heavy.
Some of the utility methods, such as findAll or findById are static, but these again are not statefull, and are utility methods on the class. I would expect this in a standard OO model anyway.
Therefore, I don't think there is any risk in doing things in the way Play expects. It may look odd, because it challenges the norm, but it does so for sound reasons.
Couple of things about static methods in an object oriented language: Let me try to explain the problems if you choose to have all static methods.
Using all static functions may not be idiomatic in an Object oriented language.
You cannot override static functions in a subclass. Therefore you lose the ability to do runtime polymorphism by overriding.
The variables that you define all become class variables automatically (since all your methods are static), so essentially you do not have any state associated with the instance.
Static methods are difficult to Mock. You might need frameworks like PowerMock to do the mocking for you. So testing becomes difficult.
Design becomes a bit complex as you won't be able to create immutable classes as you really only have the class and no instance. So designing thread-safe classes becomes difficult.
To elaborate on my comment.
static methods can call non-static methods provided you have an instance of something.
class A {
public void nonStaticMethod() { }
public static void staticMethod(String text) {
// calls non-static method on text
text.length();
// calls non-static method on new Object
new Object().hashCode();
// calls non static method on a instance of A
new A().nonStaticMethod();
}
}
Yes there is a side effect of using too many static functions or variables. You should avoid unnecessary static declarations.
Because static members always creates a memory space once the class is loaded in the JRE. Even if you don't create the object of the class it will occupy the memory.