views:

304

answers:

1

I would like to keep this one short. I build a HouseA that has two rooms, say BedRoom and StudyRoom, both deriving from a base class called Room. BedRoom and StudyRoom have a same parent called House. Also, any room in a house can access any other rooms only through the parent. If BedRoom has to access any attribute of StudyRoom, it has to go only via House (i.e. parent) and vice-versa.

HouseA ISA House
HouseA HAS BedRoom and StudyRoom.
BedRoom ISA Room
StudyRoom ISA Room

Now the Problem: Let's say, I build another home (say HouseB), which is a exactly the same as the above, but with one change. I don't want two separate rooms (i.e. BedRoom and StudyRoom), but instead a single room (MasterRoom) which has both these facilities. For the sake of code reusability, I could think of the following design options:

Option-1:
HouseB ISA House
HouseB HAS MasterRoom
MasterRoom ISA Room

Here I lose the ability to reuse the attributes of BedRoom and StudyRoom that I created for HouseA. Note that most of the attributes of BedRoom and StudyRoom need to be reimplemented in MasterRoom anyway, thereby resulting in code duplication.

Option-2:
HouseB ISA House
HouseB HAS MasterRoom
MasterRoom ISA Room
MasterRoom HAS LogicalBedroom
MasterRoom HAS LogicalStudyRoom
LogicalBedroom ISA BedRoom
LogicalStudyRoom ISA StudyRoom

This way, I use composition so that I could reuse most of my code (I have several thousand lines of code that I could reuse), but the problem is that BedRoom is a concrete class and logicalBedRoom may find certain attributes not suitable and may be forced to override methods so that they do nothing. For example, Bedroom->noOfSides() = 4 and logicalBedRoom->noOfSides() = ??. Is this a good use of inheritance?

My actual design is for a complex chip that combines the functionality of two individual chips (I used House (motherboard) and Room (chip) analogy). I code in Object Oriented Perl and I would really appreciate any alternate design suggestions.

Thanks

+16  A: 

Why not use roles to achieve this:

House A has a Bedroom
Bedroom does SleepingArea
House has a Studyroom
Studyroom does ComfyArea

House B has a MasterRoom
MasterRoom does SleepingArea and ComfyArea

The easiest way to get roles is to use Moose.

daotoad