Function Whose Every Return Path Yields The Same Literal
ID |
javascript.functions_return_constants |
Severity |
info |
Remediation Complexity |
trivial |
Remediation Risk |
low |
Remediation Effort |
low |
Resource |
Code Smell |
Language |
JavaScript |
Tags |
code-smell, simplification |
Description
Reports a function whose every return path yields the same literal. Nothing the caller passes can change the answer, so the call reads like a decision the function makes and is in fact a constant the reader has to open the body to discover.
Only a primitive literal counts — a string, a number, true, false or null, optionally with a sign. An array, an object or a template literal builds a fresh value on every call, and a regular expression a fresh object with its own match cursor, so none of them is the constant this rule is about.
Judged only where a constant return is the author’s whole intent: a named function declaration, or a function assigned to a variable or a class field. A callback argument is left alone, since a constant is a perfectly ordinary thing for a callback to produce. So are getters and setters, constructors, generators and async functions, and any method of a class that extends or implements something — there the constant satisfies an inherited contract rather than standing in for a value.
Rationale
// Bad
function defaultPageSize() {
return 50;
}
function isEnabled(user) {
if (user.admin) {
return true;
}
return true; // the branch makes no difference
}
-
The first shape hides a constant behind a call. Every reader who wonders what the page size is has to open the function to find out that it never varies.
-
The second is the more valuable of the two: a function with real branches that all end in the same value is usually a check that was disabled during debugging, or a return that was edited on one path and forgotten on the other. It looks like working code in review, and the caller’s behaviour no longer depends on the input the branch tests.
Remediation
Name the constant, and delete the branching that no longer decides anything.
// Good
const DEFAULT_PAGE_SIZE = 50;
function isEnabled(user) {
return user.admin; // the value the branch was meant to produce
}