Clean Code: Should Objects have public properties?

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

    Here's the deal.

    Although public variables may be useful on occasion, it is often best to keep them private.

    It's easy to keep your code organized if the object is the only one with control over its variable.

    Imagine that you want to maintain a height between 0 and 200. If you have a method to set your height, you can monitor this easily.

    For example (I'll be using Java for speed sake):

    public void setHeight(int newHeight)
    {
        if (newHeight < 0)
            height = 0;
        else if (newHeight > 200)
            height = 200;
        else
            height = newHeight
    }
    

    As you can see, this approach is very structured and controlled.

    Now imagine that we have a line of code that edits this height externally because you choose to make it public. Unless you control it outside the code, you may get a height that doesn't behave well with your program. Even if you did want to control it, you'd be repeating code.

    Very basic example, but I think it gets the point across.

提交回复
热议问题