Win a copy of Think Java: How to Think Like a Computer Scientist this week in the Java in General forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

class without instance variable as singleton

 
Gagandeep-Aryan Malhotra
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 5126
11
Java Netbeans IDE Opera
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 3752
62
Chrome Netbeans IDE Oracle
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 1557
5
Eclipse IDE Java Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
 
Campbell Ritchie
Sheriff
Posts: 48917
58
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic