I'm writing a chess game in Java have set it up with a Board class that has a 2d array of Square objects. Each square has a height and width (between 0 and 7 inclusive). I'm going to write a method that takes in a square object, a vertical offset, and a horizontal offset.
Ex: If I call getNearbySquare(mySquare, 3, 2), it should return the square object in my Board that is 3 above mysquare and 2 to the right of mySquare.
I originally wrote this as an instance method in the Square class and it just took in a vertical and horizontal offset. The problem is, I was creating and then returning a new square object, not the correct one from my 2d array in my Board class.
I see two options:
1) Make an instance method in Square class that takes in a Board object, vertical offset, and horizontal offset. I'll find the current height and width of the square object that calls this method, add the vertical and horizontal offsets to get the new location in the Board of the desired square, and then access it using Board[newHeight][newWidth].
2) Make an instance method in Board class does the same thing but doesn't require me to pass in the Board object as in 1). Instead, I'll need to pass in the square object.
Is there a generally accepted practice as far as making these decisions goes?
Thanks for the help, Mariogs
From a very simple view-point it makes more sense for the getNearbySquare()
method to be an instance method for the Board
rather than from the squares because the method will require intimate information about the layout and population of the board, which will be easier to do (and keep encapsulated/loosely coupled) from within the Board
instance.
Having the method on a Square
instance means giving the square objects access to information about the board that should probably be private.
Related Reading;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments