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
Related
I want to get into creating applications, however, I do not know when I should use packages. How should packages be used? How do you know what class to put in what package?
Except for really trivial programs that involve not more than one file, you should always use packages. A typical package structure is the following
com.<your_company>.<your_project>.<sub_system>....
or
org.<your_organization>.<your_project>.<sub_system>....
or (if you don't really belong to any organizations or companies)
<some_name>.<your_project>.<sub_system>....
where ... above indicate some more structure within your sub system. And
<some_name> is just some name that won't be easily in conflict with names that are used by other people. Don't worry. Even if you pick a name that
is already used by someone else, you won't be in trouble until the moment you
try to compile two packages of the same name together (obviously that
should not be allowed). So these names are all valid choices for <some_name>
playground
mytest
chapter1
tutorial
By convention, package names are always in lowercase. And in contrast, class names always start with an uppercase character. For example, in
com.google.gwt.core.client.EntryPoint;
the package name is com.google.gwt.core.client, and the classname is EntryPoint
A good way to learn is to see how other projects organize their packages and classes. Below I show some examples (which include both package names and class names):
org.hibernate.annotations.Cache;
org.hibernate.annotations.CacheConcurrencyStrategy;
com.google.gwt.core.shared.GWT;
com.google.gwt.core.client.EntryPoint;
com.google.gwt.user.client.Window;
com.google.gwt.user.client.Window.Location;
com.google.gwt.user.client.rpc.AsyncCallback;
com.google.gwt.user.client.ui.RootPanel;
com.smartgwt.client.util.DateUtil;
com.smartgwt.client.util.SC;
com.smartgwt.client.widgets.Canvas;
com.smartgwt.client.widgets.HTMLFlow;
com.smartgwt.client.widgets.layout.VLayout;
One more observation I would like to make is that package names
are often organized top-down (from big to small). This convention is
the reverse of the
convention of how Internet domain names are formed (from small to big).
In the above example, Google's GWT project has named their package as
com.google.gwt....
while Google's Internet domain names are in this form
....google.com
Many companies and organizations use the reverse of their domain names to form the prefix of their packages.
Use packages to seperate classes in your applications by concerns. This helps you in several ways:
avoid name conflicts between unrelated classes
group related classes together and isolate unrelated classes in different packages
which all should lead to a better maintainability of your application. If you can find reasonable names for your packages, you can get even a clue what purpose the classes in your package have.
You can read more about it in the official java tutorial. A very common use case is to seperate
application logic (also called model) from
presentation / gui code (often called view)
See how Java itself uses packages to seperate things:
java.lang.Math for computations
javax.swing, java.awt for gui frameworks
java.nio for buffered input/output
Packages are used in Java in order to prevent naming conflicts, to control access, to make searching/locating and usage of classes, interfaces, enumerations and annotations easier, etc.
If your program has a small amount of classes, like 3 classes
you may not have to separate them into packages.
Your classes are separated into packages in a logical way.
for example:
If you have a program that encryptes data, each of the encryption algorithms
can be separated into classes, and all of those encryption classes can be in the same package
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.
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.
Okay, so I'm wanting tips on how to pick a name for my Java packages.
I saw this post: What package naming convention do you use for personal/hobby projects in Java? but this talks about personal projects.
What if for example I wanted to make an API Wrapper, and I develop with others on GitHub? I don't have a domain name.
The domain-name-backwards convention is there to prevent name collisions. Two different companies with the same product name will have different namespaces so everything works fine.
If you don't have a domain then you need to choose a name that is meaningful to you and will not collide with anything else. That's OK; it just means very slightly more work for you to make sure that there isn't an existing product with the name you want, and there may be difficulties if there ever is a name collision.
You won't be the first to do this: the JMockit library is all in the "mockit" namespace with no "com" or "org" prefix.
The recommendation has always been to start with your domain name backwards, then the project name, e.g. com.mycompany.myproject, and continue on with submodules as necessary.
I'm just coming up the learning curve for Java SE & have no problem with the usual Java convention for package names, e.g. com.example.library_name_here.package_name_here
Except.
I've been noticing a failure to abide by this in some fairly well-known packages.
JLine: jline.*
JACOB: com.jacob.* (there is no jacob.com)
JNA: com.sun.jna.* (disclaimer on the site says NOTE: Sun is not sponsoring this project, even though the package name (com.sun.jna) might imply otherwise.)
So I'm wondering, are there instances where the usual reverse-domain-name convention breaks down, and there are good ways to get around it? The only cases I can think of revolve around domain-name ownership issues (e.g. you change the project hosting/domain name, or there's already a well-known package that has "squatter's rights" to your domain, or your ownership of the domain runs out & someone else snaps it up).
edit: if I use my company's domain name, and we are bought out or have a spin-off, what should we do with package names? keep them the same or rename? (I suppose renaming is bad from the point of view that compiled classes referring to the package then lose)
It's a naming convention. There's no real requirement or even expectation that the package name maps to a domain name.
The general idea is that two organizations would not own the same domain, so using the domain name as part of the package ensures that there are no namespace clashes. This is only a recommendation however.
There is a good reason for someone to have packages in the sun namespace. If they are providing an implementation of a public API, it's often necessary to implement the classes in the API's namespace.
If you're making your way up the Java learning curve, I would worry more about making your packaging structure clear so you can easily find the class you are looking for.
Packages are used to avoid ambiguity and collisions between components built by various entities. As long as you follow the convention, and nobody illicitly uses your slice of the package namespace pie, you shouldn't need to worry about what others have used.
The only thing that matters (IMHO) is that the parts of the package name are “sorted” by importance, i.e. that you don’t end up with gui.myprog, util.myprog, main.myprog but with myprog.gui, myprog.util, and myprog.main. Whether the package name really begins with a top-level domain followed by a domain name is of no concern to me.
You can't use language keywords as parts of a package name, that's another case where the domain name convention cannot be applied - tough luck for LONG Building Technologies
But then, the convention is just that, a convention, and pretty much the only reason why it exists is that it minimizes the chance of different projects accidentally choosing the same package name. If you can't follow it, it's not really a big problem.