Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Which is the better approach

 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi,

I am writing a generic utility class. I have two approaches and wanted to know which is the best

Approach 1:



Client code to call util methods:



Approach 2:



Client code to call util methods:



If i use Approach 2 i cannot restrict client from calling Util util = new Util(); util.perform();

What are the implications of each approach?

Thanks,
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You just have to add a private constructor to the second approach.

As for the restrictions of approach two: You will never be able to change your implementation to use multiple instances, but since this is a Utility class, this should be okay.
 
Saathvik Reddy
Ranch Hand
Posts: 228
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Should i make the utility class Util as final?
 
David Newton
Author
Rancher
Posts: 12617
IntelliJ IDE Ruby
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Srikanth Reddy wrote:Should i make the utility class Util as final?

"Should" you? I don't know--do you want it extensible?
 
Sebastian Janisch
Ranch Hand
Posts: 1183
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
If you are worried that the extending class could take the no-instance thing away, no worries... If your constructor is private it will never be possible to instantiate the class, even if another class extends it (well, using reflections,but that's a different story)...
 
Rob Spoor
Sheriff
Pie
Posts: 20532
54
Chrome Eclipse IDE Java Windows
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But yeah, you should make your class final to make it even clearer you can't extend it. Utility classes like this are in general final.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic