What are the benefits of using accessors/mutators?
There are many:
Hiding state behind getters and setters gives you more flexibility to change the internal representation of the class state without breaking other classes that uses the state.
Getters and setters allow the class to do things when the state is accessed or mutated. For instance, setters can validate prior to setting, trigger events and so on. Getters can return copies of array or collection attributes to avoid exposing the classes state to the possibility of accidental (or deliberate / malicious - see below) change.
Getters and setters can be synchronized.
Getters and setters (if implemented according to the "java bean" rules) enable all sorts of object "wiring" frameworks.
And the downsides of getters and setters are minimal:
Any half-decent Java IDE can generate a getter / setter pair for an attribute in a couple of keystrokes. And if you let your IDE generate your getters and setters, they won't be buggy either.
While getters and setters make your source code files bigger, you normally don't need to pay any attention to them when you are reading the code. An IDE helps here too.
At runtime, simple getters and setters will be inlined so that the performance is indistinguishable from directly reading or writing a public attribute.
[My parenthetical point about "deliberate / malicious" changes to exposed arrays and collections only applies when your code may be called by untrusted code in a security sandbox. As commenters pointed out, the state of private
attributes is not securely hidden ... unless you can also prevent any untrusted code from using reflection. However, if you are in that situation, my point about only returning copies can be security critical.]
I have a board, that consists of tiles. I have made a Board
class and Tile
class. A board object consists of a multidimensional array of tiles. Should the mutator for tiles in the board class set the array, or each individual tile within the array by taking two extra arguments for coordinates? What is better programming form?
Without more detail, I'd say that the Board
class should have methods:
public void setTileAt(Tile tile, int x, int y) {...}
public Tile getTileAt(int x, int y) {...}
and you probably should not have methods:
public void setTiles(Tile[][] tiles {...}
public Tile[][] getTiles() {...}
because they are (most likely) exposing the internals of the Board
class to parts of your application that (ideally) shouldn't need to know about them.
Depending on the details of your application, it may be appropriate to use som kind of Point
class instead of a pair (vector) of integer board coordinates.
Obviously though, if you were trying to implement a game playing algorithm that entailed examining huge numbers of game states to figure out the "best" move, you might want to compromise in the name of performance. But this kind of "micro-optimization" is usually a bad idea.