Andrew's Digital Garden

Flag arguments

aka 'Control parameter', or general 'boolean parameters'.

A 'flag argument' is when you pass a boolean 'flag' to a function that modifies the underlying function in some way, e.g:

function doThis(boolean flag) { foo(); if (flag) { bar(); } }

Generally, these should be avoided. They don't signal intention well and are hard to read on first glance. It also can be considered to have low cohesion, as the underlying function is doing more than one thing.

Sometimes this is okay if the 'branch' of code is more of a side effect. In this case the call site is still calling for the same action, it's just that hte implementation may do something else insignificant at the same time, e.g. analytics.

Different methods

A possible solution is to have different methods. If the implementation is more tangled than that, a possible approach can be to have public methods with clear names, that internally call a private method that uses a flag argument. This solves the problems listed above as the caller now is more intentional about what it is trying to do.

Enums/naming the flag

Another solution is to name the variable at the call site in some way, e.g. with an enum, or by passing a object with key/val pairs. This approach is better than passing a true/false as it better signals what's wanted.

Derived flags

A derived flag is subtly different, and is usually more acceptable. This is when the flag is derived from another parameter, rather than explicitly passed at the call site. For example, a customer tier that gets different booking functionality. The caller doesn't care which underlying function is called, only that the customer receives a booking. In this case, the flag is fine.

https://martinfowler.com/bliki/FlagArgument.html

[[20210202103254-coupling-cohesion]]

[[smells]]

Flag arguments