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
On projects with non-trivial complexity it is rarely - but sometimes - a good idea to use public fields. One example that comes to mind:
/**
* A two-dimensional mathematical vector. Immutable so instances may be freely shared
* without violating encapsulation.
*/
public class Vec2 {
public final int x, y;
// bunch of constructors and methods omitted
}
Rationale: It is exceedingly unlikely that the internal representation will need to be changed, or any kind of operation be performed when reading x
or y
. That is, using a setter confers no benefit here.
However it would confer some costs: