Skip to content

Latest commit

 

History

History
130 lines (73 loc) · 4.48 KB

File metadata and controls

130 lines (73 loc) · 4.48 KB

Code Smell 158 - Variables not Variable

Code Smell 158 - Variables not Variable

You assign a value to a variable and use it, but never change it

TL;DR: Be declarative on mutability.

Problems

  • Readability

  • Honor the Bijection mutability.

  • Potential performance and memory issues.

Solutions

  1. Change the variable to a constant and be clear on its scope

Refactorings

Refactoring 003 - Extract Constant

Refactoring 008 - Convert Variables to Constant

Context

We are always learning from the domain.

Sometimes we guess that a value can change with the MAPPER.

Later on, we learn it won't change.

Therefore we need to promote it to a constant.

This will also avoid Magic Constants

Sample Code

Wrong

<?

function configureUser() {
    $password = '123456';
    // Setting a password on a variable is a vulnerability
    $user = new User($password);
    // Notice variable doesn't change
}

Right

<?

define("USER_PASSWORD", '123456')

function configureUser() {  
    $user = new User(USER_PASSWORD);
}

// or 

function configureUser() {  
    $user = new User(userPassword());
}

function userPassword() : string {
    return '123456';
}

Detection

[X] Automatic

Many linters check if the variable has just one assignment.

We can also perform mutation testing and try to modify the variable to see if tests break.

Tags

  • Mutability

Conclusion

We must challenge ourselves and refactor when the variable scope is clear and we learn more about its properties and mutability.

Relations

Code Smell 116 - Variables Declared With 'var'

Code Smell 127 - Mutable Constants

Code Smell 107 - Variables Reuse

Code Smell 02 - Constants and Magic Numbers

More Info

The Evil Power of Mutants

Disclaimer

Code Smells are just my opinion.

Credits

Photo by Noah Buscher on Unsplash


A complex system that works is invariably found to have evolved from a simple system that worked.

John Gall

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code