Java package understanding in real life projects - java

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.

Related

Inspection to separate one java package from the rest of the project

I have a java package foo.bar. It contains few classes, that are frequently modified, improved etc in this time of project.
I don't want any developer to use classes from the other packages in this one. I want this package to be separated in its usage. So this package must be isolated.
I could make an external jar, but that would introduce much more handling for little number of classes, that it does not make sense.
I want this inspection to be run from my build process.
I tried several code-inspection tools (pmd...) but I was not able to configure this. How to do this?

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 files on the same folder and on the same package

At least on my machine when I put 2 Java class files on the same folder, without making them part of the same package, they already see one another, so from one file I can call a public class from the other file and vice-versa.
Questions:
Is this the general case or a coincidence that may not work on every platform?
If this is not a coincidence, I am guessing the purpose of packages is to allow you to organize your class files and make they share stuff, even if they are spread across different folders and paths. Is this correct or I am missing something?
If no package name is specified, the classes in the file go into a special unnamed package. And this is the same case for all files with no explicit package specification. Hence, they all fall into the special unnamed package, and exhibit the behavior that you are seeing.
You might want to go through this for a better understanding.
If they're in the same directory then they're in the same package, or are you copying .class files around after they've been written by the compiler?
Packages are a way of organising classes into a namespace. There are plenty of reasons to do this, the best bet is to start with the tutorial.
I sure it is general case, but it is bad approach.
You are right, but more general reason to use package is to separate namespaces, for example, you have to create Car class, but there are many people who want to use this classname, thats why you have to use package, for example: com.yourcompany.yourproject. In such case you can use your Car class from your package without implicitly defining package and you also can use other Car classes in such manner: new com.google.general.Car();
In the java rules, it is recommend to use domain name right-to-left for providing unique package name.

Why do Java sources have so many folders inside each other?

Every time I look at some Java source code, I find myself surfing in a folder that has folder that has folder that has folder in it etc. Why does Java require so many nested folders, which have nothing else in them except the new subfolder?
For example:
https://github.com/halfninja/android-dragcontrol3d/tree/master/src/uk/co/halfninja/android
That's probably not the worst example, but there are two folders "uk" and "co" that just don't make sense. I see this in Java sources only!
And for example minicraft: http://www.ludumdare.com/compo/ludum-dare-22/?action=preview&uid=398
import com.mojang.ld22.gfx.Font;
import com.mojang.ld22.gfx.Screen;
import com.mojang.ld22.gfx.SpriteSheet;
Why not just write:
import gfx.Font;
import gfx.Screen;
import gfx.SpriteSheet;
That's so much cleaner.
(I have never programmed in Java.)
These are there to prevent conflicts with other jars. Having something like the company url in the package name makes it likely to be unique enough to not conflict with someone else's package and classes.
Your example is a good one, since it seems pretty reasonable to imagine two people thinking of using "gfx" as a package name and with classes like Font or Sprite. Now, if you wanted to use both of them, how could you since the package and class name would be the name?
Your way is cleaner, but it assumes nobody else in the world is ever going to create a package called gfx, which is a pretty weak assumption. By prepending your reversed domain name, you create a unique namespace that avoids collisions.
This fits perfectly with the "culture of sharing" that pervades Java programming, in which applications typically combine large libraries from many sources.
In Java, the convention is to name your packages (which correspond to the folder structure containing your code) with information identifying your organization (typically including a TLD and the company name) and project (which might add a few more sections).
Being more specific like this also reduces the likelihood of namespaces accidentally colliding with eachother.
It's merely an organizational technique for preventing namespace conflicts. Nothing more or less. Java package names match the underlying directory structure, so any organizational pattern at the package level will be reflected there. It's typical for teams to start their package names with their organization's name and wax specific. This is simply convention, but it's ingrained and should be followed absent a very good reason.
It's all about Namespaces. With 'Namespaces', you can create 2 classes with the same name, located in different packages/folders. This Namespace logic can also be used for creating 'Access Privileges', etc etc. Below are some links:
1) Namespace
2) Java Package
3) Java Package Naming Conventions
EDIT: Let us assume that you are creating a new project and are using 2 open source frameworks from companies/organizations - comA and comB. Also, let us assume that comA and comB have created a class in their projects with the same classname. Now, with the Java package naming conventions, we have com.comA.SomeClass and com.comB.SomeClass. You can import and use both the classes in your class, without having a conflict. This is just a simple example. There are other uses from this naming convention.
If you want to share code with everyone else, but use generic names without conflict. its considered good practice to include you domain name (backwards)
Everyone write a package called gfx.Font you wouldn't be able to use more than one version in the same application.
You might feel your code will not be shared with the world (or even should not be shared) In which case, a shorted package structure may be simpler.
If you use an IDE, it does a good job of hiding long package structures so you don't need to worry about it.
This is due to recommended packaging structure. In large projects, so many packages/libraries are used and in order not to put source files into same folder with another library, programmers put their source codes into unique folders. As websites are unique, it is a convention to use packaging structure that looks like folder structure of websites.
Java does not require anything: you can just put all your classes in the default package and surf away. But for serious projects that kind of organization is not only wise, it's mandatory. The com.mojang.ld22 part is just a convention:
com = either this or org, java/javax for official packages
mojang = second part is company name
ld22 = third part is application name

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.

Categories

Resources