Java Programming Practices – Is Using KDoc/Javadoc Comments Inside a Function Bad Practice?

documentationjavajavadocskotlinprogramming practices

I often find it helpful to use KDoc/Javadoc comments inside of a class or function instead of normal comments. IntelliJ colorizes them more obviously by default and, more importantly, allows hyperlinking to definitions. I'm wondering if it is considered bad practice to do so.

For example:

/**
 * Standard kdoc comment here...
 */
fun saveUser(user: User) {

    /**
     * Save the user to the [UserRepository]
     */
    userRepo.save(user)
}

In the inner comment, [UserRepository] will be linked to the type definition for that class. This example is a bit forced, but I often find it helpful in read code.

Best Answer

You ask "is it considered bad practice", and the answer is Yes.

But not so much because of using KDoc/Javadoc syntax in an inappropriate place, but because of the level of commenting. If you feel compelled to comment your code inside some method, think about rewriting it to achieve better readability.

In your example

fun saveUser(user: User) {

    /**
     * Save the user to the [UserRepository]
     */
    userRepo.save(user)
}

your comment is redundant. To any sane developer, userRepo.save(user) is perfectly readable as "save the user to the repository", so the comment can simply be deleted.

You talk about the linking possibilities. On the userRepo variable, any decent IDE will show you its declared type and let you navigate to the variable definition and to the class source, so this linking also isn't necessary (and it will only work with a non-standard IDE that accepts KDoc/Javadoc in places beyond the specification).

Of course, there might be situations where your comment isn't as trivial as in your example. But then, if your code is so obscure that it needs such a comment, you'd better rewrite it, or restructure it to call smaller methods with sensible names and the opportunity to add KDoc/Javadoc there.