I\'m reading the book \"Clean Code\" and am struggling with a concept. When discussing Objects and Data Structures, it states the following:
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.