Search code examples
javascriptangulartypescriptsonarqubeangular8

SonarQube displaying to 'remove this useless assignment to local variable'


Why is SonarQube giving this error? How should I fix it? Their rule page does not specify the solution,

Remove this useless assignment to local variable "validateAddressRequest".

  validateAddress() {
    if (this.propertySitusMailingForm.valid) {
      let validateAddressRequest: ValidateAddressRequest = new ValidateAddressRequest();
      let propertySitusData = new PropertySitusAddress(this.propertySitusMailingForm.value);
      validateAddressRequest = convertToValidateRequest(propertySitusData);
      this.validationService.validateCall(validateAddressRequest);
    }
  }

enter image description here


Solution

  • This site says that the error occurs when:

    A value is assigned to a variable or property, but either that location is never read later on, or its value is always overwritten before being read. This means that the original assignment has no effect, and could indicate a logic error or incomplete code.

    On the first line of the if block, you assign to validateAddressRequest, but then on the third line of the if block, you overwrite validateAddressRequest without having read the previously assigned variable. So the first line is useless.

    Declare validateAddressRequest only when calling convertToValidateRequest instead.

    const validateAddressRequest = convertToValidateRequest(propertySitusData);
    

    Note that you almost certainly don't need the type annotation - if Typescript knows that convertToValidateRequest returns a ValidateAddressRequest already, there's no need to do so again with the new variable. You can do so if you think it's unclear otherwise, or if you don't have type Intellisense, but it may just be noise.

    If you were declaring the variable with let so as to enable assignment to it in the future, keep in mind that it's best to avoid reassignment whenever possible, and it's almost always possible to avoid reassignment. If you need another variable that contains a ValidateAddressRequest, give it a different variable name so that you can use const to declare both variables; that makes the code more understandable at a glance, when a reader can be sure that a particular variable reference isn't ever going to be reassigned.