I am getting following code smell in my sonarqube dashboard, and I am not sure how to resolve such issues.
‘isInitialized’ is already declared in the upper scope.
Here’s my code-
let _isInitialized = false;
/**
* Getter for _isInitialized
*
* @return {Boolean} _isInitialized
*/
export const isInitialized = function() {
return _isInitialized;
};
/**
* Sets isInitialized
* @param {Boolean} isInitialized new value for inititialized
*/
export const setIsInitialized = function( isInitialized ) {
_isInitialized = isInitialized;
};
Can anyone please explain what’s the problem in my code?
Don’t know what to try as my code is working correctly but getting this issue on sonarqube dashboard.
2
Answers
Here you define a variable called
isInitialized
in the scope of the module usingconst
Here you define a variable with the same name in the scope of the function using an argument name.
Don’t do that. Use unique names for variables.
tldr: There isn’t any problem with the code.
SonarQube is configured to check a rule similar to the
no-shadow
rule of ESLint. It basically checks that the code does not reuse a name when another object is accessible in the same scope using that name.The function
setIsInitialized()
uses the nameisInitialized
for its parameter but in its scope, the global constisInitialized
is also visible.The function parameter
isInitialized
hides the global const, rendering it unusable in the function body.Your current code:
You can rename the parameter of
setIsInitialized()
to have access to the global constisInitialized
and this will make the message disappear.Your code does not need this change because the
setIsInitialized()
function does not have any reason to use theisInitialized()
function.However, avoiding shadowing is generally considered a good practice; it prevents confusion and misunderstanding for the code readers.