Clean Code: Should Objects have public properties?

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

    Actually by using a Property e.g.

    public class Temp
    {
       public int SomeValue{get;set;}
       public void SomeMethod()
       {
         ... some work
       }
    }
    

    You are hiding its data as there is an implicit variable to store the value set and returned by the SomeValue property.

    If you have

    public class Temp
    {
       private int someValue;
       public int SomeValue
       {
         get{ return this.someValue;}
         set{ this.someValue = value;}
       }
       public void SomeMethod()
       {
         this.someValue++;
       }
    }
    

    Then you'll see what I mean. You're hiding the object's data someValue and restricting access to it using the SomeValue proiperty.

提交回复
热议问题