States(properties) should never be public or it breaks encapsulation.That's why a language that allows a property to be a method under the hood is usefull, because the state is still encapsulated.
State changes can have desirable side effects.If you expose an instance variable directly it's harder to encapsulate that.
Of course there are exceptions. If you have a class that is meant to be only a parameter bag(in an rest API for instance),that's ok,imho.
I work just fine in a language that has no "private" variables or methods. It's not for everyone, and it requires some discipline to not get burned.
Don't get me wrong, I'm big on encapsulation and separation of concerns, etc. But you don't need to force "privacy" onto your class's users in order to achieve it.
The worst thing about having everything public (this is python, btw) is that sometimes it pollutes the auto-complete, and hinders discoverability. It's also not immediately obvious what the user should/shouldn't have access in your class.
Here's a class C with a variable v of type T. It's supposed to be something that the rest of the world can access. You can make it public. Or you can make it private, and write
public T get_v() { return v; }
So far, not much difference. Both let the world access the variable, and both break encapsulation by doing so.
The difference comes when the class gets more complicated, and v changes. Now v might be null, whereas it never could be null before. But if it is, then what the rest of the world saw as v should now be some default value. So we can say:
public T get_v()
{
if (v != null)
return v;
else
return default_T;
}
and life goes on for everybody that was using v. But if all we had was a variable that everybody accesses, then all the users have to change. They either have to access the new getter or, worse, they each have to copy the logic to check for null.
This is how the getter encapsulates the inner workings of the class, and why it's a really good thing.
"P.S.: How do I specify code formatting on HN?"
I'm not sure if there is one. But if you want, just make a pasteIt, or a fiddle. Not sure which one is the one that caters for C/C++ code.
Your public facing methods/accessors are a sort of contract between a class, and whatever uses it.
The contract basically says: "I will behave as you expect me to and as we agreed but only as long as you only interact with me in the predetermined(designed) ways that I allow you to"
State changes can have desirable side effects.If you expose an instance variable directly it's harder to encapsulate that.
Of course there are exceptions. If you have a class that is meant to be only a parameter bag(in an rest API for instance),that's ok,imho.