Component and Service type beans and most of the other bean types are by default singleton.
In one of my code Pull requests, I declared a method as static in a Component as the method wasn't modifying any class level variables.
My code reviewer pointed out that since the class is anyways a Singleton and is going to have a single reference, he said it was unnecessary to make the method static, but rather make it a instance method.
Which way is the correct way of writing code as most of the classes in my application are Singletons?
Your reviewer is probably right about this one, it makes little sense to declare a static method inside a singleton; unless this static method is a factory method that returns the singleton instance itself.
I could think of two other reasons not to declare static methods in the singleton : testing is harder for static methods in some cases and you will really confuse the caller of this singleton. He/she might see that there is a static method and have a hard time understanding why it was declared like this, it would require extra reasoning as far as I see for such a method.
Related
I'm wondering what different between static method and singleton class method when i use them for multiple thread. I think if use static method, it will conflict result data or parameter but i don't think use singleton method class then the same problem will occur.
We use "synchronized" to solve the multiple threads problem.
The static method and singleton method's main differences are:
1. a static method can only use the static fields and methods, as a non-static method can use all fields and methods of the class.
2. a static method can be called without a instance, as a non-static method must be called by a instance.
When you create a static method it can be used without creating an instance of the class, which is not true when you're creating a class-method.
Synchronization is orthogonal issue: you'll probably have to use some kind of synchronization mechanism regardless of which one of the two options you chose to use.
So, I'm beginning to learn Java and I think it's an awesome programming language, however I've come across the static keyword which, to my understanding, makes sure a given method or member variable is accessible through the class (e.g. MyClass.main()) rather than solely through the object (MyObject.main()). My question is, is it possible to make certain methods only accessible through the class and not through the object, so that MyClass.main() would work, however MyObject.main() would not? Whilst I'm not trying to achieve anything with this, I'd just like to know out of curiosity.
In my research I couldn't find this question being asked anywhere else, but if it is elsewhere I'd love to be pointed to it!
Forgive me if it's simple, however I've been thinking on this for a while and getting nowhere.
Thanks!
Any static method or member belongs to the class, whereas non-static members belong to the object.
Calling a static method (or using a static member) by doing myObject.method() is actually exactly the same as MyClass.method() and any proper IDE will give a suggestion to change it to the second one, since that one is actually what you are doing regardless of which of the two you use.
Now to answer the actual question:
is it possible to make certain methods only accessible through the class and not through the object
No, not as far as i know, but like I said, any proper IDE will give a warning, since it makes little sense and it gives other readers of the code an instant hint that you're dealing with static members.
Yes, short answer is no.
But you can put your static members in a dedicated class, so that no instances share any one of them.
MyObject is instance of MyClass, and you aggregate all you static parts in MyStaticThing.
Using static member on an instance can be misleading, so it is a bad practice
http://grepcode.com/file/repo1.maven.org/maven2/org.sonarsource.java/java-checks/3.4/org/sonar/l10n/java/rules/squid/S2209.html
While it is possible to access static members
from a class instance, it's bad form, and considered by most to be
misleading because it implies to the readers of your code thatthere's
an instance of the member per class instance.
Another thing, do not use static things, because you cannot do abstraction and replace implementations to extend your code.
Being able to switch between implementations is useful for maintenance and tests.
In Java, you can crete an object with these keywords.(new keyword, newInstance() method, clone() method, factory method and deserialization) And when you create an object,it can also use classes abilities which is like static methods.
Short answer:No.
Is it possible to make certain methods only accessible through the class and not through the object?
Yes, it is. You achieve this by preventing any instances of the class to ever be created, by making the class non-instantiable: declare its constructor private.
public final class NonInstantiable {
private NonInstantiable() {
throw new RuntimeException(
"This class shouldn't be instantiated -- not even through reflection!");
}
/* static methods here... */
}
Now, it only makes sense to declare any methods of the class static -- and they can only be called through the class name. Such a class is often called a utility class.
This is a follow-up question to a previous question.
From what I understand, one #Controller-annotated class with #RequestMapping-annotated methods cannot successfully inherit from another because Spring can't recognize they're both mapping to the same method(s). Even if Spring recognized they were the same instance, it would have no way to decide which instance of the two controller beans to use to invoke the method.
But static methods are invoked independent of any instances of a class, and child classes do not carry their own copy of the parent's static members. Making all of my #RequestMapping-annotated methods static (at least on the parent class) could resolve this problem, which brings us to my question:
Can a public static method be used with #Controller on the class and #RequestMapping on the method? And would it behave about the same as a non-static method*?
* I know that a static method naturally can't access instance members, but controllers should typically be implemented in such a way that there aren't any instance variables anyway. All the methods I'm dealing with would work exactly the same if they were static methods, provided the framework allows for it.
It works fine for me in Spring 3.2.X. Though, controllers often have data members on their instances, but they're usually autowired instances that are services. So I wonder if you're misunderstanding the overall design pattern of the Spring framework.
I can't think of any real benefit in using a static method, the controller instance is already there, so even if you made the controller have all static methods it's still going to get instantiated. I would think the instance invocation overhead would be minuscule and lost in the noise as far as performance.
I have a helper class that creates some objects, like a builder. The helper class does not have a state. It is on a multi-threaded environment; specifically, a web server. Is this class a good candidate for being a singleton?
What would be the difference between implementing this class as a singleton and just using static methods?
What would the effect of thousands of users accessing this object/these methods be?
I could make the class a regular class, but instantiating it every time it is needed would be a waste of memory.
Infact instead of singleton you can make the methods static.
Singleton doesn't have to be only 1, you can create a pool of instances and delegate work depending on the requirement, where as you don't have such control with static methods.
discussion on Singleton vs Static methods is here
As the name suggests, singletons are used to have only one instance of the object present at the time. So singleton does have a state, but you're accessing to that one state wherever you're calling your singleton.
So if you don't need any state saved in your class/method I'd suggest to use static approach.
No need to use singleton here (since you do not need a state), you can use static methods.
Singleton in principle offers more control by allowing a state. There won't be much difference in your case, but static methods will be easier to implement and use.
What would the effect of thousands of users accessing this object/these methods be?
Again, not much difference in both cases, but in Singleton you can have a state, and if you do not implement carefully, your code will be non-thread-safe. Every user calling the static method gets its own "instance" of the method (I think this is what you ask), so no risk of running into thread-safety problems there.
As has been stated before, given that your class doesn't have object state, static methods would work just fine.
However, consider the following - Depending on the overall design of your system, you may want to be able to specify a different implementation of the methods. This is usually done with either subclassing (...), or interface implementation (now the preferred method) - look up the strategy pattern. In either case, being able to provide alternte implementations would require you to not use static methods, but to have an (empty) object to call methods on.
Is there any difference between a Singleton class and a class with
all static members (i.e. methods and attributes).
I could not find any instance where 'all static member class' would not achieve
the same functionality as class properly implementing Singleton pattern?
For eg. java.lang.Runtime is a proper Singleton class whereas java.lang.System has all static method for access and merely has a private constructor to avoid external construction . Does anybody know why classes like Runtime are made Singleton and not implemented like java.lang.System.
Is it merely because it would be a cleaner design (i.e. mimics an object more realistically) or is there some performance benefit here?
Yes, there's a difference - a singleton can implement an interface.
Also, what looks like a singleton from the outside can actually be implemented via different classes, where the singleton access method (e.g. Runtime.getRuntime()) can create the right instance at execution time. I'm not saying that's what's happened here, but it's an option.
Well you can serialize and unserialize an object (and thus a Singleton) using the Serializable interface (on Java), but not a static class.
A singleton is instantiated once.
A static class is never instantiated.
I believe there is no difference between what you call a singleton and a class with all static methods/members in principle. In fact, I think that creating a class with all static members is a way of implementing the singleton idiom. Well, maybe in Java there is some kind of serious difference, but I'm speaking from the C++ point of view.
I think you should ask what's different between final class with private constructor and static class.
Because singleton is a class and implementation depends on programmer who programs this class.
It's same as ask what's differences between an object and static class.
A class can be extended to create another singleton (e.g. for testing purposes), or non-singleton class. static methods cannot be overidden, they can only be hidden in a sub class.
A common use for singletons with lazy initialization (aka Meyers singletons) is to control the order of static objects initialization (which, in C++, is undefined across different translation units). In this respect, singletons just behave like global objects, but whose order of construction behaves well.
It becomes quite difficult to control the order of destruction though. If you must rely on the singletons being destructed in some particular order (eg. a singleton logging class which should outlast other singleton instances), see Alexandrescu's book to witness the difficulty.
The primary purpose for singletons cited by the GoF is to provide a polymorphic service, where the singleton is an abstract base class, and the concrete type is decided at runtime. And, of course, there must only be one of them in the program.