I hate "it"

In principle it is a nice thing to avoid repetitive local parameters. It is a perfect tool for one-liners like

items.filter { it.size > 10 }

But after reading lots of code with overused it in much too large code blocks, I’m thinking that it does more harm than good. Maybe it should be added to the coding conventions that it should only be used for single or maybe two line functions.

What do you think?

4 Likes

In
https://kotlinlang.org/docs/reference/coding-conventions.html#lambda-parameters

It already says so:

In lambdas which are short and not nested, it's recommended to use the `it` convention instead of declaring the parameter explicitly. In nested lambdas with parameters, parameters should be always declared explicitly.

7 Likes

First let me say I love the title of this topic :wink:
On a more serious note, I think I mostly agree with you. In my experience this just happens naturally. I just did a quick search for “it” in a current project and I couldn’t really find any uses of “it” in functions that are longer than a few lines. I would say that 2 is to few though. I’m fine with “it” being used if the block is at most 5-10 lines long. That way you always see where it is declared and you can easily see the context of it. Anything more is definelty to much.
I think this is more an issue for code reviews. Is this name meaningful enough for the number of uses. A temp varaible that only has a scope of a line or 2 can have a much weaker name than a value that is in use for much longer. I don’t think there are any easy to follow rules here that can solve a subjective issue like this except “use good varaible names”.

4 Likes

Kotlin is optimized for the looks, it is not the only place where the language gives you a very easy option to make your code less readable.

And it’s not difficult to understand why. Were it not for the cool syntax, there would be no substantial difference with Java, no raison d’etre!

Well… null safety is a sufficient ‘raison d’être’.
But sure, extension functions, context programming and coroutines are useless.
And the fact thzt recent jeps introduce things such as records, improved switches, sealed classes (oh yeah) shows that kotlin introduced nothing valuable… please, do not make hasty responses that add nothing to the debate.

You can argue that “it” hurts readability, but so does long lambdas. And in this matter, java is not better than kotlin. Nothing can protect you from “hype”, whatever language. What you can do is use tools to add constraints over programming style that suits you better (like checkstyle, spotbug, etc). Tooling.

3 Likes

I guess that using custom linter rule (e.g. for AS/IDEA) you can ban using it in your team or project if you think that it’s harmful. I’m following coding conventions and never had issues with it.