Clean Code: Should Objects have public properties?

前端 未结 13 1603
礼貌的吻别
礼貌的吻别 2021-01-03 20:40

I\'m reading the book \"Clean Code\" and am struggling with a concept. When discussing Objects and Data Structures, it states the following:

  • Objects hide thei
相关标签:
13条回答
  • 2021-01-03 21:18

    Generating public accessors with private fields establishes a contract between user code and your class. Ideally, this contract should not change over revisions to code.

    In C#, the way to enforce contract compliance is with an interface. Interfaces will allow you to specify required method and property implementations, but does not allow for fields.

    Moreover, in various points of .NET, properties are often preferred over fields. e.g. PropertyGrid control only enumerates properties, ASP.NET MVC model classes require properties, etc.

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