A piece of code that is called only once deserves its own method?

From observing the source code for various Android applications (not written by me), I noticed a pattern of placing certain fragments of code in my own methods, although in fact there is no reuse of the code, because these methods are called only once in the entire application.

So far, I had a rule that dictates that if part of the code is used twice or more in the application code, then it deserves its own method simply because of the elimination of code redundancy.

But, seeing these neatly broken pieces of code in my own methods (and my own invocation of the method call), I begin that maybe I'm missing something.

In addition, for documentation purposes, what other reasons can justify entering only 4 lines of code (which are called only once!) In your own method?

+5
source share
7 answers

There are several reasons that I can think of, although admittedly there are a few coincidences:

  • This helps make your code self-documenting.
  • This simplifies (single) testing.
  • This helps stop you from using methods that are hundreds of lines long.
  • You might want to use this code somewhere else in the future.

, , 4 . , : , , , .

+5

:

  • . ( , API-, . , , , , .)
  • , , . , ; , .
  • , , .

, , .

+8

, . ..............................................................................

+4

, .

, , .

+3
+2

- .

, , , .

? /, ? , , .

, , . , .

, .

+1

The Java VM generally has a limit on the maximum size of a method that will be eligible for inlining. Extracting the often-called code can lubricate the wheels, so to speak. Can you provide examples?

0
source

All Articles