Home:ALL Converter>replace conditional to polymorphism when using typescript model class

replace conditional to polymorphism when using typescript model class

Ask Time:2019-05-29T21:16:11         Author:Eddie

Json Formatter

I have built a game of life simulation and now I am trying to clean the code and make it more Object Orientated. Despite several days of search, I am having a hard time replacing conditionals with polymorphism.

So I have a component.ts a game model and a cell model. The cell model contains property status: boolean amongst other things. which can be dead or alive. Then I have given the user the ability to toggle a cell status on start. So I have tried for the status to create an abstract class and then two subclasses with dead or alive but I am not sure if that is the right way to go.

this is the cell.model

import { Coordinates } from './coordinates.model';

export class Cell {
  private coordinates: Coordinates;
  public status: string;


  constructor(coordinates) {
    this.coordinates = coordinates;
    this.status = new Alive().status;
  }

  getCoordinates(): Coordinates {
    return this.coordinates;
  }

  toggleCell(): void {
    console.log(this.status)
  }

}

export abstract class Status {
  status: string;
  abstract setStatus(): string;
}

export class Alive extends Status {
  status = 'alive';
  setStatus(): string {
    return this.status = 'dead';
  }
}

export class Dead extends Status {
  status = 'dead';
  setStatus(): string {
    return this.status = 'alive';
  }
}

In the game model as u can see below, I used conditionals to change the status

toggleCell(cellIndex: number) {
  const cell: Cell = this.cells[cellIndex];
  // if (this.cells[cellIndex].status === 'dead') {
  //     this.cells[cellIndex].status = 'alive';
  //     this.addToLivingCells(cellIndex);

  // } else {
  //     this.cells[cellIndex].status = 'dead';
  //     this.removeFromLivingCells(cellIndex);
  // }

  cell.toggleCell()
}

so what I want to do is remove the conditionals and use polymorphism to toggle the status from the dead to alive and back depending on the current status.

Let me know if the rest of the code is needed.

Thanks in advance

Author:Eddie,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/56361552/replace-conditional-to-polymorphism-when-using-typescript-model-class
Paweł Wollny :

I think your approuch is too much complicated for such a simple case. For this case this code is enough: \n\nexport class Cell {\n private coordinates: Coordinates;\n public status: 'alive' | 'dead';\n\n constructor(coordinates) {\n this.coordinates = coordinates;\n this.status = 'alive';\n }\n\n getCoordinates(): Coordinates {\n return this.coordinates;\n }\n\n toggleCell(): void {\n this.status = this.status === 'alive' ? 'dead' : 'alive';\n console.log(this.status);\n }\n}\n",
2019-05-29T13:51:04
yy