I was going through java class in which I found all the methods were static , I want to know when there is the requirement or where the condition arises when we have to prefix static in front of all the methods. Is it any kind of design pattern..?
This is typically used in utilities classes. Think for example the Math class. You don't need an instance of an object to calculate the minimum of 2 numbers, so it makes sense that Math.min is a static method.
However, overuse of static methods / fields is not necessarily a good design practice.
Exactly: utility pattern
http://en.wikipedia.org/wiki/Utility_pattern
Helper classes usually provide static only methods. These are classes that provide some methods that are not specific just to one kind of object, but can be shared across the entire project. For instance, a MathHelper could define a method for calculating the average of an array of float values, another one for calculating the distance between 2 points and so on.
Classes which have all static methods are used for below purposes :
1) Copied from Joshua Bloch Effective Java
Interfaces can’t have static methods, so by convention, static factory methods for
an interface named Type are put in a noninstantiable class (Item 4) named Types.
For example, the Java Collections Framework has thirty-two convenience
implementations of its collection interfaces, providing unmodifiable collections,
synchronized collections, and the like. Nearly all of these implementations are
exported via static factory methods in one noninstantiable class (java.util.Collections).
The classes of the returned objects are all nonpublic.
2) Utility Pattern as suggested by #tgoossens
Related
I was reading effective java and one advantage of static factory methods written is that they can return an object of any sub-type of return type.
I understood the way we can implement this as mentioned in following link with example.
https://www.slideshare.net/mysky14/java-static-factory-methods
But in the book an example of Collections API is given that has static factory methods in java.util.Collections utility class and it is written that "Collections API is much smaller than it would have been had it exported 32 separate public classes".
It is also mentioned that in this manner, API can return objects without their classes to be public and this results in very compact API.
I want to know how the API size is reduced by implementing this method and not having separate public classes.
I want to know how the API size is reduced by implementing this method and not having separate public classes.
Let's use the same concrete example used in the book: java.util.EnumSet has static factories that return one of two implementations: RegularEnumSet or JumboEnumSet. These implementations have their own complexities, but are effectively hidden to the clients of Collections. In theory, the factories could use other implementations in the future, and the clients of them would not be affected.
If you visualized this in a class diagram, the factory methods (e.g., of(), as opposed to a constructor) return an abstract type EnumSet, which hides the details of the implementations. Abstract (or Interface) types effectively abstract (simplify) the API.
What's more, the implementations are actually package private, meaning they're declared without a public keyword. This means that only classes in the same package can see them, so it prevents having Client depend on them. This is a great example of information hiding, which allows API developers to simplify their API and also to change the hidden parts later without breaking the code.
Another example that comes to mind where factory methods can simplify an API are the concrete iterators in Collections. In this case, it's a factory method that is not static, e.g., ArrayList.iterator(), that returns a concrete iterator for ArrayLists. The name of this class is even less "known" than the EnumSet implementations.
In general having static factory method would take out your object instantiation logic out of your class. Suppose based on certain logic, you need to return different subclass objects. This would result in if-else logic in your class method whichever is responsible for appropriate object instantiation. Moving this out to static factory method would result in cleaner class design which would be easier to test and closer to "Closed to modification" principle
Why did new Spliterators class appear in Java 8? Since Java 8 we have possibility to add static methods to the interfaces.
Since Spliterators class has only static method wouldn't be simpler to declare all its methods in the Spliterator interface?
The same question about Collectors/Collector pair.
Thank you.
It’s perfectly possible that this decision was made without even thinking about this brand new possibility, but simply following the established-since-twenty-years pattern.
Besides that, it can be debated whether it is really useful to add 25 to 30 static methods to an interface. It makes sense to offer a few factories for canonical implementations, but you should draw a line somewhere. It’s not feasible to add factories to all implementations to an interface, just because they are offered by the same library. But this debate would be off-topic.
Further, Spliterators does not only offer static methods, but also nested classes. Unlike static methods, these classes would pollute the name space of every implementation class, when being defined in an interface.
Collectors and Spliterators may also contain implementation-specific non-public methods and even fields.
No, is not good idea, because interface declares a contract, but class represents logic. But after add default method to interface in Java 8 we can only declare public method, but in abstract class we can add public and private abstract method, so we still can hide some logic in abstract classes. Imagine, in actual level of language you can declare only public method, and everyone can change your idea for e.q. Collection
Because there is a difference between an interface and a class. These two have different intentions. Interface declares a contract. Default methods for the interface should be used carefully, for instance, where you can't break compatibility by adding a method declaration into an interface and can't declare xxxV2 interface.
A class is an entity, which represents a unit of the program logic.
Maybe this question is general but I did not find an answer I was looking for, so I was hoping to get some ideas from this post. I am trying to move out some commonly used methods to a helper to simplify my design. I looked at multiple posts and debate about making the utility methods static v/s non-static. My question is more related to creating a helper classes with a combination of static and non-static methods. Since the existing class contains a combination of static and non-static methods that I want to move out as I do not want duplicate code in multiple classes. So, I was wondering if it is a good idea to include both static and non static methods in the helper class. The reason I am a little hesitant is most utility methods are static in nature and I want to understand if it a good design choice to have static and non-static methods in utility classes. Any suggestions??
It depends on what the class is doing.
Non-static methods imply that the helper class maintains some state that can be different across different instances. If you don't have that then all static methods is the way to go (think like the java Math or Collections classes).
If you need to maintain instance state across method calls, then non-static methods are useful. If you go in this direction, then your helper class will have constructors or static factory methods that create Helper objects and each instance will have fields that maintain state.
non-static methods might also be a good idea if your otherwise static methods often have the same parameters over and over again that are all the same values/references. In that case it might be cleaner to make those constructor parameters and just have the method parameters for the additional parameters that differ between the methods.
As a general convention, should static method(s) be separated into another class from a class with instance methods?
Is there also an example of your reason?
There is no general convention that dictates that a static method must be separate from a non-static method. In fact, if the two methods are related enough to one another, it would be counter-intuitive to have the methods separated.
Recall what use case static methods (and fields) have: they're methods/fields that can be used without an instance of a particular class. This generally means that they hold valuable metadata or perform a useful operation that's related to their class instance, but would not require direct instantiation of that class.
Take, for example, Integer. It has the static [final] fields MAX_VALUE and MIN_VALUE. Since both of these fields contain fixed information that would not change between instantiations, it would not make sense to have to instantiate an Integer to get this information.
Integer also has the useful operation parseInt, which takes a String and turns it into an int. We shouldn't require an instance of Integer to convert from String to int, especially if we're not placing it into an instance of Integer.
The overarching convention has been to keep related methods together, regardless of if they're static or not. You can see clearer examples of this in certain Java library classes, like Integer.
It probably is a duplicate question, but no, static methods have very specific benefits that are often valuable in classes that are instantiated as objects.
There is no such convention. It's completely depends on your situation. Some class may really needs mixture of both static and non-static members.
But some times it's is seen the use of Constatns.java/ Utils.java class in some java project. You may found -
public static final double PI = 3.1416;
public static getArea(double r){}
This class contains some final static property and some final method. The purpose of these class to provide some constants or utility method all over the project.
Definitely answer would be dictated by the use case but there is no convention as such. At most you have some Utility class that may have bunch of static methods that are used by other classes as helper methods. For example to test whether a String is an email or to extract username from email etc.
Putting all static methods in a separate class would be useful while writing an API or a framework. Collections class is an example. java.lang.Math or java.lang.System is another.
Normally, define static methods in the following scenarios:
While writing utility classes .
If the method does not use any instance variable.
If any operation is in-dependent of instance creation.
If you are sure that the definition of the method will never be changed or overridden. As static methods can not be overridden.
see here - https://stackoverflow.com/a/5313383/760393
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.