Search code examples
qtmodel-view-controllerarchitecture

How can I call a function from one controller inside of another controller in MVC?


I am building an app using the MVC architecture. I have a window with some buttons and a graphics scene where rectangles are displayed. When I now click on a button in the window, the rectangles should be hidden. Now the problem is that I have two separate controllers: one for the window and one for the scene. How can I achieve that the scene knows to hide the rectangles when the button is clicked in the window?

Since I'm building my app using Qt I thought of emitting a signal and the other controller could react to that but this does not seem to be a very good solution since I want the controllers to be separate from each other.


Solution

  • Generally speaking you can achieve your goals either via orchestration or via choreography.

    If your controller A directly calls controller B then it is a form of orchestration. controller A acts as an orchestrator in order to achieve the desired outcome it knows who should do what.

    If your controller A emits a signal and controller B reacts on it then it is a form of choreography. controller B knows what to look for and how to react on it. While controller A may or may not know anything about the rest of the components.

    The orchestration concept can be easily extended in the way that the orchestrator is not the controller A itself rather than a third controller. That third controller knows how to communicate with controller A and controller B to achieve the desired outcome while the other two controllers remain totally separate.


    UPDATE #1

    Is this good practice? Or should you design your application in a way that the controllers don't have to interact with each other?

    As always it depends.

    If there are too many interactions between two controllers then they become tight together which makes them hard to test and hard to extend.

    If you combine the two into a single controller then you might end up in a situation where that single has too many responsibilities and will eventually become hard to maintain.

    If the number of interactions kept low and there is no circular referencing (controller B also calls controller A in some cases) then it is a good.

    Having a dedicated orchestrator for a single interaction might be an overkill. But if you know that there will be many then it is a good direction.