cover-img

Code Smell 46 - Repeated Code

DRY is our mantra. Teachers tell us to remove duplication. We need to go beyond

28 January, 2023

3

3

2

Problems

Solutions

  1. Find repeated patterns (not repeated code).
  2. Create an abstraction.
  3. Parametrize abstraction calls.
  4. Use composition and never inheritance.
  5. Unit test new abstraction.

Examples

Sample Code

Wrong

<?

final class WordProcessor {

function replaceText(string $patternToFind, string $textToReplace) {
$this->text = '<<<' . str_replace($patternToFind, $textToReplace, $this->text) . '>>>';
}
}

final class Obfuscator {

function obfuscate(string $patternToFind, string $textToReplace) {
$this->text = strlower(str_ireplace($patternToFind, $textToReplace, $this->text));
}
}

Right

<?

final class TextReplacer {
function replace(string $patternToFind, string $textToReplace, string $subject, string $replaceFunctionName, $postProcessClosure) {
return $postProcessClosure($replaceFunctionName($patternToFind, $textToReplace, $subject));
}
}

// Lots of tests on text replacer so we can gain confidence.

final class WordProcessor {

function replaceText(string $patternToFind, string $textToReplace) {
$this->text = (new TextReplacer())->replace($patternToFind, $textToReplace, $this->text, 'str_replace', fn($text) => '<<<' . $text . '>>>');
}
}

final class Obfuscator {

function obfuscate(string $patternToFind, string $textToReplace) {
$this->text = (new TextReplacer())->replace($patternToFind, $textToReplace, $this->text, 'str_ireplace', fn($text) => strlower($text));
}
}

Detection

Linters can find repeated code.

There are not very good finding similar patterns.

Maybe soon machine learning will help us find such abstractions automatically.

For now, it is up to us, humans.

Tags

  • Duplication

Conclusion

Repeated code is always a smell.

Copying and pasting code is always a shame.

With our refactoring tools, we need to accept the duplication removal challenge trusting our tests as a safety net.

Relations

Code Smell 11 - Subclassification for Code Reuse

More Info

Laziness II - Code Wizards

%[https://en.wikipedia.org/wiki/Copy_and_paste_programming]

https://deepdive.hashnode.dev/dry-dont-repeat-yourself

Credits

Photo by Sid Balachandran on Unsplash

  • * *
Copy and paste is a design error.

David Parnas

  • * *

Software Engineering Great Quotes

  • * *

This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code

3

3

2

Maxi Contieri

Buenos Aires, Argentina

🎓Learn something new every day.📆 💻CS software engineer 👷coding👨🏽‍🏫teaching ✍🏾writing 🎨Software Design 🏢SOLID 🌉TDD 👴Legacy 💩Code Smells

More Articles

Showwcase is a professional tech network with over 0 users from over 150 countries. We assist tech professionals in showcasing their unique skills through dedicated profiles and connect them with top global companies for career opportunities.

© Copyright 2024. Showcase Creators Inc. All rights reserved.