Singleton and Static Utility classes [closed] - java

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 11 years ago.
What factors influence the appropriate design pattern to use?
Clarification:
The reason I ask this question is because I'm designing an application that requires multiple static factory classes and singleton manager classes. At times, I become confused as to which design I should employ and I thought asking this community why and when may help clarify things for me a bit.

Singleton is used when a single object needs to be instantiated and all requested object access goes through this particular instance. This object can maintain state if desired.
Static Utility is used when you have a class that is just stateless utility functions.. it does not maintain state. An instance of the object is never instantiated.

I use static utility classes for shared functions that will be called from many different contexts - e.g. maths functions similar to those in java.util.Math. This is an appropriate pattern assuming that these are "pure" functions (i.e. don't manipulate any state or access any data other than than the parameters they are given).
I very rarely use singletons, and in particular try to avoid global singletons. They suffer from all the usual problems associated with global variables. They make testing difficult, and unless your singleton is also immutable they introduce problems of global state. The main place I have found them useful is in performance hacks that depend on object identity - for example:
public static final END_OF_SEQUENCE_MARKER=new EndMarker();
Then when traversing a sequence you can just test if (object==END_OF_SEQUENCE_MARKER). Because it's a static final reference, the JIT will turn this into an extremely fast test....
EDIT
Having just seen your clarification, some quick extra comments:
Static factory classes don't usually make sense. The whole point of a factory class is that you can instantiate it (or a subclass!), make some configuration changes on the factory object, then use it to generate object instances according to the configuration that you need. If you're going to make it static, you might as well just create a static MyObject.create(..) method rather than having a whole static MyObjectFactory class....
Likewise, why have a separate singleton manager class? Usually the best class to manage the singleton is the singleton class itself, since you will typically need it to access a private constructor, assuming you want to guarantee that only one instance will ever be created. Just having a simple static MySingleton.getInstance() method will usually do everything that you need.

IMO static utility classes chalk down a concrete contract between the caller and the class. This is different than singletons wherein you can change the implementation behind the scenes to make your so called 'singleton' provider hand out a new instance each time a call to getInstance is made.
So yes, basically use static utility methods when you are damn sure (e.g. Math) you'd never need an instance and use singletons when you think that a single instance is good enough for the time being but might change in the future (e.g. connection providers).

I'm not sure what the question is here.
Singleton patterns are used where the instance has state that may be preserved or altered across a number of calls - this might be a connection pool or some other shared object that the class provides access to.
Static utility classes are used where each individual method is stateless, and has no bearing on the other methods that the class provides.

Related

Creating static utility methods should not be overused however ? how to avoid it? [closed]

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.

What are Java interfaces useful for and how to deal with cross-class methods? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 9 years ago.
I understand that Java Interfaces are used for declaring methods that will be used in more classes as those classes implement them. For example:
public interface MyInterface{
void myVoidMethod();
Bool myBoolMethod(int x);
String myStringMethod(String a,String b);
}
So, from what I understand, it is mainly used just to make sure some methods are declared in a class and those methods are usually ones that are more general, and might be applied in more classes. But what about methods that should already contain some code and should apply to more classes?
For example what if I have many classes where I need myBoolMethod defined as
Bool myBoolMethod(int x){
return x?0:1;}
(I gave just a simple example, but obviously I would need to use more complex methods). I've heard about "code injection" and I'm pretty sure it's related to it, but I have no clue how to go further, neither do I know what to do not to rewrite the same code in different places.
Not necessarily. It is also used for testing. If you don't have an interface you can't provide a custom implementation for your testing purposes. Another concern might be the "code to interfaces not implementations" paradigm. Let me illustrate:
Suppose you have an ArrayList of Strings:
ArrayList<String> list = new ArrayList<String>();
You use this in your code but later you later find out that you'll need a LinkedList because it is more efficient for your problem.
What happens now? You have to refactor your code in many places.
However if you've used the List interface in the first place you could've passed it around without caring about the implementation of it so if you later find out that you need a LinkedList instead of an ArrayList you just have to modify in a single place:
List<String> list = new LinkedList<String>();
If you need cross-class methods you can create an abstract class and provide a default implementation for a method defined in your interface. It will be shared in all your implementing classes in case you don't override it.
With java 7, you would have to use an abstract class to provide a default implementation for a method. There is no way to define some behaviours of your object in an interface.
With java 8 you would be able to provide a default implementation for a method in an interface.
You are looking for abstract classes and inheritance.
More info on inheritance and using the super keyword here:
http://docs.oracle.com/javase/tutorial/java/IandI/super.html
If you wish to ensure that classes have certain methods that already have implementations, then you want to be using an Abstract Class.
An Interface is simply a contract, that stipulates when a class agrees to implement that interface, it MUST provide an implementation for those methods. This is useful when you want to encourage loose coupling in your code, by having objects refer to your class via an interface, rather than via the object's direct methods.
An interface is useful (speaking from practical experience) where you want to specify that a certain variable/parameter should conform to the contract some other posters mention, and nothing extra. E.g. you have a resource that gets injected (say a data source) but you don't want to specify yet whether it should be a connection to a say MySQL DB, a SQL Server DB, or a dummy data source that you are going to use just for testing without affecting live data. So you specify the type as the interface type, and at runtime an instance of the appropriate implementing type gets injected. You could google for some injection (CDI) tutorials if you are interested.
In other cases you would rather want to use a superclass (abstract or not). The correct answer is: it depends, and one would do good to read (and then review) theory and books on Java language fundamentals to be able to make the best choice for your particular circumstances.

When we can have class and method as static? [closed]

It's difficult to tell what is being asked here. This question is ambiguous, vague, incomplete, overly broad, or rhetorical and cannot be reasonably answered in its current form. For help clarifying this question so that it can be reopened, visit the help center.
Closed 10 years ago.
When we can have class and method as static?
Anybody please help me with some example...
When you don't need a class instance to invoke that method. It means that method does not depend on any non-static members of the class
You can make a method static if it doesn't use any non-static members of the class.
You can make a class static if it only contains static members.
If a method doesn't change it's behaviour based on different objects of it's enclosing class. it can be marked static.
Check Math class. all of it's methods are static cause, their behaviour just depends on the argument within methods and those methods don't make any change in the class states.
All the utility/helper methods can be (should be) marked as static. i.e. if their behaviour is same for all objects, why to have different copy for each object, just have one copy and let all objects share same copy.
You should check this also: Why are you not able to declare a class as static in Java?
A static method belongs to the Class and thus not to a specific instance. If you think at programming languages in term of message dispatching we can say procedural programming provides only 1 level of message dispatching as the name of the function correspond to its actual behavior. In Object Oriented Programming we have two level of message dispatching as you also has you have to specify an object plus the signature of a function (method). The same function may behave differently on different object depending on their status (subClass overridden method, etc.). A static method is instead like a global function you can execute where and how you want and always has the same behavior.
You may therefore limit the usage of static methods although there are cases in which they are helpful. In the Singleton pattern (http://it.wikipedia.org/wiki/Singleton) a static method is necessary to retrieve the Singleton's instance (also a private static attribute is necessary to keep track of it).
For those who claim Singleton are evil and you should always use Dependency Injection via Google Guice, also Guice relies on static method for instance to create an injector (http://lowcoupling.wordpress.com/2012/12/05/dependency-injection/).
So I guess the best answer is you should always think if the problem you are facing might just be solved by the injection of object but there are cases in which the usage of static methods is pretty reasonable.

Singleton v/s class with static members & methods in Java [duplicate]

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)

Why not singleton instance provided out of box in java? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
You can make class singleton by implementing Singleton pattern. Nowadays singleton class is basic requirement.
Why don't JVM handles Singleton object creation by itself at runtime?
By having marker interface like "Singleton" and creating object instance once by JVM at runtime. Anyways Java compiler adds "extends Object" if Class is not extending any other class. Similar approach can be applied in Singleton case.
This will save lot of time and development effort and discussions around various implementations of Singleton pattern.
1) Synchronized getInstance()
2) Synchronized block inside getInstance() instead of making whole method synchronized
3) Option 2 with singleInstance as volatile member
This will also save lot of time and duplicate efforts if you need to implement singleton pattern in multiple classes(not considering SingletonPatternFactory class which will return singleton instance of any class which is been passed)
Let's take a look at all of the steps needed to create a singleton:
private constructor
a static final field
(optional) if you want the class to be serializable, trivial implementations of readResolve and writeObject
Most singletons that I've come across don't care about serialization, so that third step isn't needed. This leaves you two really, really easy steps.
public class Whatever extends WhateverElse {
public static final Whatever INSTANCE = new Whatever();
private Whatever() {}
}
It's even lazy-loaded, since the constructor won't be run until you access the class, which would only be to get the singleton instance of it. I don't know what your definition of "a lot" is as far as time and development effort, but I don't consider this to be onerous.
Implementing basic design patterns is not the responsibility of the core language, unless there is a compelling reason it should be. Design patterns come and go -- for example, the singleton pattern is widely regarded as an extremely bad pattern that should never be used. Even if you decide to use it anyway, do you want an eager singleton? Lazy singleton? What should happen if instantiation fails for some reason? There's a whole lot of seemingly minor issues to cover, but adding this feature to the language is not a trivial change.
By implementing it yourself you get exactly the features and behavior you want.
You can use an enum instead of a singleton pattern - this is not very complex:
public enum Singleton {
INSTANCE;
}
There are two basic categories of Singletons, those with lazy initialization and those with eager initialization.
Aside from the whole argument on flavors of Singletons, many Java developers consider Singletons to be bad or an anti-pattern. This is probably an area of disagreement among those currently maintaining the Java spec.
Lastly, the same could be said true of most any pattern. There is not a huge need for a language to adopt or endorse any specific set of patterns, IMHO.
You would not want a Singleton interface, since the interface has no behavior of its own. You would want an abstract class... kind of. In reality you would want something a lot more powerful than just an abstract parent. You need to have a private constructor (or a private instantiation method that calls a private constructor and returns the single instance) that has to be called in the getInstance() method defined in the parent (violation of scoping).
What you are suggesting is something that will work outside of the traditional class system. Perhaps it can be done as a new object type (similar to how an enum is not a class), but definitely not as a standard interface or class.

Categories