This week's book giveaways are in the Refactoring and Agile forums.
We're giving away four copies each of Re-engineering Legacy Software and Docker in Action and have the authors on-line!
See this thread and this one for details.
Win a copy of Re-engineering Legacy Software this week in the Refactoring forum
or Docker in Action in the Cloud/Virtualization forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Static methods Vs Instance Methods

 
Santhosh Kumar
Ranch Hand
Posts: 242
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If a class does not have any state (that is, it consists of only methods), what is best design approch to follow?
1. Make the methods static. So that users can directly access the methods which out any objects
2. Still make it as instance methods, user should make an object and invoke the methods
Pl refer any document/url regd this design guidelines.
thank you very much
 
Bosun Bello
Ranch Hand
Posts: 1510
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are saying that there will be no reason to create an instance of this class, then you can just make the methods static.
 
Ilja Preuss
author
Sheriff
Posts: 14112
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Depends.
Static methods aren't polymorphic - they are resolved at compile time by the type of the reference (instead of the type of the referenced object).
Therefore, if you want to use polymorphism, you need to use instance methods - the Strategy design pattern is a good example.
OTOH, if the class provides simple helper methods (like java.lang.Math does), it's probably ok to make the methods static.
Does that help?
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic