Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better to extend a class or modify it directly?

Tags:

java

extend

class

So I'm working on creating a visualization for a data structure in Java. I already have the implementation of the data structure (Binary Search Tree) to start with, but I need to add some additional functionality to the included node class. As far as conventions and best practices are concerned, should I create a subclass of the node with this added functionality or should I just modify what I have and document it there?

My question is similar to what's asked here but that's a little over my head.

I know it probably doesn't matter much for what I'm doing, so I'm asking this more as a general thing.

Edit: I probably should have been more clear. My modifications don't actually change the original implementation other than to add a couple of extra fields (x and y coords plus a boolean to set whether that node is highlighted) and functions to access/modify those fields. Also the node class I'm working with is included in the BST implementation

From reading your answers it seems like there's arguments to be made for either case. I agree that creating a separate class or interface is probably the best thing to do in general. Creating another class seems like it could get tricky since you'd still need a way to extract the data out of the node. The BST implementation I'm using is generic and doesn't have any such functionality by itself in the Node class or the BST class to just return the data so at minimum I have to add that.

Thanks for the informative replies.

like image 318
primehunter326 Avatar asked Dec 01 '22 05:12

primehunter326


1 Answers

The question to answer is, is the 'base functionality' useful, even disirable, when you're not visualizing the data structure?

You might not even want to extend the class at all. Without more detail, it seems to me that you have a datastructure that works. You could create a NEW class that knows how to vizualise it.

That is, instead of a datastructure than knows how to visualize itself, you have a datastructure, and another class that knows how to visualize the datastructure. Heck - you may find that that evolves into another whole class hierarchy because you might need to visualize queues, stacks, etc. etc. NOTHING to do wiht your binary search tree.

like image 57
n8wrl Avatar answered Dec 05 '22 09:12

n8wrl