Skip to content

Latest commit

 

History

History
97 lines (53 loc) · 3.03 KB

File metadata and controls

97 lines (53 loc) · 3.03 KB

Code Smell 41 - Regular Expression Abusers

Code Smell 41 - Regular Expression Abusers

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

TL;DR: Avoid regular expressions as much as possible.

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]$")

Right

val prefix = "\\+"
val digit = "[0-9]"
val space = "[– -]"
val phoneRegex = Regex("^$prefix(?:$digit$space?){6,14}$digit$")

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

Code Smell 06 - Too Clever Programmer

Code Smell 20 - Premature Optimization

Code Smell 121 - String Validations

Code Smell 185 - Evil Regular Expressions

More Info

What exactly is a name - Part I The Quest

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

Software Engineering Great Quotes


This article is part of the CodeSmell Series.

How to Find the Stinky Parts of your Code