2

i have seen many developers using method local class (i don't mean anonymous class) in their code.

for example (in android):

private void myFunc()
{
    class Worker extends AsyncTask<Void, Void, Void> 
    {...}

    new Worker();
}

what are the pros and cons when doing this for both design and run time? is it bad to use local class when the method is called many times?

arshajii
  • 127,459
  • 24
  • 238
  • 287
Akram Berkawy
  • 4,920
  • 2
  • 19
  • 27

2 Answers2

1

As said, encapsulation is one reason, an also to not to have to create a new file for just a few lines that maybe don't have enough meaning on their own. In other languages is much easier and common to pass around behavior (high order functions, lambda expressions, etc...) and not to have to write a new class in a new file.

This you posted is one of the cheapest ways that Java has to accomplish that... so far. Java 8 seems to bring some of these other features.

Pedro R.
  • 142
  • 1
  • 11
1

Whoever reading the code can immediately know the method local class is not used anywhere else -- it can only be used inside that method. Hence if in the future it needs refactoring, the developer will know the change will only affect that method, not anything else in the program. Consider an enterprise-sized application with thousands of classes -- this extra bit of information is very valuable.

gerrytan
  • 40,313
  • 9
  • 84
  • 99