Software Engineer Robert Muth wrote this interesting article on refactoring large functions.
The article starts with providing ample motivation for using functions (or methods in a strictly object-oriented context). Apart from making code shareable and reusable, which is only a minor benefit of functions / methods, reasons for writing code as functions are:
- giving a meaningful name to several lines of related code
- readability
- limiting visibility
- lowering indentation levels
- improving testability
The article goes on to describe several common cues indicating that extracting the code at hand to a function might be warranted. Some of these cues are:
- loops
- complex if-statements
- logical cohesion (flag parameters)
Finally, the author shares some techniques and best practices for refactoring code with functions while making the code more testable in the process.