Yonatan Karp-Rudin
Yonatan Karp-Rudin

Follow

Yonatan Karp-Rudin

Follow
Kotlin Code Smell 003 - String Abusers

Photo by Sven Brandsma on Unsplash

Kotlin Code Smell 003 - String Abusers

Too many parsing, exploding, regex, strcomp, strpos, and string manipulation functions.

Yonatan Karp-Rudin's photo
Yonatan Karp-Rudin
·Dec 2, 2022·

1 min read

Play this article

Table of contents

  • Problems
  • Solutions
  • Examples
  • Sample Code
  • Conclusion
  • Credits

TL;DR: Use real abstractions and real objects instead of string accidental manipulation.

Problems

  • Complexity

  • Readability

  • Maintainability

  • Lack of Abstractions

Solutions

  • Work with objects instead of strings.

  • Replace strings with data structures dealing with object relations.

  • Find Bijection problems between real objects and the strings.

Examples

  • Serializers

  • Parsers

Sample Code

Wrong

val schoolDescription = "College of Springfield"

// location = "Springfield"
val location = """[^ ]*\$""".toRegex()
    .find(schoolDescription)?.value

// school = "College"
val school = """^[\w]+""".toRegex()
    .find(schoolDescription)?.value

Right

class School(
    private val name: String,
    private val location: Location
) {
    fun description() = "$name of ${location.name}"
}

class Location(
    val name: String
)

Conclusion

Don't abuse strings. Favor real objects. Find absent protocol to distinguish them from strings.

Credits

 
Share this