Joined August 2011
·

Anders Norås

CTO at Itera
·
Oslo, Norway
·
·
·

Posted to Easier Java object initialization over 1 year ago

@wimplash Indeed. Particularly for maps, as for lists I find the Arrays.asList method instead, since it is more compact. E.g.:
Arrays.asList(5, 4, 1, 3, 9, 8, 6, 7, 2, 0)

Posted to Easier Java object initialization over 1 year ago

@mikera I respect your concerns. However, this is not primarily about saving yourself from a little typing. It's about improving readability. Remember that we spend more time reading code than writing it.

If a class shouldn't be inherited from, you should declare it as final. You cannot create an anonymous inner class from a final class. Not accepting derived classes has a lot of implications, much more severe than blocking my little initialization trick. For instance final classes cannot be mocked for testing purposes unless you use JDave, PowerMock or something similar.
Remember that this trick exploits the is-a relationship of object orientation, which is a fundamental part of the Java language. Far from sneaky IMHO. Still, this is different from you're vanilla Java, and I agree that my example might be a little hard to grasp the first time you come across it.

Posted to Java and JavaScript over 1 year ago

Java and JavaScript are similar in the same way as Car and Carpet are similar.

Posted to Easier Java object initialization over 1 year ago

@sujaykrishna The only difference between the anonymous classes and the top-level classes is that the anonymous classes will hold an implicit reference to the outer class.
This won't manifest itself in performance unless you serialize the class, which will have a minor performance implication.
You'll spend a little more memory, but that is largely nothing to worry about. The same GC-rules apply to anonymous classes as top-level classes.

Posted to Easier Java object initialization over 1 year ago

@rosspb3 Yes, that is correct. This technique exploits that the nested inner class is-a JsonObject. I've never found this to be a problem, even if it will use a bit more memory and that it changes the type.

Achievements
238 Karma
14,248 Total ProTip Views