When does it make sense to use a public field?

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

    So the best answer I can give is that when you do magic via reflection, as one is wont to do when taking advantage of a statically typed language, properties have meaning over fields. From things like ORM tools, to mappers, and to binding data, properties can have different meaning than fields from that behavioral standpoint.

    The JITter doesn't turn properties into fields, it can inline them, though I won't promise it does in all cases.

    0 讨论(0)
  • 2021-02-18 17:33

    In my opinion, when you design a structure of a class you should pay more attention to future changes and should always be friendly to them. If a future requirement need you to do some logic before returning a value instead of just returnning the value of the field, you'll have to change the interface of the class, and all users of your library will have to change. That usually become a disaster.

    Keep in mind, the open / close principle.

    0 讨论(0)
提交回复
热议问题