user1527491
user1527491

Reputation: 965

MVC : Should this function be in the Controller or in the Model

I want to make a simple game relying on the MVC pattern. The game is a grid on which the player is able to swap neighbors cells.

My question is :

Should I check that the cells are neighbors in the Controller or in the Model ?

I would say that I should have a swapCells(cell1, cell2) function in the Model and that the Controller should check whether the two cells are neighbors (because the ability to swap neighbors cells sounds in my head like a permission more than something related to data). Yet I can't be sure of it.

Thank you.

Upvotes: 1

Views: 97

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726849

Checking that a user action is valid should be done in the controller, so if you are to implement swapCells(cell1, cell2) the check for the two cells being neighbors should be in the controller.

However, in this situation the validation of neighboring cells can be avoided altogether: rather than passing two cells to the model, pass one cell, and a direction to its neighbor:

enum DirectionToNeighbor {
    NORTH, EAST, SOUTH, WEST
}
...
swapCells(originCell, directionToNeighbor)

Now the controller does not need to check if the two cells are neighbors, because the second cell is specified implicitly. All it needs to check is that the origin cell is not on the border on the side of directionToNeighbor (i.e. if directionToNeighbor is NORTH, the cell must not be on the northern border; if the direction is WEST, it must not be on the western border, and so on).

Upvotes: 1

Related Questions