|
| 1 | +--- |
| 2 | +title: Provide default values with care |
| 3 | +date: 2025-08-20 |
| 4 | +page.meta.tags: programming, practices |
| 5 | +page.meta.categories: programming |
| 6 | +--- |
| 7 | + |
| 8 | +Something that comes up from time to time in code review is the use of default |
| 9 | +arguments for function parameters. Typically the line of reasoning for their |
| 10 | +inclusion involves making it easier for users of the function signature by |
| 11 | +requiring them to pass less arguments. I'm not a fan of this line of reasoning |
| 12 | +for a few reasons: |
| 13 | + |
| 14 | +1. If the function signature has become so long and convoluted that it's a burden |
| 15 | + to the caller then the function should probably be refactored. Not only is it |
| 16 | + a burden for the caller, it's probably difficult to test. |
| 17 | +1. Default values are a leaky abstraction. Clearly the argument is important to |
| 18 | + the internal mechanics of our function. It also may be important to the caller. |
| 19 | + What if we decide the default value should change? Is that a major breaking |
| 20 | + change (yes)? What state is the caller in if we change the default. Does everything |
| 21 | + keep working for them with the new default, did they come to rely on our leaky |
| 22 | + abstraction beyond the call boundary and now their code breaks with the change? |
| 23 | + |
| 24 | +Sometimes default argument values make sense. If you're writing an HTTP or ODBC |
| 25 | +library then a default timeout makes sense. When building applications or libraries |
| 26 | +that are specific to your company or project be careful. Context changes, people |
| 27 | +change, time moves forward and what once made sense as a default value |
| 28 | +will probably change. If it does it's hard to know the full impact. |
0 commit comments