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?
Three reasons to start with:
Of course this can be overdone, but it can definitely be useful.
There are a few reasons I can think of, though admittedly there's some overlap:
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.
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?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With