Report package not matching directory structure

description of the Rule

Unlike in Java, the Kotlin compiler only consider the package declared in the file (using the package keyword) and don’t consider the directory structure in which the file is located.

For instance a file located in org/myorg/main/File.kt can start with:

package com.github.somethingelse

And the latest only is valid for usage in imports.

How can it happen?

  • When one copy a file, it is easy to forget to change the package declaration.
  • When reorganizing a project structure, because we move a lot of files, we can easily end-up with package not matching the
  • When creating a file from scratch, one may not write the package declaration.

If the IDE does help in most of the situation, it is far from perfect, and having package not-matching the directory structure does happen from time to time.

Why is it a problem?

  1. It is against the conventions
  2. It is confusing when the import we have to do doesn’t match the directory structure we see. It may lead to compile-time problem difficult to understand.
  3. We may not notice that we have types in the default-package. And that sometime lead to error or bug when using some technologies.

Snippet of Noncompliant Code

File org/myorg/main/File.kt

package demo

fun foo() {
}

Snippet of Compilant Code (fixing the above noncompliant code)

File org/myorg/main/File.kt

package org.myorg.main

fun foo() {
}

External references and/or language specifications

Official Kotlin conventions: https://kotlinlang.org/docs/reference/coding-conventions.html#directory-structure

Type : Code Smell

It is confusing.

I would personally set the default severity to “Minor”

Tags

convention

Thank you very much, @jcornaz, for the effort put into specifying this rule. We will come up with a follow-up message once we evaluate all the rules you have suggested.