Clean Code: Should Objects have public properties?

前端 未结 13 1759
礼貌的吻别
礼貌的吻别 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 20:59

    It is mostly another definition of the term "property". A property in C# is not what most other languages think of as properties.

    Example:
    A C++ public property is:

    class foo
    {
      public:
        int x;
    };
    

    The corresponding term in C# would be a public field:

    class foo
    {
      public int x;
    }
    

    What we name in C# as properties would be setters and getters in other languages:

    C#:

    class foo
    {
      public int X { get; set; }
    }
    

    corresponding C++:

    class foo
    {
      private:
        int x;
    
      public:
        void setX(int newX) { this->x = newX; }
        int  getX() { return this->x; }
    }
    

    In short:
    C# properties are totally fine, just don't blindly default them to get and set and don't make every datafield in your class a public property, think about what users of your class really need to know/change.

提交回复
热议问题