Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 338
an00b Avatar asked Jan 30 '12 15:01

an00b


3 Answers

Three reasons to start with:

  • You can test it in separation from anything else. (This may end up going against the mantra of only testing public APIs, but that's fine by me. It's annoying if I have to make a method package-level instead of private in order to test it, but I'd rather do that than have to test a huge lump of logic in one go.)
  • You can build a more complicated method from simple methods, where the whole of the complicated method is at a single abstraction level, without specifying details. Reading the high-level method means just reading the names of the building blocks it's composed from; you can then dive into just the details you're interested in if you need to.
  • You can write methods which each do one thing well, and name and document them in an obvious way

Of course this can be overdone, but it can definitely be useful.

like image 168
Jon Skeet Avatar answered Nov 04 '22 19:11

Jon Skeet


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.

like image 7
vaughandroid Avatar answered Nov 04 '22 19:11

vaughandroid


documentation and readability are very good reasons to put code into methods, even if those methods will only be executed once. Some applications might have a bunch of logical steps to complete on startup....would you rather have all that code jumbled in one init method, or an init method that calls methods that are properly named?

like image 4
hvgotcodes Avatar answered Nov 04 '22 21:11

hvgotcodes