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 11: Refactoring APIs
Key Insight 3 from this chapter

Remove Flag Argument

Key Insight

Flag arguments are function parameters that callers use to signal which specific code path or behavior the called function should execute. These can manifest as boolean values, enums (e.g., `CustomerType.PREMIUM`), or strings ('premium'). Such arguments hinder API comprehensibility by obscuring the distinct function calls available and their corresponding meanings. Boolean flags are particularly problematic as their `true` or `false` value lacks inherent meaning at the call site, making intent unclear. Providing explicit functions for each specific task, such as `premiumBookConcert(aCustomer)`, significantly improves code clarity.

A parameter qualifies as a flag argument if callers pass literal values (not data flowing through the program) and if the argument primarily dictates the function's control flow, rather than serving as data for subsequent operations. Eliminating flag arguments not only makes code more readable but also benefits code analysis tools by clarifying distinct logic branches. While the presence of multiple flag arguments might suggest retaining them to avoid an excessive number of explicit functions, this often indicates an overly complex function that could benefit from decomposition into simpler, more composable units.

The refactoring process involves creating a dedicated, explicit function for each distinct literal value the flag argument might take. If the original function's logic is structured with a clear conditional dispatch based on the flag, that conditional can be decomposed to form the new explicit functions. Alternatively, simple wrapping functions can be created that delegate to the original function with the appropriate flag value. Each call site that uses a literal for the flag argument is then updated to invoke the relevant explicit function. For example, `deliveryDate(anOrder, true)` becomes `rushDeliveryDate(anOrder)`, and `deliveryDate(anOrder, false)` becomes `regularDeliveryDate(anOrder)`. If the flag's logic is deeply embedded, creating wrapper functions like `function rushDeliveryDate (anOrder) {return deliveryDate(anOrder, true);}` is a viable strategy. After all callers are updated, the original function can be removed or its visibility restricted.

📚 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.