Create better code – avoid using variables unless necessary
One of the most frustrating things a developer can deal with is hard-to-find bugs. Creating variables is one of those things that are best to avoid where possible. It is an approach to improve software quality by reducing the number of possible bugs and improving readability.
In JavaScript, use const instead of let. In Java, use final to indicate the value can be assigned only once.
Let’s dive in with some examples to explain why. I will use JavaScript in this example.
function setErrorMessage(someParam) {
let errorMessage = "";
if (someParam.length === 0) {
errorMessage = "Please provide a value";
} else if (someParam.length < 10) {
errorMessage = "Too short";
} else if (someParam.length > 50) {
errorMessage = "Too long";
}
document.getElementById('error').innerHtml = errorMessage
}
Ever seen something like this in your codebase? Maybe you have written a function yourself? I know I have. This variable is completely unnecessary, it could easily be written as:
function determineErrorMessage(someParam) {
if (someParam.length === 0) {
return "Please provide a value";
} else if (someParam.length < 10) {
return "Too short";
} else if (someParam.length > 50) {
return "Too long";
} else {
return "";
}
}
function setErrorMessage(someParam) {
const errorMessage = determineErrorMessage(someParam);
document.getElementById("error").innerHtml = errorMessage;
}
Declaring a variable means you are creating a side effect. Some people may argue that it is okay because it is a local scope variable and can not have a side effect. That may not be the case as the function grows and the variable gets modified. An earlier if the condition could influence the result and you have to go back and read each line of code to see what could have modified the value rather than just looking at the return statements. The second example will output in cleaner code with well-defined functions. Read more strategies on my storytelling blog post.
When should you use variables? The only time is when you are declaring state that must be immutable. This is pretty rare. If you find yourself declaring a variable, try refactoring out into a function like in the above example.