Skip to main content

Command Palette

Search for a command to run...

Kotlin Code Smell 29 - Regular Expression Abusers

From Spaghetti Code to Readable Magic

Updated
1 min read
Kotlin Code Smell 29 - Regular Expression Abusers
Y

I've started to work as a software engineer at 2014, however, I started to write code at high-school.

My first language was Assembly, but still, I fall in love with the possibilities to make the computer to do as you wish, shortly after that I started to write in C.

Later on I studied a practical engineering in electricity, and during this time discovered that I preferred much more writing code than design electrical components.

As a result of this understanding I decided to switch and study bachelor degree in computer science in Reichman university, where the focus was of the Java language.

Today I'm working at SumUp using Kotlin, SpringBoot & Micronaut, Cassandra and Kafka

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

Problem

  • Readability

  • Maintainability

  • Testability

  • Intention Revealing

Solution

  1. Use regular expressions just for string validation.

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

Sample Code

Wrong

val regex = "^\\+(?:[0-9a-zA-Z][– -]?){6,14}[0-9a-zA-Z]$".toRegex()

Right

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

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.

Credits

Kotlin Code Smells

Part 8 of 36

In this series, we will see several symptoms and situations that make us doubt the quality of our development. We will present possible solutions. Most are just clues. They are no hard rules.

Up next

Kotlin Code Smell 28 - Abstract Names

Unleashing the Magic of Meaningful Naming

More from this blog

Yonatan Karp-Rudin | kotlin for backend developer skills | java for backend developer skills | SpringBoot | Tutorials

57 posts

Experienced Senior Software Engineer passionate about functional programming & Kotlin. Excels in app development, optimization, and team collaboration. Let's create something amazing!