Package structure for a Java project? - java

Whats the best practice for setting up package structures in a Java Web Application?
How would you setup your src, unit test code, etc?

You could follow maven's standard project layout. You don't have to actually use maven, but it would make the transition easier in the future (if necessary). Plus, other developers will be used to seeing that layout, since many open source projects are layed out this way,

There are a few existing resources you might check:
Properly Package Your Java Classes
Spring 2.5 Architecture
Java Tutorial - Naming a Package
SUN Naming Conventions
For what it's worth, my own personal guidelines that I tend to use are as follows:
Start with reverse domain, e.g. "com.mycompany".
Use product name, e.g. "myproduct". In some cases I tend to have common packages that do not belong to a particular product. These would end up categorized according to the functionality of these common classes, e.g. "io", "util", "ui", etc.
After this it becomes more free-form. Usually I group according to project, area of functionality, deployment, etc. For example I might have "project1", "project2", "ui", "client", etc.
A couple of other points:
It's quite common in projects I've worked on for package names to flow from the design documentation. Usually products are separated into areas of functionality or purpose already.
Don't stress too much about pushing common functionality into higher packages right away. Wait for there to be a need across projects, products, etc., and then refactor.
Watch inter-package dependencies. They're not all bad, but it can signify tight coupling between what might be separate units. There are tools that can help you keep track of this.

I would suggest creating your package structure by feature, and not by the implementation layer. A good write up on this is Java practices: Package by feature, not layer

The way I usually organise is
- src
- main
- java
- groovy
- resources
- test
- java
- groovy
- lib
- build
- test
- reports
- classes
- doc

I usually like to have the following:
bin (Binaries)
doc (Documents)
inf (Information)
lib (Libraries)
res (Resources)
src (Source)
tst (Test)
These may be considered unconventional, but I find it to be a very nice way to organize things.

The way i usually have my hierarchy of folder-
Project Name
src
bin
tests
libs
docs

One another way is to separate out the APIs, services, and entities into different packages.

Related

Use of modules within Java programming

Hopefully this is a question that only needs a fairly quick answer, but I haven't had much luck finding something online that is in terms I understand!
Quite simply, I'm working on my first real project in Java, a text adventure, (using IntelliJ IDEA) and I was just wondering if I need to be splitting my code into modules? So, for my monsters, should I keep all of my monster classes within a module called Monsters, or can I just keep it in the same module?
I only ask because; a) I wasn't sure whether it was a done thing in order to keep the project tidy and b) When I tried to create a Monster module, I received a warning telling me that the files in this module wouldn't be accessible from the rest of the program, which seems to defeat the object to me...
Many thanks in advance for any advice!
I believe you are referring to IntelliJ's concept of a module. As stated on their page:
A module is a discrete unit of functionality which you can compile, run, test and debug
independently.
Modules contain everything that is required for their specific tasks:
source code, build scripts, unit tests, deployment descriptors, and
documentation. However, modules exist and are functional only in the
context of a project.
So, modules should not be referencing the source code from other modules. They should essentially be completely different units.
As in thecbuilder's answer, you should look into using Java's packaging system instead.
By modules if you mean packages, then its a good habit to keep related classes in one package and distributing unrelated classes in different packages.
And to the thing, that the classes wouldn't be accessible, you'll have to make them public to access them from different packages.
More on package structuring :
http://www.javapractices.com/topic/TopicAction.do?Id=205
http://docs.oracle.com/javase/tutorial/java/package/namingpkgs.html
https://stackoverflow.com/a/3226371/3603806
For access specifiers :
Taken from : http://www.go4expert.com/articles/java-access-specifiers-t28019/

Java package understanding in real life projects

I want to understand the packing methodology in real big projects.
Suppose we have a package com.abc.xyz, and for this, we really have a path like com/abc/xyz.
Is it possible to have multiple same package names in different directory structure like:
Directory path 1:
/home/user1/project/module1/src/java/com/abc/xyz
Directory path 2:
/home/user1/project/module2/src/java/com/abc/xyz
And finally when we create jar for the whole project, do we create jar with respect to com directory?
When some application uses import com.abc.xyz, how does it know which directory path's package it is referring to?
And finally, is there any good book/resource which gives guidelines about packaging, how to divide project into modules, package names etc.
One more thing, does a project have common package base name like in above case:
com.abc.xyz (e.g., org.apache.hadoop ).
Thanks,
Vipin
Packages created in different source directories are the same package, as far as the classloader is concerned. It also doesn't matter if the class files are in the same jar or different jars. The JVM does not discriminate based on where the source code came from.
(Of course if you have two jars loaded by different classloaders those are going to be treated differently.)
One case where you frequently have different source trees with the same package is when you have tests in a different directory (using the usual Maven convention where the code is under src/main/java and the tests are in src/test/java) but with the same package as the code that they exercise. These tests are able to exercise protected and package-private parts of the code under test, because they're in the same package as that code.
The path of directories inside the jar should start at the root of the package. (The topmost directory should be /, then one called com or org or whatever, etc.) Packages do form a tree-like structure, and when you put your code in a filesystem you end up having a hierarchy of packages, but the language itself doesn't recognize a concept of "subpackage" (except that packages that start with java are special and get special treatment by the classloader).
Organizing code into packages is done differently by different people. Some people like to organize their code by layer (putting all controllers in one package, all services in another package, all daos in still another package), some like to organize their code by feature.
Package-by-layer is the conventional way of organizing code, it seems to be the preferred practice in the Java community. One consequence of this is that when code implements a feature as a vertical slice at right angles to the package structure (as it may require a new controller endpoint, maybe a new service method, etc.), so closely-related bits of code for the same feature end up scattered across different directories. The Java Practices website makes an interesting case for package-by-feature:
Package By Feature Package-by-feature uses packages to reflect
the feature set. It tries to place all items related to a single
feature (and only that feature) into a single directory/package. This
results in packages with high cohesion and high modularity, and with
minimal coupling between packages. Items that work closely together
are placed next to each other. They aren't spread out all over the
application. It's also interesting to note that, in some cases,
deleting a feature can reduce to a single operation - deleting a
directory. (Deletion operations might be thought of as a good test for
maximum modularity: an item has maximum modularity only if it can be
deleted in a single operation.)
Here's an SO question asking about package by feature or layer.
Yes, you could make duplicate packages in separate directories, but I can't think of a good reason to do it. If the classes within the package have the same names you can certainly get namespace collisions. I am not sure what "module" means in this context but I'd recommend
com.abc.module1.xyz
com.abc.module2.xyz
instead. Those would be distinct packages to the classloader. You can still keep your /home/user1/project/module1/ directory structure up front, that doesn't matter.
From 2 modules you will have two seperate jar files: module1.jar and module2.jar. Both will be loaded into ClassLoader when application starts.
When some application uses import com.abc.xyz, how does it know which directory path's package it is referring to?
Classloader will handle that. http://www.javaworld.com/article/2077260/learn-java/the-basics-of-java-class-loaders.html
If you trying to develop multi module application i recommend you to check Maven tool:
http://maven.apache.org/‎
Why maven? What are the benefits?
For guidance for package organization you can just google 'java packages' phrase.
http://www.tutorialspoint.com/java/java_packages.htm
https://www.facebook.com/Niranthara-Jaya-JavaSocial-Media-Apps-Software-Project-Management-244119296136021/
This page is for people who wish to know how to work with real world Java projects. Send a message to this page and check out the articles.

What is a good practice to combine your classes

Not to keep all my classes in a single src -> 'package_name' folder I'm creating different sub-packages in order to separate my classes by groups like - utilities, models, activities themselves, etc. I'm not sure if it is a good practice and people do the same in real projects.
Yes, it's definitely standard practice to separate your classes into packages. It's good to establish a convention for how they are separated, to make it easier to find things later. Two common approaches:
Put things into packages based on what they are: model, service, data access (DAO), etc.
Put things into packages based on what function they support (for example, java.io, java.security, etc.
I've used both and keep coming back to the former because it's less subjective (it's always clear whether a class is a model or a service, but not always clear whether it supports one function or another function).
Doing it by class type the way you describe is one way that I've seen in real projects. I don't care for it as much as I used to because when I need to make a change or add a feature I tend to need to have several packages expanded in my IDE. I prefer (when I have the choice) to group classes by feature instead. That way I know where to look for all classes that support that feature.
The convention I prefer is to group classes first by module, then by functionality. For example, you could have the following structure:
com.example.modulea - modulea specific code that doesn't have any real need of a different package
com.example.modulea.dao - data access for module a
com.example.modulea.print - printing for module a
...
com.example.moduleb - moduleb specific code that doesn't have any real need of a different package
com.example.moduleb.dao - data access for module b
com.example.moduleb.print - printing for module b
In this fashion, code is clearer by package.
In the other style, of grouping by pure functionality, the package size tends to be quite large. If your project contains 15 modules, and each module has one or more elements per package, that's at least 15 classes per package. I much prefer clearly separated packages than packages that simply group things because "oh here are some printing utilities that are used for every module but only one module actually uses one of them from this package" - it just gets confusing.

Do you follow any guidelines (java) in packaging?

Do you follow any design guidelines in java packaging?
is proper packaging is part of the design skill? are there any document about it?
Edit : How packages has to depend on each other?, is cyclic packages unavoidable?, not about jar or war files.
My approach that I try to follow normally looks like this:
Have packages of reasonable size. Less then 3 classes is strange. Less then 10 is good. More then 30 is not acceptable. I'm normally not very strict about this.
Don't have dependency cycles between packages. This one is tough since many developers have a hard time figuring out any way to keep the dependencies cycle free. BUT doing so teases out a lot of hidden structure in the code. It becomes easier to think about the structure of the code and easier to evolve it.
Define layer and modules and how they are represented in the code. Often I end up with something like <domain>.<application>.<module>.<layer>.<arbitrary substructure as needed> as the template for package names
No cycles between layers; no cycles between modules.
In order to avoid cycles one has to have checks. Many tools do that (JDepend, Sonar ...). Unfortunatly they don't help much with finding ways to fix cycles. That's why I started to work on Degraph which should help with that by visualizing dependencies between classes, packages, modules and layer.
Packaging is normally about release management, and the general guidelines are:
consistency: when you are releasing into integration, pre-production or production environment several deliveries, you want them organized (or "packaged") exactly the same way
small number of files: when you have to copy a set of files from one environment to another, you want to copy as many as possible, if their number is reasonable (10-20 max per component to deliver), you can just copy them (even if those files are important in size)
So you want to define a common structure for each delivery like:
aDelivery/
lib // all jar, ear, war, ...
bin // all scripts used to launch your application: sh, bat, ant files, ...
config // all properties files, config files
src // all sources zipped into jars
docs // javadoc zipped
...
Plus, all those common directory structures should be stored into one common repository (a VCS, or a maven repo, or...), in order to be queried, without having to rebuilt them every time you need them (you do not need that if you have only one or two delivery components, but when you have 40 to 60 of them... a full rebuilt is out of the question).
You can find a lot of information here:
What strategy do you use for package naming in Java projects and why?
The problem with packaging in Java is that it has very little relation to what you would like to do. For example, I like following the Eclipse convention of having packages marked internal, but then I can't define their classes with a "package" protection level.

How do I organize my java packages in our web mvc project?

Do you have any good tips on how should i organize class packages for my java project?
We are usually building web MVC projects and our structure is something like this
com.company.project.model.* - all model classes
com.company.project.service.* - all service classes
com.company.project.service.entity.* - service classes related to particular model class
com.company.project.service.dao.* - dao classes
this seems somehow smelly tho...
When using a modern IDE, it probably won't make much difference to the developer - personally I add the package the first time I need it using Eclipse, and forget about it afterwards. From a performance perspective, you don't gain anything by listing only the classes you need - using the * notation does not result in more memory used or slowing down of the application.
we also do it the lazy way, just add a package if you need one, i think you´ll find a class faster if you have more packages...

Categories

Resources