Refactoring 013 - Remove Repeated Code
Tags: webdev, beginners, programming, tutorial
Published: 2024-06-16 01:37:23

*Don't Repeat Yourself*

> TL;DR: How to remove repeated code	     

# Problems Addressed

- Don't Repeat Yourself

- Copy/Paste Programming

- No single source of truth

# Related Code Smells

{% post https://dev.to/mcsee/code-smell-46-repeated-code-4iib %}

{% post https://dev.to/mcsee/code-smell-11-subclassification-for-code-reuse-1136 %}

{% post https://dev.to/mcsee/code-smell-232-reusable-code-44p5 %}

# Context

Duplicated code is a severe code smell, it leads to maintainability problems and ripple effects.

Start by identifying behavior duplication.

Once you find it, you will extract it into reusable functions or classes, reducing redundancy, creating a single source of truth, and simplifying future updates.

Behavior duplication is a sign of a missing abstraction you need to create. 

As always, you should search for it in the real world.

Refactoring isn't a one-time event; it's an ongoing process that should be integrated into your development workflow. 

# Steps

1.  Make a contextual copy of the repeated code

2. Parametrize what is different

3. Invoke the abstraction
 
4. Find a real-world metaphor for the abstraction

*(This is the harder and not mechanical step)*

# Sample Code

*(This is actual code generated by Google Gemini)

See a complete explanation in this [talk](https://dev.to/mcsee/clean-code-with-ai-4kck)*

## Before

[Gist Url]: # (https://gist.github.com/mcsee/4faa40928a8ac53cca2d1381c8a2e1c2)

```php
<?php

class AccessControlPanel {

  private $users = [];

  public function createRegularUser($username, $password, $email) {
    $user = [
      "username" => $username,
      "email" => $email,
      "type" => $this->regularUserRole(),
      "creationDate" => $this->timeSource->currentTimestamp(),
      "needsToChangePassword" = $this->needsToChangePassword(),
      "loginPolicy" => $this->userLoginPolicy()
    ]
    $this->users[] = $user;
    $this->addCreationToJournal($user);
  }
  
   public function createAdminUser($username, $password, $email) {
    $user = [
      "username" => $username,
      "email" => $email,
      "type" => $this->regularUserRole(),
      "creationDate" => $this->timeSource->currentTimestamp(),
      "needsToChangePassword" = $this->needsToChangePassword(),
      "loginPolicy" => $this->adminUserLoginPolicy()
    ]
    $this->users[] = $user;
    $this->addCreationToJournal($user);
    return $user;
  }
} 

?>
```

## After

[Gist Url]: # (https://gist.github.com/mcsee/9c90a11f4488bfbeded051d6e1be596a)

```php
<?php

class AccessControlPanel {

  private $users = [];

  // 1.  Make a contextual copy of the repeated code
  
  private function createUser(
     $username, 
     $password,
     $email, 
     $role, 
     $loginPolicy) {
    $user = [
      "username" => $username,
      "email" => $email,
      "type" => $role,
      "creationDate" => $this->timeSource->currentTimestamp(),
      "needsToChangePassword" => $this->needsToChangePassword(),
      "loginPolicy" => $loginPolicy
    ];
    $this->users[] = $user;
    $this->addCreationToJournal($user);
    return $user;
  }
  
  // 2. Parametrize what is different (in this case $role and $loginPolicy)

  public function createRegularUser($username, $password, $email) {
    // 3. Invoke the abstraction
    return $this->createUser(
      $username,
      $password,
      $email, 
      $this->regularUserRole(),
      $this->userLoginPolicy());
  }

  public function createAdminUser($username, $password, $email) {
    return $this->createUser(
      $username,
      $password,
      $email,
      $this->adminUserRole(), 
      $this->adminUserLoginPolicy());
  }
  
  // 4. Find a real-world metaphor for the abstraction
  // private function createUser(
  // $username, 
  // $password,
  // $email, 
  // $role, 
  // $loginPolicy)
}

?>
```

# Type

[X] Semi-Automatic

The steps are defined but sometimes not about text duplication, but behavior duplication.

# Safety

Since this is not a mechanical refactoring, you need good coverage on the code you modify.

# Why is the code better?

You have a single source of truth, more compact code, and an easier-to-maintain solution.

# Tags

- Coupling

# Related Refactorings

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

{% post https://dev.to/mcsee/refactoring-003-extract-constant-4j5p %}

{% post https://dev.to/mcsee/refactoring-007-extract-class-18ei %}

{% post https://dev.to/mcsee/refactoring-010-extract-method-object-3ff8 %}

# Credits

Imagen de <a href="https://pixabay.com/en/users/rachealmarie-3893509/">Rachealmarie</a> en <a href="https://pixabay.com/en//">Pixabay</a>

* * * 

This article is part of the Refactoring Series.

{% post https://dev.to/mcsee/how-to-improve-your-code-with-easy-refactorings-2ij6 %}