DEV Community

Cover image for Code Smell 158 - Variables not Variable
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

3

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

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

<?php

function configureUser() {
  $password = '123456';
  // Setting a password on a variable is another vulnerability
  // And Code Smell
  $user = new User($password);
  // Notice Variable doesn't change
}
Enter fullscreen mode Exit fullscreen mode

Right

<?php

define("USER_PASSWORD", '123456')

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

// or 

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

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

// Case is oversimplification as usual
Enter fullscreen mode Exit fullscreen mode

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

Refactorings

More Info

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


This article is part of the CodeSmell Series.

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay