I've been reading two articles (1)(2) on javaworld.com about how all class fields should be private and getter/setter methods are just as bad. An object should act on the data it has rather than allowing access to it.
I'm currently working on a University assignment for Connect Four. In designing the program the Agents playing the Game need access to the Board's state (so they can decide what to move). They also need to pass this move to the Game so it can validate it as a legal move. And during deciding what to move pieces are grouped into Threats with a start and end Points.
Board, Threat and Point objects don't really do anything. They are just there to store related data that can be accessed in a human readable way.
At the start of design I was representing Points on the board as two element int arrays, however that got annoying when creating points or referencing components of them.
So, the class:
public class Point {
public int x;
public int y;
public Point(int x, int y){
this.x = x;
this.y = y;
}
}
Perfect in every way I can think of. Except it breaks every rule I've learned. Have I sinned?
This is one advantage that c# has over Java. YOu can declare a class that has public fields and later on change your mind use a hidden field with getter and setter; but the callers syntax is the same
becomes
but the caller always does
If you know the interface won't change, it's perfectly legal to have the variable public. The problem is as the programs get more complex you would need to change the access to the field, but modern IDEs make refactoring easy, so I would say go ahead.
Public fields break the rule of encapsulation i.e protection of the data. Yes, they do hold data but by having your instance variable PUBLIC it can be accessed by any class out there in your workspace. Instance variables can be protected as well as private.Your getter and setter methods are used just so you can modify the data that your class's instance variables hold. Usually your setter methods would have some kind of validation which is why we have to protect the instance variables of corrupt data (by marking them private or protected)
In the example above you have a constructor,which is initializing your inst. variable, but the chances are that you, as the developer of this class, has the rights and know what to data to insert in order to keep the integrity of your class. Someone else working on your class might not be aware of that and might access your variables by breaking the encapsulation and your program as a whole.
Consider x=-10; when x can only be from 0 to 100 (for example). I would recommend sticking to the encapsulation principles. Hope this helps!