Search code examples
javarefactoringcode-reusecode-readability

chunk of code that's called only once - merits own method?


From observing source code for various Android applications (not written by me), I noticed a pattern of placing certain pieces of code into their own methods, although there really isn't any code reuse, because those methods are only called once throughout the entire application.

Up until now I had a rule of thumb which dictates that if a piece of code is used twice or more in the application code, then it merits its own method, simply for reason of eliminating code redundancy.

But seeing those neatly broken out chunks of code into own methods (and own method calling overhead), I am beginning that maybe I am missing something.

Other than for documentation purposes, what other reasons can justify putting only 4 lines of code (that are called only once!) into own method?


Solution

  • There are a few reasons I can think of, though admittedly there's some overlap:

    • It helps make your code self-documenting.
    • It makes (unit) testing easier.
    • It helps stop you ending up with methods which are hundreds of lines long.
    • You might want to use that code somewhere else in the future.

    Of course, all of this relies on the assumption that those 4 lines of code are related, and performing a single function. I find that a good rule of thumb is: if you can't think of a name for it, it probably shouldn't be a method.