Flag arguments to be avoided?
A flag argument is a function argument of a boolean type that alters the function behaviour. Often but not always, a function caller decides what behaviour she wants by specifying the value for the flag. And if she does, it makes sense to review the API and determine if we need the flag argument.
Martin Fowler recommends splitting one method into two instead of a flag argument.
My reasoning here is that the separate methods communicate more clearly what my intention is when I make the call. Instead of having to remember the meaning of the flag variable when I seebook(martin, false)
I can easily readregularBook(martin)
.
Another approach might be to remove the flag and have only one function. Consider the following example.
export const linkToInspiration = (slug, locale, absolute = false) => {
const base = absolute ? absoluteUrl(locale) : '';
return `${base}/inspiration/${slug}`;
};
// We have functions for for different links `linkTo<some name>`.
I prefer to remove the flag argument from all these functions and add one more method to make the link absolute.
export const makeAbsolute = (locale, url) => `${absoluteUrl(locale)}${url}`;
export const linkToInspiration = (slug) => `/inspiration/${slug}`;
// Use case:
console.log({
rel: linkToInspiration('abc'),
abs: makeAbsolute('en-US',linkToInspiration('abc'))
});
My reasoning here is that each method clearly communicates the intention to the API user. This is precisely the same argument as Marting gives in his book.
This is a subtle decision because of the consequences for the API users. However, it simplifies the function's implementation and removes code duplication. And I would argue that having two different methods for every URL type would introduce even more code duplication and pollute the API.