|
|
|
|
|
by brunoborges
122 days ago
|
|
In many cases, yes, public fields are fine. But there are limitations: - Can't synchronize access. `synchronized` keyword is not applicable to fields, only to methods and code blocks. - Can't proxy. Not possible in public fields, therefore can't intercept calls before state is changed. This is useful for example in mocking frameworks, and telemetry libraries. - Can't evolve. Methods allow encapsulation, which allows evolution of the implementation detail. For code base where the public field is accessible by consumers only within the same code base, this may be fine. But for shared libraries, it can easily become a problem. |
|
1. Synchronizing on trivial properties (otherwise you couldn't use `public` anyway!) is an anti-pattern, as it's a too fine-grained unit of concurrency and invites race conditions.
2. Can't proxy without rewriting byte code, you mean.
3. Of course you can evolve, it's just a breaking ABI change so it requires a trivial code migration on the side of the callee. If the cost of that migration is too high, something else is wrong.