Bad or good idea for inheritance

Started by
1 comment, last by Rycross 14 years, 6 months ago
Hi, I was wondering what your thought was on this case for inheritance. I am making a tetris clone. I have a block class. A block is made up of 4 squares. The block class creates four square class objects everytime a new one is made. Now there is a common set of variables used between both things. Like widths, square medians, etc. Would an inheritance of the block class from the square class be a good idea or should I just pass the values. Regards chad
Advertisement
If block inherits from square, that means "Block is a Square", which means any code that you write to deal with squares MUST also work if you give it a block instead of a square.

If you want to use inheritance in this case, I would make a 3rd class that BOTH block & square inherit from, which contains the data/methods that are common to both classes.
Is a block a square, or does a block have squares? ;)

In general, I'm extremely cautious about using inheritance if the proposed subclass only uses only a subset of the code in the proposed superclass. That would imply to me that extracting a common superclass, or simply using composition, is a better strategy.

Or to put it another way, some common functionality between two classes does not necessarily imply that one should derive from the other.

This topic is closed to new replies.

Advertisement