Code Smell 66 - Shotgun Surgery

Code Smell 66 - Shotgun Surgery

Say it only once

Maxi Contieri
·Apr 5, 2021·

2 min read

Subscribe to my newsletter and never miss my upcoming articles

Play this article

Table of contents

  • Problems
  • Solutions
  • Sample Code
  • Detection
  • Tags
  • Conclusion
  • More info
  • Credits

Problems

  • Bad Responsibilities Assignments

  • Code Duplication

  • Maintainability

  • Single Responsibility Violation.

  • Copy-pasted code.

Solutions

  1. Refactor

Sample Code

Wrong

<?

final class SocialNetwork {

    function postStatus(string $newStatus) {
        if (!$user->isLogged()) {
            throw new Exception('User is not logged');
        }
        ///...
    }

    function uploadProfilePicture(Picture $newPicture) {
        if (!$user->isLogged()) {
            throw new Exception('User is not logged');
        }
        ///...
    }

    function sendMessage(User $recipient, Message $messageSend) {
        if (!$user->isLogged()) {
            throw new Exception('User is not logged');
        }
        ///...
    }
}

Right

<?

final class SocialNetwork {

    function postStatus(string $newStatus) {
        $this->assertUserIsLogged();
        ///...
    }

    function uploadProfilePicture(Picture $newPicture) {
        $this->assertUserIsLogged();
        ///...
    }

    function sendMessage(User $recipient, Message $messageSend) {
        $this->assertUserIsLogged();
        ///...
    }

    function assertUserIsLogged() {
        if (!$this->user->isLogged()) {
            throw new Exception('User is not logged');
            //This is just a simplification to show the code smell
            //Operations should be defined as objects with preconditions etc.
        }
    }
}

Detection

Some modern linters can detect repeated patterns (not just repeated code) and also while performing our code reviews we can easily detect this problem and ask for a refactor.

Tags

  • Code Duplication

Conclusion

Adding a new feature should be straightforward it our model maps 1:1 to real world and our responsibilities are in the correct places. We should be alert for small changes spanning in several classes.

More info

Credits

Photo by William Isted on Unsplash


Duplication is the primary enemy of a well-designed system.

Robert Martin



This article is part of the CodeSmell Series.

 
Share this

Impressum

Technical Opinions are my own. I don't have the revealed truth.

Software Design is a creative activity. These are hints and not rigid rules.

I write on BackEnd Business Systems and OOP Design. My advice/experience might not suit other systems.

You can write me at info(at)maximilianocontieri.com