0

in several projects I saw developers tendency to subclass anonymously say HashSet to mimic Set literal of some sort.

Set<String> set = new HashSet<String>() {{
  add("a");
  add("b");
}};

So what happens here is we're creating anonymous class and abusing it's instance initializer to add some items to Set. Personally, I consider it as a bad style, because of initializer, which we normally trying to avoid and because of pointless generation of another .class file. Sure, eyes hurts from that, but is it actually that bad? I mean nowadays we're getting one class file for every lambda anyways, so ...

What do you think?

Martin Mucha
  • 2,385
  • 1
  • 29
  • 49
  • 2
    Perhaps better asked in stack exchanges codereview ? – Marged Jan 10 '19 at 09:30
  • 1
    Read more about this in answer - ["Every time someone uses double brace initialisation, a kitten gets killed."](https://stackoverflow.com/a/27521360/1746118) – Naman Jan 10 '19 at 09:34
  • You’re *not* getting “one class file for every lambda”. You won’t find a single class file generated for a lambda expression in your compiled application. There are runtime classes generated by the JRE, but that’s an implementation dependent behavior. These generated classes carry much less overhead and in principle, a different JRE could generate much less classes. As said, that’s implementation dependent. – Holger Jan 10 '19 at 09:49
  • Besides that, this curly brace style is not even improving the readability. Nothing stops you from creating one `static Set hashSet(T... contents)` factory method in your application. Then compare the resulting usage `Set set = hashSet("a", "b");` (using `import static`) with the `Set set = new HashSet() {{ add("a"); add("b"); }};`; add more elements to make the difference even bigger. Even using built-in-since-Java-5 features only, `Set set = new HashSet<>(); Collections.addAll(set, "a", "b");` is more concise, especially when adding more elements. – Holger Jan 10 '19 at 09:54

0 Answers0