Clean Code: Should Objects have public properties?

前端 未结 13 1755
礼貌的吻别
礼貌的吻别 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:07

    Public properties are fine. Not having to write explicit GetHeight() and SetHeight() methods is what properties are all about. A property in C# is not data; it is best viewed as a pair of getter/setter methods. (Properties are actually compiled down into methods in the generated IL.)

    The data hiding is possible because you can change the implementation without changing the interface. For example, you could change

    public int Height { get; set; }
    

    into

    public int Height { get { return m_width; } set { m_width = value; } }
    

    if you decided that your object should always be square. The code using your class would not need any modifications.

    So if your object exposes public properties, it still "hides it data behind abstractions and exposes functions that operate on that data", as the book recommends.

提交回复
热议问题