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

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay