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:
versus the slightly longer, but arguably clearer:
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:
You'd have to look up what those parameters mean; if they were enums, it'd be a lot more clear:
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.