Anonymous classes do not βhideβ the code, but they do a TEND to make it somewhat less reusable. Please note that this also applies to closure.
In a sense, they allow some good refactors because you are allowed to pass code to a method. This can be used effectively to reduce duplication, and I'm certainly not against anonymous classes / closures, however there are a few cases where they can be a drawback.
First, think that the code of the anonymous inner class that you pass in cannot be reused in your code. If you do the same in some other code, you will have to rewrite it as something other than an anonymous inner class in order to reuse it, and at this point it would be difficult even to know that there is code in another place for reuse.
Along with the lack of reuse, it is difficult to determine the parameterization, which leads to my biggest complaint ... they usually lead to copying and pasting the code.
I saw a lot of graphical interfaces where someone started with anonymous inner classes as event responders. Many had to do something a little different: for example, 5 lines of code, where the only difference is the line in the middle. Once you are used to using inner classes, a simple solution is to copy and paste the block and replace this line.
The decision to create a new "Named" class that has a string parameter and passes this class to all methods is rarely found at someone at this point. This named class can use parameters or inheritance to define different types of behavior, as well as code.
I'm a fan of closures and don't hate anonymous classes - just pointing out some of the pitfalls I've seen.
Bill K May 01 '17 at 16:38 2017-05-01 16:38
source share