zar
zar

Reputation: 12237

Providing interface for objects within objects

I am creating a model as in MVC which is made of other objects. My single main model object contains the constituents object. My question is should I be asking the main model object for all the operations that will actually be carried out by constituents object or should I ask for the constituents objects and run its operations? I can see in the first approach, the main model will have to account for all the operations of its constituents modules and will result in adding many functions which will simply delegate to the constituent objects.

Let me explain with an example which is very close to what I am doing. This code below is on fly so please ignore c++ syntax mistakes if any.

class Arm
{
public:

    Move(int x, int y);
}

class Robot
{
public:
    Arm leftArm;
    Arm rightArm;

    // should this function be there?
    MoveLeftArm(int x, int y)
    {
        leftArm.Move(x,y);
    }

    // and likewise this?
    MoveRightArm(int x, int y)
    {
        rightArm.Move(x,y);
    }
}

// in the view when I want to move robot arms, should I do this
robot->MoveLeftArm(x,y);
//or this
robot.leftArm.Move(x,y);

A dump question but should it depend on how many operations the constituents objects actually support? Also since we are it, is this also an example of facade design pattern?

My concerns:

Please consider the constituents objects are many more than just two robot arms above and it has more methods.

Upvotes: 0

Views: 53

Answers (1)

IonutG
IonutG

Reputation: 51

I think it's usually better to encapsulate data and behavior and let each class maintain it so you don't create strong relationships between them.
So the best would be that the View calls Robot.MoveLeftArm and RobotMoveRightArm and the Robot is the one that would send the message down to the Arms which would execute the actual movement. This way the call and implementation of the arm moving is encapsulated in the Arm and it could change without affecting the View.
There are also options to have interfaces define the behavior and have the classes actually implement that behavior, thus creating a contract between them.

Upvotes: 1

Related Questions