DEV Community

Yonatan Karp-Rudin
Yonatan Karp-Rudin

Posted on • Originally published at yonatankarp.com on

1

Kotlin Code Smell 29 - Taming the RegEx Beast for Cleaner Code

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()

Enter fullscreen mode Exit fullscreen mode

Right

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

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.


I hope you enjoyed this journey and learned something new. If you want to stay updated with my latest thoughts and ideas, feel free to register for my newsletter. You can also find me on LinkedIn or Twitter. Let's stay connected and keep the conversation going!


Credits

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more