DEV Community

Cover image for Code Smell 04 - String Abusers
Maxi Contieri
Maxi Contieri

Posted on • Edited on • Originally published at maximilianocontieri.com

2 1

Code Smell 04 - String Abusers

Too many parsing, exploding, regex, strcomp, strpos and string manipulation functions.

TL;DR: Use real abstractions and real objects instead of string accidental manipulation.

Problems

  • Complexity
  • Readability
  • Maintainability
  • Lack of Abstractions

Solutions

1) Work with objects instead.

2) Replace strings with data structures dealing with object relations.

3) Go back to Perl :)

4) Find Bijection problems between real objects and the strings.

Examples

-Serializers

-Parsers

Sample Code

Wrong

<?

$schoolDescription = 'College of Springfield';

preg_match('/[^ ]*$/', $schoolDescription, $results);
$location = $results[0]; // $location = 'Springfield'.

$school = preg_split('/[\s,]+/', $schoolDescription, 3)[0]; //'College'
Enter fullscreen mode Exit fullscreen mode

Right

<?

class School {

    private $name;
    private $location;

    function description() {
        return $this->name . ' of ' . $this->location->name;
    }

}
Enter fullscreen mode Exit fullscreen mode

Detection

Automated detection is not easy. If code uses too many string functions, it can trigger a warning.

Relations

  • Primitive Obsession

More info

Tags

  • Mapping

Conclusion

Don't abuse strings. Favor real objects. Find absent protocol to distinguish them from strings.

Credits

Photo by Nathaniel Shuman on Unsplash


This article is part of the CodeSmell Series.

Last update: 2021/06/03

Hot sauce if you're wrong - web dev trivia for staff engineers

Hot sauce if you're wrong · web dev trivia for staff engineers (Chris vs Jeremy, Leet Heat S1.E4)

  • Shipping Fast: Test your knowledge of deployment strategies and techniques
  • Authentication: Prove you know your OAuth from your JWT
  • CSS: Demonstrate your styling expertise under pressure
  • Acronyms: Decode the alphabet soup of web development
  • Accessibility: Show your commitment to building for everyone

Contestants must answer rapid-fire questions across the full stack of modern web development. Get it right, earn points. Get it wrong? The spice level goes up!

Watch Video 🌶️🔥

Top comments (0)

Dev Diairies image

User Feedback & The Pivot That Saved The Project

🔥 Check out Episode 3 of Dev Diairies, following a successful Hackathon project turned startup.

Watch full video 🎥

👋 Kindness is contagious

Embark on this engaging article, highly regarded by the DEV Community. Whether you're a newcomer or a seasoned pro, your contributions help us grow together.

A heartfelt "thank you" can make someone’s day—drop your kudos below!

On DEV, sharing insights ignites innovation and strengthens our bonds. If this post resonated with you, a quick note of appreciation goes a long way.

Get Started