4 ms·
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
by AnimalMuppet 12y ago
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?
- zo1 12y ago"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.
- deleted 12y ago[deleted]
- msluyter 12y agoIndent the code with two or more spaces: public T get_v() { return v; } See: https://news.ycombinator.com/formatdoc https://news.ycombinator.com/formatdoc