Code Smell 154 - Too Many Variables
Tags: webdev, beginners, programming, tutorial
Published: 2022-07-31 23:11:00

*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](https://dev.to/mcsee/refactoring-002-extract-method-1eee)

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

[Gist Url]: # (https://gist.github.com/mcsee/b3d04c90186e88bca3e3353af7c24284)
```php
<?

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
  }
```

![variables](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/oal957254rles8mmwim8.PNG)

## Right

[Gist Url]: # (https://gist.github.com/mcsee/21117af327d700e359d1eccf2d45accc)
```php
<?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);
        }
    }
```

# 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](https://dev.to/mcsee/refactoring-002-extract-method-1eee) is our best friend. 

We should use it a lot.

# Relations

{% post https://dev.to/mcsee/code-smell-149-optional-chaining-jk %}

{% post https://dev.to/mcsee/code-smell-107-variables-reuse-3m53 %}

{% post https://dev.to/mcsee/code-smell-62-flag-variables-1a9p %}

# Refactorings
 
{% post https://dev.to/mcsee/refactoring-002-extract-method-1eee %}

# Credits

Photo by [Dustan Woodhouse](https://unsplash.com/@dwoodhouse) on [Unsplash](https://unsplash.com/s/photos/polluted)  

* * *

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

_Martin Fowler_
 
{% post https://dev.to/mcsee/software-engineering-great-quotes-26ci %}

* * *

This article is part of the CodeSmell Series.

{% post https://dev.to/mcsee/how-to-find-the-stinky-parts-of-your-code-1dbc %}