ClearSlide Blog

The Latest Product Updates & Thought Leadership

PSA: Avoid Flag Arguments

tech-tuesday

‘Sliders have heard me harp on this before, but I really dislike flag arguments: I think they should be avoided. Fowler defines a flag argument as, “a kind of function argument that tells the function to carry out a different operation depending on its value.” A flag argument is a form of control coupling. The caller passes a flag to tell the receiver what to do. This implies that your function is doing more than one thing and may be more complicated than it needs to be.

I was reviewing a pull request this morning and was reminded of one of the reasons for my disdain.

blog

There are two invocations of `UploadStatus.startUploadStatus(…)`. Both calls have the same set of arguments, except for the last, Mr. Flag. Who can tell me what the difference is? You might actually know. However, will you remember 6 months from now? How about a year? I know that I’ve written code like this and then later had to look up what the flag does.

One argument I’ve heard is that, “my IDE will tell me what it means.” Sure. However, code doesn’t exist in an IDE alone. In this case, I was reviewing it in stash. I even tried to look up what the flag meant in my IDE, but that method isn’t in my branch. I have to keep track of enough things in my head. I don’t want to have to remember what the flag is doing.

Remembering what it controls isn’t always enough. You also have to remember which value controls it in what way. For example, every object in Ruby has a “methods” method (that’s a mouthful) that lists all the methods the object will respond to. If you pass it true, it will return all the public and protected methods including those it inherited. If you pass it false, it will only return it’s unique methods. Confession, I never remember which value maps to which result and had to look it up just now.

With this in mind, do yourself and your coworkers a favor and avoid flag arguments. A better alternative is to just tell the receiver what to do by calling a different method. If you see me succumbing to the allure of the easy change by introducing a flag, call me out on it. Publicly and with great mockery.

Here are two links that discuss flag arguments if you are interested in learning more:

* Fowler: Flag Argument
* Robert C. Martin’s Clean Code Tip #12: Eliminate Boolean Arguments

Written By: TJ Singleton, Lead Software Engineer