ILikeTrains
ILikeTrains

Reputation: 73

Does it make sense to have the same package statement, even if the files are in different folders?

So imagine this folder structure.

main\
  \pack1
    a\A.java
    b\B.java

A.java is not in the same folder as B.java. But both have the same package statement as following:

package main.pack1;

With that package statement, they have no compiler error, if i try to access protected fields from each other. If I have the package statement as following:

package main.pack1.a;
package main.pack1.b;

for the two Files respectivly, I cannot access the protected fields of each other, as expected.

The question is, is it good practice to group classes from different folders into one package?

I want to structure the .java files in a folder structure, for better organisation (so that i dont have like 20 files in one folder), but they should be in the same package, for usage of protected fields.

I hope its clear, what im asking.

Upvotes: 0

Views: 76

Answers (1)

E-Riz
E-Riz

Reputation: 32914

There is no requirement from the standard javac compiler for any specific organization of source code files, but if your folder structure doesn't mirror the package structure you would be violating a (practically) universal convention. Reasons you would not want to do that include:

  • It violates the Principle of Least Surprise for any developer who will ever look at the code.
  • Most IDEs will flag it as a warning (or possibly an error, depending on how the tool is configured). Eclipse and Intellij, specifically, flag it in their default configurations. Developers should strive to minimize warnings in their code, since having lots of noise in the warnings can mask real, legitimate problems that should be addressed.
  • There are likely some tools that do require the folder structure to mirror the package structure. If you ever go to apply such a tool to your code base, it will be a pain to fix.
  • If a package gets too "big" or "full" then there's usually an obvious way to break the package itself down into sub-packages, such that the corresponding folders are also less "full."
  • The horse's mouth urges you to follow the convention.

tl;dr : Conventions exist for a reason, and usually it's best to follow them unless there is an ovewhelming reason to go against the grain. Such cases exist, but "I don't like 20 files in one folder" wouldn't be one of them IMNSHO.

Upvotes: 1

Related Questions