DEV Community

Cover image for Code Smell 41 - Regular Expression Abusers
Maxi Contieri
Maxi Contieri

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

2 2

Code Smell 41 - Regular Expression Abusers

RegEx are a wonderful tool, we should to use them carefully and not to look smart.

Problems

  • Readability

  • Maintainability

  • Testability

  • Intention Revealing

Solutions

  1. Use regular expression just for string validation.

  2. If you need to manipulate objects, don't make them strings.

Sample Code

Wrong

val regex = Regex("^\\+(?:[0-9a-zA-Z][– -]?){6,14}[0-9a-zA-Z]$")
view raw smart.pl hosted with ❤ by GitHub

Right

val prefix = "\\+"
val digit = "[0-9]"
val space = "[– -]"
val phoneRegex = Regex("^$prefix(?:$digit$space?){6,14}$digit$")
view raw declarative.pl hosted with ❤ by GitHub

Detection

Regular expressions are a valid tool.
There's not much automated way of checking for possible abusers. A whitelist might be of help.

Tags

  • Primitive Obsession

  • Abusers

Conclusion

Regular expressions are a great tool for string validation. We must use them in a declarative way and just for strings.

Names are very important to understand pattern meanings.

If we need to manipulate objects or hierarchies, we should do it in an object way.

Unless we have a conclusive benchmark of impressive performance improvement.

Relations

More info

What is in a name

Credits

Photo by John Jennings on Unsplash


A Perl program is correct if it gets the job done before your boss fires you.

Larry Wall

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

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

Okay