I'm developing a chess program in Java and considering the following problem:
- The Rook piece requires implementation for moving in straight lines.
- The Bishop piece requires implementation for moving in diagonal lines.
However,
- The Queen piece requires implementation for both of the above movement patterns.
I can't think of a clean solution to modelling this relationship, I have considered some but none of them are both compliant with good object-orientated design and code efficient.
Java doesn't support multiple inheritance, so Queen cannot borrow implementation from Rook and Bishop
If Rook and Bishop extended Queen, I'd need to extract the logic for each kind of movement into separate methods, this would serious bloat my current design for how movement is validated.
Neither of the above solutions seem elegant enough to beat just:
- Putting ALL of the movement implementation into the parent class of all the pieces, this way they all can share all of the common implementation (of which there is quite a bit)
I'm aware solution 3 is in violation of good Java design, but in this case, that design pattern seems to only be forcing bloated, inelegant solutions.
Probably this could be avoided with a complete restructuring of the program, but everything up to this point looks pretty efficient to me, does good OO design always come at the cost of directness of functionality and structure? Is my approach just wrong for the style of the language?
How would you solve this problem?
Copyright Notice:Content Author:「David Wood」,Reproduced 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/32247718/chess-in-java-object-orientation-vs-efficiency