Cover of Refactoring by Martin Fowler, Kent Beck - Business and Economics Book

From "Refactoring"

Author: Martin Fowler, Kent Beck
Publisher: Addison-Wesley Professional
Year: 1999
Category: Computers

🎧 Free Preview Complete

You've listened to your free 10-minute preview.
Sign up free to continue listening to the full summary.

🎧 Listen to Summary

Free 10-min Preview
0:00
Speed:
10:00 free remaining
Chapter 6: A First Set of Refactorings
Key Insight 1 from this chapter

Extract Function

Key Insight

Extract Function is a fundamental refactoring technique, frequently applied to enhance code clarity and maintainability. Its core motivation is to encapsulate a coherent code fragment into a new function, explicitly naming it after its purpose rather than its implementation details. This approach prioritizes separating 'what' a piece of code does from 'how' it achieves it, which greatly improves readability. This refactoring advocates for creating very small functions, often just a few lines or even a single line, as exemplified by a 'highlight' method calling 'reverse'; the length is less important than the clarity gained by naming the intention.

The mechanics involve creating a new function with an intent-revealing name, then copying the target code into it. Variables local to the original function but needed by the extracted code must be passed as parameters; if a variable is only used within the extracted section but declared externally, its declaration should be moved into the new function. Special care is needed for variables assigned within the extracted code, especially if they are passed by value; ideally, the extracted code acts as a query returning a single result to be assigned. If too many variables are reassigned, it may be better to reconsider the extraction, perhaps by first applying 'Split Variable' or 'Replace Temp with Query'. After handling variables, replacing the original code with a call to the new function and thorough testing are crucial steps.

For languages supporting nested functions, extraction can initially be nested to simplify variable scope. When dealing with reassigned local variables, if the variable is used outside the extracted function, its new value must be returned. If multiple values need to be returned, it is often preferable to restructure the code to allow for single return values or to use a record for return, though simplifying temporary variables with 'Replace Temp with Query' or 'Split Variable' is usually better. Identifying descriptive comments in the original code often provides excellent hints for the new function's name, further enhancing self-documentation.

📚 Continue Your Learning Journey — No Payment Required

Access the complete Refactoring summary with audio narration, key takeaways, and actionable insights from Martin Fowler, Kent Beck.