When does it make sense to use a public field?

后端 未结 8 1331
时光说笑
时光说笑 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:17

    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:

    1. The public final field will make it abundantly clear the class is immutable, with a getter, you have to trust the documentation comment. (Do note that the absence of a setter does not imply immutability, because some other method might assign the field)
    2. Code accessing the vector would be slightly less readable, as get() confers no meaningful semantic information, but still has to be skipped over when reading the code (at least in Java, C# is better here).
    3. This being an extremely low level class frequent use is possible, and invocation overhead might become an issue. Yes, the virtual machine can perform inlining in many cases, but at least for non-final methods, some overhead is likely to remain even if no subclasses are currently loaded.

提交回复
热议问题