Kotlin Code Smell 3 - String Abusers

yonatankarp

Yonatan Karp-Rudin

Posted on December 4, 2022

Kotlin Code Smell 3 - String Abusers

z8ol4jpeszi5wydtv1nj.png

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

Enter fullscreen mode Exit fullscreen mode

Right

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

class Location(
    val name: String
)

Enter fullscreen mode Exit fullscreen mode

Conclusion

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

Credits

💖 💪 🙅 🚩
yonatankarp
Yonatan Karp-Rudin

Posted on December 4, 2022

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related