Home > Software engineering >  Is it common to have controller Classes in OOP
Is it common to have controller Classes in OOP

Time:09-10

Im recently switching to a OOP Paradigm. I have burning question around its Architecture. I have searched high and low online and have only managed to be further confused. For learning purposes I am making a game of monopoly. My architecture is as follows:

export class Monopoly {
  constructor() {
    this.players = new PlayerContoller();
    this.board = new Board();
    this.dice = new Dice();
    this.piece = new Piece(); 
}

Then inside these objects are I instantiate other objects such as Property Utility Station, Square,Chance,Community chest etc.

My question is surrounding the players controller. Is it needed? This is what it contains

import { Player } from "./Player.js";

export class PlayersContoller {
  constructor() {
    this.players = []; 
    this.playerTurn = 0;
 }

 addPlayer(piece) {
    const player = new Player(piece);
    this.players.push(player);  
 }

 getCurrentPlayer() {
    return this.players[this.playerTurn];
 }

 changePlayersTurn() {
   this.playerTurn  ;
   if (this.playerTurn === this.players.length) {// if the player reaches above the number of players its reset to 0
     this.playerTurn = 0;
   }
 }

 getAllPlayersObjects() {
   return this.players;
 }
}

The purpose of it is so that I dont have to store these methods directly in the main Monopoly Class and I also dont have to store the players Array in the main Monopoly Class. Any methods I need to call on the player themselves such as increaseMoney() are stored in a Player Class and these object are stored in the players Array which is a property of the PlayerController Class. The playerController Class is just to control who's turn it is and find the current player so I can call methods on it from the player class e.g. increaseMoney() again, or pass the data into my view ( I'm using the MVC pattern).

Are these controller classes common as to not have a big main class or am I better to store an Array as a property in the Monopoly Class and call methods directly from the Monopoly Class?

CodePudding user response:

I would call that class PlayerCircle (or even Table). The defining feature is not just that it holds an array of players - for which you wouldn't need an extra class -, but that it keeps the state of whose turn it is.

Given this, I'd consider this to be part of the model, not a controller. In classical MVC, the controller is what connects the view with the model, in particular with methods that execute actions on the model. Your PlayersController doesn't do that.

  • Related