Prasham
Prasham

Reputation: 6686

Java: Extending a class instead of performing same logic in too many classes. Pros and Cons?

There is a logic and properties used to create certain object. That logic is going to repeated in several classes. Like some template logic. e.g. suppose I am creating a template to create enums like objects, which basically requires setting an int in constructor and getting value through method.

There are two ways to do this

  1. Create a template superclass which has both of these logics, and extending it whenever we need to create an enum like object.

  2. Create and re write both the logics every where.

Keeping memory and performance of code in mind which option is preferable. What are the pros and cons for it?

Upvotes: 1

Views: 205

Answers (2)

aioobe
aioobe

Reputation: 421180

As always memory consumption and performance are secondary to readability and maintainability.

If I were you, I would sit down and think about where the logic belongs logically, and put it there. You could for instance ask yourself, Which solution would be easiest for me to defend for someone reading my code for the first time?

If the logic sort of spans across all subclasses (i.e. if you can't extend the class without dealing with this logic) put it in the super class.

If the logic is truly specific to all subclasses, then put it in the subclasses.

If you go for the later, consider writing it in a way such that you can enforce the logic to be implemented through abstract methods in the super class.


(BTW, your question, and the enum-tag isn't really clear. You can't instantiate enums in runtime in Java.)

Upvotes: 4

Joe
Joe

Reputation: 47709

This feels like the territory of the Single Responsibility principle. What you are saying seems to suggest you should pull out the functionality into another class and compose it into the respective objects (i.e each object has one of the 'helper' object, or maybe all reference the same helper object). Extending isn't the only way of re-using code!

Upvotes: 1

Related Questions