In Java, should I be creating a new Package, Folder, or Source Folder?

eclipse, java

Solution

In a typical java eclipse project, you will have one or more source folders (for example one for app code, one for your unit tests).

Each folder contains a package tree, typically starting with your base package, for example `com.mycompany.myapp`.

In order to avoid name collisions, packages names are usually start with the domain name of the entity who is the author of the code, starting with the top-level-domain and going backwards (more general to more specific). That way, each class fully qualified name is unique. For example if google creates a class named `List`, it will be known as `com.google.List`, and it will not enter in conflict with the existing `java.util.List` interface.

You can have a unlimited number of packages inside this base package, for example :

com.mycompany.myapp.persistence
com.mycompany.myapp.domain
com.mycompany.myapp.services
com.mycompany.myapp.web

It all depends on your project and the way you want to organize your code and your classes.

At the logical level, packages are named with dots as separator. They contain java classes.

At the physical on disk level, each package is a directory. The java classes are contained in .java files (most frequently one class per file).

In Eclipse a "source folder" is a folder inside your project that is known to Eclipse to contain java source files. It will be compiled included in the output (for example JAR file) when you build your project.

In Eclipse, you usually view them at the logical level, showing packages. When you tell Eclipse to "create a new package", it will create the directory for you. For example, if you tell it to create the `com.mycompany.myproject` package, it will automatically create a `com` folder containing a `mycompany` folder containing a `myproject` folder.

Problem

There are a couple of questions on SO that sort of hit this, but I am totally new to Java development and I don't know the correct way to approach this. I have a C# solution, containing two projects (my app, and a unit test project) and within the app, most things are put into folders eg. Interfaces, Exceptions etc. I am trying to recreate this in Java / Eclipse, but I don't know how. I ended up with lots of packages, which sounds really bad. I also tried adding a source folder but that ended up being outside of the package. Could anyone point me in the right direction? Namely, which of those should I use to represent my unit test project/set of unit tests, and subfolders which exist just for organising stuff. Edit: It also says use of the default package is not advised. What should I be doing? Edit 2: Here is what it looks like. Does this look vaguely correct? My original C# solution is on the right.

Original source

Related problems