This is a question I have had for a while now:
When does it make sense to expose a field publicly like so?
public class SomeClass()
{
public int backi
Here is the summary of pros and cons of public fields:
Advantages
Disadvantages
So when should we use public fields? Depends. It is obvious that for public classes disadvantages outweigh the advantages. Possible problems with evolving the code inside the package are far worse than more clutter in the code and minor performance impact.
However, a class can be package private or even private nested, in which case the probable changes to the code will be localized. Therefore it is absolutely possible to use public fields. Also there are cases when performance difference is not so little. For instance, Android Developers guide claims that it is a good practice to use direct field access instead of getters/setters where it is possible because it is several times faster.
To sum up, I will quote one of my favourite books, Effective Java by J. Bloch, Item 14:
In summary, public classes should never expose mutable fields. It is less harmful, though still questionable, for public classes to expose immutable fields. It is, however, sometimes desirable for package-private or private nested classes to expose fields, whether mutable or immutable.