News for hackers. Stuff that matters.
Re:Java 9 features announced by AnimalMuppet on Monday August 18, 2014 @03:58PM (#8194297)
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?

Re:Java 9 features announced by msluyter on Monday August 18, 2014 @05:30PM (#8194813)
Indent the code with two or more spaces:

  public T get_v() {
      return v;
  }
See: https://news.ycombinator.com/formatdoc
Re:Java 9 features announced by zo1 on Monday August 18, 2014 @04:03PM (#8194335)
"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.