Is defining a variable to name a method argument a good practice

coding-style

For the sake of readability I often find myself defining temporary variables while calling functions, such as the following code

var preventUndo = true;
doSomething(preventUndo);

The shorter version of this to this would be,

doSomething(true);

But when I come back to the code I often wonder what true refers to. Is there a convention for this kind of conundrum?

Best Answer

Explaining Variables

Your case is an example of the introduce explaining variable / extract variable refactoring. In short, an explaining variable is one which is not strictly necessary, but allows you to give a clear name to something, with the aim of increasing readability.

Good quality code communicates intent to the reader; and as a professional developer readability and maintainability are your #1 goals.

As such, the rule of thumb I would recommend is this: if your parameter's purpose is not immediately obvious, feel free to use a variable to give it a good name. I think this is a good practice in general (unless abused). Here's a quick, contrived example - consider:

editButton.Enabled = (_grid.SelectedRow != null && ((Person)_grid.SelectedRow).Status == PersonStatus.Active);

versus the slightly longer, but arguably clearer:

bool personIsSelected = (_grid.SelectedRow != null);
bool selectedPersonIsEditable = (personIsSelected && ((Person)_grid.SelectedRow).Status == PersonStatus.Active)
editButton.Enabled = (personIsSelected && selectedPersonIsEditable);

Boolean Parameters

Your example actually highlights why booleans in APIs are often a bad idea - on the calling side, they do nothing to explain what's happening. Consider:

ParseFolder(true, false);

You'd have to look up what those parameters mean; if they were enums, it'd be a lot more clear:

ParseFolder(ParseBehaviour.Recursive, CompatibilityOption.Strict);

Edit:

Added headings and swapped the order of the two main paragraphs, because too many people were focusing on the boolean parameters part (to be fair, it was the first paragraph originally). Also added an example to the first part.

Related Topic