Last week, we had the author of TDD for a Shopping Website LiveProject. Friday at 11am Ranch time, Steven Solomon will be hosting a live TDD session just for us. See for the agenda and registration link
My assignment was to create a Dictionary implemented as a Tree. I've created a tree that does everything I need & whatever else I felt it should, and now I started whiting my Dictionary class so that its methods match the methods in the Dictionary Abstract Data Type we were given in class. My problem is really a basic one: Should I let Tree extend Dictionary or have the Dictionary contain an instance of my Tree class? On what do you base this choice? I thought Tree extends Dictionary was good because the Dictionary can clearly do everything specified (with exact method signatures) and then Tree can do that and a whole lot more. Feedback? [ February 22, 2004: Message edited by: Elouise Kivineva ]
You are correct in that Tree should extend the Dictionary class. There are several reasons, but the easiest to see is contained right in your topic subject: a tree is a type of a dictionary. As you said, the Dictionary can clearly do everything specified (with exact method signatures) and then Tree can do that and a whole lot more. It wouldn�t make sense to say a Tree "has a" Dictionary. If it did, how would you call the Dictionary methods from outside the tree? It could be done, but the resulting code would be convoluted. But more importantly, you wouldn't be rewriting similar or duplicate code in the Tree class that you already have in the Dictionary class; it all would be inherited. Tied to this basic "is a" reason, is the second reason why it should extend Tree: polymorphism. If Tree extends Dictionary, it can be used anywhere the Dictionary class is called for. So if you have a method in SomeClass with the following signature:
If Tree extends Dictionary, you can do this:
That�s a very powerful paradigm. Overall, it just makes much more sense for Tree to extend Dictionary then to have one as an instance variable.
Tree extending or implementing dictionary will have another benefit ... maybe you'll learn a faster algorithm for dictionary storage and lookup and want another implementation. Say a ternary tree or some kind of hashmap. Anyone using the Dictionary type will be able to use your new implementations without change.
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi