DEV Community

Yonatan Karp-Rudin
Yonatan Karp-Rudin

Posted on • Originally published at yonatankarp.com on

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

Top comments (0)