aspose file tools*
The moose likes Java in General and the fly likes class without instance variable as singleton Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of EJB 3 in Action this week in the EJB and other Java EE Technologies forum!
JavaRanch » Java Forums » Java » Java in General
Bookmark "class without instance variable as singleton" Watch "class without instance variable as singleton" New topic
Author

class without instance variable as singleton

Gagandeep-Aryan Malhotra
Greenhorn

Joined: May 29, 2012
Posts: 4
Suppose if a class is not having any instance variable and is getting invoked very frequently then is it a good practice to make it a singleton class.
Darryl Burke
Bartender

Joined: May 03, 2008
Posts: 4522
    
    5

Gagandeep-Aryan Malhotra wrote:Suppose if a class is not having any instance variable and is getting invoked very frequently...

Classes are instantiated. Methods are invoked.

You need to clarify exactly what you're referring to, preferably with a short code in the form of an SSCCE.
Martin Vajsar
Sheriff

Joined: Aug 22, 2010
Posts: 3433
    
  47

I don't think so.

Firstly, singletons are can be bad. There are a few threads here on the Ranch discussing this, you might try to find them out.

Secondly, singleton can achieve two things: share one object's state among many users, and reduce overhead of costly object creation. A class with no instance variables does not have a state to share, and at the same time it is not costly at all to create objects of such class.

And lastly, but probably most importantly: class with no instance variables does not have to be instantiated at all - simply declare all its methods static.
Anayonkar Shivalkar
Bartender

Joined: Dec 08, 2010
Posts: 1456
    
    5

Hello Gagandeep-Aryan Malhotra,

Welcome to CodeRanch!
Suppose if a class is not having any instance variable

Any specific reason for having class like this?
is getting invoked very frequently

Well, technically, you don't invoke a class, but instantiate a class (i.e. make an object) and invoke methods on it.
is it a good practice to make it a singleton class

Again, making a class to singleton class has its own overheads, and should not be done unless absolutely necessary. Do you really need it? Will two or more instance of that class will create any problem?

I hope this helps.


Regards,
Anayonkar Shivalkar (SCJP, SCWCD, OCMJD, OCEEJBD)
Campbell Ritchie
Sheriff

Joined: Oct 13, 2005
Posts: 36465
    
  15
If a class has no instance fields, why instantiate it at all? Why not treat it as a utility class, with only a private constructor and all static members?
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: class without instance variable as singleton
 
Similar Threads
Singleton
private & static
Static variables problem
Singleton Class ?
Singleton Class