Reputation: 32081
I've got a bunch of related classes, they all implement a certain interface to do the same function in different ways.
About 70% of the code in any one class is unique, and about 30% can be re-used between 2 or more classes. There are about 30 such classes in the set.
I just can't decide what's more logical:
Create a big base class with all the reusable functions in it, or just create a utils class with the common functions in it.
The two approaches appear the same to me, but is there a reason I might favor one over the other?
Upvotes: 1
Views: 958
Reputation: 680
You will need to identify classes with common functionality, Group them and extract an interface out.
Best example to look @ is the way Java Collections have been managed.
You can have 1. Interface Hierarchy 2. Abstract classes shared between common Concrete classes 3. Utility classes
Upvotes: 1
Reputation: 2454
The relationship between a parent class and its child should be quite special, the child "is a" more specialized case of the parent. Would your common functionality fit into this kind of thinking? When you talk about a "big base class", I suspect not, but given the information you've supplied that's just a hunch.
If the helper functionality doesn't fit into this kind of relationship, then I would suggest utility classes.
Bear in mind though it may also be appropriate to mix and match, it all depends on what each method is doing.
Upvotes: 1
Reputation: 34367
The answer is dependent on the nature of your methods. Util
classes/methods are more useful when you want to perform some operation on stateless object values(independent) e.g. getMaxOfArray(int[] array)
. To re-iterate, when you pass certain(limited) arguments to a method and get the expected output from the method then you may consider making that method as Util
class method. This is the reason, normally util methods are created as static
and are not associated with class instances.
If this is the behavior then use the Util
class. But if your methods are heavily dependent on object instances then better to use Class Hierarchy with common methods defined in the base class.
Upvotes: 3
Reputation: 7854
if there is some functionality that can be used independently as a utility, I'd prefer a util class as it is easy to test and can be used wherever required with no side effect, rather than going in heirarchy or composition unless it logically makes sense
Upvotes: 0