Kotlin Code Smell 3 - String Abusers
Cut the Strings: Embrace Objects for Simpler, Readable, and Maintainable Code
Play this article
Table of contents
TL;DR: Use actual objects and abstractions instead of random string manipulation.
Problems
Complexity
Readability
Maintainability
Lack of Abstractions
Solutions
Utilize objects instead of strings.
Replace strings with data structures that handle object relations.
Identify bijection problems between real objects and 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
Avoid excessive reliance on strings. Prioritize actual objects. Establish clear protocols to differentiate them from strings.