Since I started reading “Good Code, Bad Code,” I’ve found a wealth of beneficial information. One key takeaway is how using named functions instead of anonymous functions can significantly improve readability. Here are some examples to illustrate this point.
Example with Anonymous Functions
Consider the following code, which filters a list of election candidates to include only those from a specific party, sorts them by the number of votes, and maps them to a simplified object:
|
|
Named Functions
The same logic can be rewritten using named functions, enhancing readability and maintainability:
|
|
Improvements with Named Functions
The modifications from using anonymous functions to named functions have improved the code in the following aspects:
- Readability:
- Anonymous Functions: Inline anonymous functions can obscure the purpose of each operation, making the main logic harder to follow.
- Named Functions: Each named function clearly states its purpose, improving the readability of the main processing pipeline. It is immediately clear what each step is doing.
- Maintainability:
- Anonymous Functions: Any changes to the logic require modifying the inline code, which can be cumbersome and error-prone.
- Named Functions: Named functions can be updated independently, making the codebase easier to maintain and extend.
- Reusability:
- Anonymous Functions: The logic encapsulated in anonymous functions cannot be reused easily.
- Named Functions: Named functions like
isFromPartyA
,sortByVotesDesc
, andextractCandidateInfo
can be reused in other parts of the code, promoting code reuse.
- Debugging and Testing:
- Anonymous Functions: Debugging can be more difficult as the stack traces may not provide meaningful function names.
- Named Functions: Named functions provide meaningful names in stack traces, aiding in debugging. Additionally, each function can be independently tested, ensuring the correctness of each part of the logic.
Summary
By using named functions, the code becomes more readable, maintainable, reusable, and easier to debug and test.