Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does pure composition break OOP concepts?

class Room{
  public:
    void ColorRoom(){};
};

class House{
  public:
    Room* GetRoom(){return &m_room;}
  private:
    Room m_room;
};

1) Room cannot exist without a house, an house "has a" room. (composition)
2) Another way to color room would be to have a method in House that would invoke the ColorRoom in Room method but then this is more of delegation. (i want to avoid this)

The only way I see is the one above but looks like returning reference to private member is breaking OOP. Is this a good design ?

like image 570
Frank Q. Avatar asked Jan 26 '10 18:01

Frank Q.


2 Answers

The thing is that you're not explicitly exposing your private member. Your API just shows a method to get a room, and the consumer doesn't know if House is creating that room, returning something held in a private field, or getting the room from a web service. That's solid OO.

like image 106
Jay Avatar answered Oct 15 '22 07:10

Jay


Overall, you're good, since House creates member variable m_room by itself -- it does not require a consumer to call something after instantiation. This follows the pattern that an item is usable immediately after instantiation (it does not require special actions like setting a room or whatever).

I do have some minor nit-pickings:

class Room
{
public:
    // virtual method to allow overriding
    virtual void ColorRoom(){};
};

class House
{
public:
    // Returning a non-const pointer in C++ is typically a bad smell.
    const Room& Room() const { return m_room; }
    // Allow for assignment and manipulating room, but breaks const-ness
    Room& Room() { return m_room; }
    // Facade method for houses with more than one room
    // You can forward parameters or come up with room-painting schemes, but you should
    // not require that a House has a Room called Room().
    virtual void ColorAllRooms()
    {
        m_room.ColorRoom();
    }
private:
    Room m_room;
};
like image 36
Travis Gockel Avatar answered Oct 15 '22 08:10

Travis Gockel