When does it make sense to use a public field?

后端 未结 8 1218
北恋
北恋 2021-02-18 17:02

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:18

    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.

提交回复
热议问题