Kotlin Code Smell 3 - String Abusers
Yonatan Karp-Rudin
Posted on December 4, 2022
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
💖 💪 🙅 🚩
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.