What's the harm in using Anonymous class?

后端 未结 6 1061
-上瘾入骨i
-上瘾入骨i 2021-01-31 08:41

The question arose while reading a answer to this question - How do I join two lists in java. This answer gave the solution

List newList = new Arra         


        
6条回答
  •  庸人自扰
    2021-01-31 09:06

    This particular use of anonymous classes has several problems:

    1. it's a little-known idiom. Developers that don't know it (or know it an don't use it a lot) will be slowed down when reading and/or modifying code that uses it.
    2. it's actually misusing a language feature: you're not trying to define a new kind of ArrayList, you just want some array list with some existing values in it
    3. it creates a new class that takes up resources: disk space to hold the class definition, time to parse/verify/... it, permgen to hold the class definition, ...
    4. even if the "real code" is slightly longer, it can easily be moved into an aptly-named utility method (joinLists(listOne, listTwo))

    In my opinion #1 is the most important reason to avoid it, closely followed by #2. #3 is usually not that much of a problem, but should not be forgotten.

提交回复
热议问题