Codementor Events

Kotlin exposes internal implementation of objects

Published Apr 03, 2017

There is a lot of articles about why android developers should use Kotlin instead of Java.
It definitely requires less boilerplate and a code is more readable, It allows tons of great features, and I use it as well.
But today I’ll write about biggest Kotlin disadvantage I see so far.

And it’s not about default final classes, it’s about encapsulation problems and about the king of SOLID principles – single responsibility.

Let’s take a look at an example. I’m writing an app, that takes flight information and generates flight plan request according to air traffic control rules.
I have a class, responsible for providing flight information

data class FlightData(
val fleetSize: Int,
val radius: Float,
val startDate : Date = Date(),
val finishDate : Date,
val speedKmH : Int,
val localOperatorPoint : String,
val pilotPhoneNumber: String,
val pilotFamilyName: String,
val amountWithPassengers: Int
)

Then we will use data from this object in RequestGenerator like this

sb.append(" ЕЕТ/")
sb.append(data.localOperatorPoint)
sb.append("0001")

later, I will probably change the internal structure of FlightData class – it will contain location description object, that will contain information about the location and localOperatorPointIndex, instead of separate fields.
From Uncle Bob’s Clean Code book we know, that objects should hide internal implementation but provide behavior.
And in Java, we will not change any classes, that uses flight data. We will keep changes internally to FlightData object.
But because of property access syntax in Kotlin, we dispose internal implementation of our classes in sources (at compile time they will generate getters), and now I have to change all the places FlightData was used, just because of internal FlightData changes.

Of cause, we still can write getters manually and hide values, and use getters access. But language doesn't counsel us to do so. Instead, by default IntelliJ will advise us to use property access syntax over of getters by highlighting lint warnings.

Discover and read more posts from Dmitry
get started