When does it make sense to use a public field?

后端 未结 8 1362
时光说笑
时光说笑 2021-02-18 16:52

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         


        
8条回答
  •  失恋的感觉
    2021-02-18 17:06

    Here is the summary of pros and cons of public fields:

    Advantages

    • Less clutter in the code
    • Better performance (in some cases)

    Disadvantages

    • Representation can't be changed without changing the API
    • Invariants can't be enforced (unless the field is immutable)
    • No additional actions can be taken when accessing these fields

    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.

提交回复
热议问题