Best Practices When Using Abstract Classes

Viewed 54

I'm building a Chess application with HTML, CSS, and Javascript and was curious about a few best practices when building JS abstract classes. Because I am building a Chess Application, I have a class Piece (with a few common getter/setter methods), and other classes like Knight, Pawn, Queen, which extend off the Piece class. For example, I have an abstract method called 'isLegalMove(tile)', which evaluates whether the piece can move to the specified tile. Though all pieces have different rules, hence the method being abstract, they also have some common rules, like they can't go off the board, or black pieces can only go on blacks turn.

The question I have is in the abstract method 'isLegalMove(tile)', is it best practice to evaluate both common and unique conditions as seen below

//Queen.js
isLegalMove(tile) {
    if (this.getBoard().getTurn() != this.getColor() || tile.getRow() > 8 || tile.getRow() < 1 || tile.getCol() > 8 || tile.getCol() < 1) { // common illegal conditions
        return false;
    }
    if (isPieceBetween(this.getTile(), tile)) { // unique illegal condition for a queen
        return false;
    }
    return true;
}

or, build a non-abstract method such as 'commonConditions(tile)', which evaluates all common conditions and run it in all 'isLegalMove(tile)' methods so I can remove redundancy within different files, as seen below

//Piece.js
commonConditions(tile) {
    if (this.getBoard().getTurn() != this.getColor() || tile.getRow() > 8 || tile.getRow() < 1 || tile.getCol() > 8 || tile.getCol() < 1) { // common illegal conditions
        return false;
    }
    return true;
}
//Queen.js
isLegalMove(tile) {
    if (commonConditions(tile) === false) {
        return false;
    }
    if (isPieceBetween(this.getTile(), tile)) { // unique illegal condition for a queen
        return false;
    }
    return true;
}

This may be a silly question that comes down to preference or how redundant those common conditions are, however it's best I know if that's the case.

0 Answers
Related