2

I have common methods written in different classes, making code duplicate and now to avoid this duplicacy, I am thinking of 2 approaches:

  1. Make static methods in some util class and call them, or
  2. Make a super class and write all these methods in super class and extend each class with this super class.

Definitely, with approach 2, I will loose the ability to extend my class further. So I am thinking to go with approach 1.

Can you please help me in identifying which approach is good and also in suggesting better approach, if you have any?

Arpit Aggarwal
  • 27,626
  • 16
  • 90
  • 108
  • Why would you loose the ability to extend the class further? I recommend the second approach, but it depends on the functionality you are thinking of. – Laurentiu L. May 23 '15 at 10:53
  • If super class is created and extended by other classes (sub-classes), than sub-classes can't extend any other class, correct? – Arpit Aggarwal May 23 '15 at 11:05
  • Correct. But a sub-class of the sub-class can extend the sub-class :) You extend the most important class. For the first approach you can try the factory pattern to keep your method. – Laurentiu L. May 23 '15 at 11:15
  • Please avoid utility classes if possible: http://blogs.msdn.com/b/nickmalik/archive/2005/09/07/462054.aspx – Tom May 23 '15 at 11:42
  • Favor [composition over inheritance](http://stackoverflow.com/questions/49002/). – jaco0646 May 23 '15 at 16:45

1 Answers1

0

Creating Utility packages and/or class is a common solution to this problem. Apache Commons is a prime example. I would favour approach 1

Brett Walker
  • 3,566
  • 1
  • 18
  • 36