Avoid Kotlin destructuring declarations
Although destructuring declarations are so handy some times, we should not forget a very important issue that might arise a long period of time after writing it for first time.
A simple destructuring declaration
We have a very simple data class, the User
with two members in it (name
and surName
).
We are going to use the previous data class with destructuring declaration.
As expected the previous code snippet prints Hello Bill Tsapalos
. So far, so good but here comes the change!
Update data class structure
After a long time, when everyone has forgotten the previous implementation a new feature request arrives. This feature needs a new member (nickname
), so the data class is going to change into this:
Also we need to change our main
function. So, let’s change it because the compiler is going to complain about the parameters of the data class.
Compiler is not complaining anymore! So let’s try and run this change! Instead of printing Hello Bill Tsapalos
it is printing Hello Bill BILLyTheLiTTle
which obviously is going to raise an issue into an older feature! Why is this happening?
Behind the scenes
Every time we have a weird issue the only way to clear things up is to read the decompiled code. Let’s see what is the decompiled code of the first data class (with name
and surname
). The following snippet contains the decompiled declaration of the data class and the usage of the members of it.
Pay close attention to the componentX
methods. It seems that the 1st parameter of the data class (name
) is returned by the component1()
method. The surname
obviously is returned by component2()
. Let’s see the decompiled code of our feature implementation (data class with nickname
member) to see if we are correct with our assumptions.
As we suspected! The methods are generated by getting the position of the constructor parameters!component2()
method returns the nickname
! Now that we know what is going on we shall proceed with the fix!
What to NOT do
Your IDE is clever enough (but not a lot!) and it shows a warning!
But as I said, is not so clever. If you change the name of the variable in the destructuring declaration is not going to show to you anything!
As you can see there is no warning! So, you should not depend on your IDE no matter how clever it is!
What to do
The solution to this problem is really simple. Just avoid destructuring declarations. I assure you that your code is going to be readable and bulletproof!
The end
No matter what opportunities are provided to you by any new language you should prefer what you know better. Don’t use anything new because it is a trend, use what you need to have your job done!
More
Do you want to see more refactoring/design ideas? Here is the table of contents.