DEV Community

Cover image for Code Smell 154 - Too Many Variables
Maxi Contieri
Maxi Contieri

Posted on • Originally published at maximilianocontieri.com

Code Smell 154 - Too Many Variables

You debug code and see too many variables declared and active

TL;DR: Variables should be as local as possible

Problems

  • Readability

  • Code Reuse

Solutions

  1. Extract Method

  2. Remove unused variables

Context

Our code should be dirty when programming and writing test cases fast.

After we have good coverage we need to refactor and reduce methods.

Sample Code

Wrong

<?

function retrieveImagesFrom(array $imageUrls) {
  foreach ($imageUrls as $index=>$imageFilename) {
    $imageName = $imageNames[$index];
    $fullImageName = $this->directory() . "\\" . $imageFilename;
    if (!file_exists($fullImageName)) {
      if (str_starts_with($imageFilename, 'https://cdn.example.com/')) {
          // TODO: Remove Hardcode
          $url = $imageFilename;
          // This variable duplication is no really necesary 
          // When we scope variables        
          $saveto= "c:\\temp"."\\".basename($imageFilename);
          // TODO: Remove Hardcode
          $ch = curl_init ($url);
          curl_setopt($ch, CURLOPT_HEADER, 0);
          curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
          $raw = curl_exec($ch);
          curl_close ($ch);
          if(file_exists($saveto)){
               unlink($saveto);
          }
          $fp = fopen($saveto,'x');
          fwrite($fp, $raw);
          fclose($fp);
          $sha1 = sha1_file($saveto);
          $found = false;
          $files = array_diff(scandir($this->directory()), array('.', '..'));
          foreach ($files as $file){
              if ($sha1 == sha1_file($this->directory()."\\".$file)) {                         
                  $images[$imageName]['remote'] = $imageFilename;
                  $images[$imageName]['local'] = $file;
                  $imageFilename = $file;
                  $found = true;
                  // Iteration keeps going on even after we found it
              }
          }
          if (!$found){
            throw new \Exception('We couldnt find image');
         }
        // Debugging at this point our context is polluted with variables
        // from previous executions no longer needed
        // for example: the curl handler
  }
Enter fullscreen mode Exit fullscreen mode

variables

Right

<?php

function retrieveImagesFrom(string imageUrls) {
  foreach ($imageUrls as $index => $imageFilename) {
    $imageName = $imageNames[$index];
    $fullImageName = $this->directory() . "\\" . $imageFilename;
    if (!file_exists($fullImageName)) {
        if ($this->isRemoteFileName($imageFilename)) {
            $temporaryFilename = $this->temporaryLocalPlaceFor($imageFilename);
            $this->retrieveFileAndSaveIt($imageFilename, $temporaryFilename);
            $localFileSha1 = sha1_file($temporaryFilename);
            list($found, $images, $imageFilename) = $this->tryToFindFile($localFileSha1, $imageFilename, $images, $imageName);
            if (!$found) {
                throw new \Exception('File not found locally ('.$imageFilename.'). Need to retrieve it and store it');
            }
        } else {
            throw new \Exception('Image does not exist on directory ' . $fullImageName);
        }
    }
Enter fullscreen mode Exit fullscreen mode

Detection

[X] Automatic

Most Linters can suggest use for long methods.

This warning also hints us to break and scope our variables.

Tags

  • Bloaters

Conclusion

Extract Method is our best friend.

We should use it a lot.

Relations

Refactorings

Credits

Photo by Dustan Woodhouse on Unsplash


Temporary variables can be a problem. They are only useful within their own routine, and therefore they encourage long, complex routines.

Martin Fowler


This article is part of the CodeSmell Series.

Top comments (3)

Collapse
 
mcsee profile image
Maxi Contieri

you are right !
Changed !
thank you

Collapse
 
joolsmcfly profile image
Julien Dephix

There are various things missing or not working in your code example. It doesn’t change the meaning you’re trying to convey, of course, but it makes it look like you rushed and didn’t pay attention to details.

Parameter is string imageUrls (it’s missing the dollar sign) but you iterate over it so it should be an array, not a string.

throw new \Exception('We could'nt find image');
Enter fullscreen mode Exit fullscreen mode

Syntax error: either escape the apostrophe or surround the message with double quotes.

I know it’s not the scope of your post but you could have passed $imageNames as param to avoid referencing a variable outside of the function scope.

$imageName = $imageNames[$index];
Enter fullscreen mode Exit fullscreen mode

Talking about too many variables you can just return a Boolean here:

list($found, $images, $imageFilename) = $this->tryToFindFile($localFileSha1, $imageFilename, $images, $imageName);
Enter fullscreen mode Exit fullscreen mode

Something like:

// method probably doesn’t need all 4 parameters
if (!$this->fileExists($localFileSha1, $imageFilename, $images, $imageName)) {
    // throw exception
}
Enter fullscreen mode Exit fullscreen mode

I like the idea of showcasing code smells but it would look better with working code IMHO.

Collapse
 
mcsee profile image
Maxi Contieri

Hi

Thank you very much for taking the time to correct the code.
I've made several of your suggestions.

I treat code as pseudocode and not real one

More on this here

I've also decided not to use 'php list()' returning more than one argument because it is not common on other languages