I’m making a chess game, and I have a base ‘piece’ interface that I want all the pieces to implement. I have some common variables that each need to have, but I don’t want to make getters and setters in each class (seems like it goes against DRY anyway).
What I’ve done is called my interface PieceBase, have a concrete class called Piece, and I have my actual pieces extent from Piece and implement PieceBase. I don’t want Piece to ever be instantiated though, because it doesn’t make sense by itself, and something about this method makes me uneasy.
How is this normally done?
Specifically, this is in Java, but I don’t know if it’s different in any other OO language.
It’s generally considered bad practice, at least in Java and C++, to use inheritance for the purpose of code reuse (see Joshua Bloch’s “Effective Java” for arguments). It’s typically better to use composition (or some other form of delegation) instead.
In your case I’d turn things around entirely, such that
Pieceis afinal classsimply taking anenumrepresenting the type of piece it is:So all of the logic common across all pieces is implemented once in
Piece, and the differing portions are encapsulated by theType. And if you ever need to know what kind of piece you’re looking at, you don’t need to useinstanceofand cast or anything, you just implementPiece.getType()andswitchon that.