What is the suggested way to name Java packages? - java

I've seen lots of examples like com.mycompany.someapp. Seems to be the reverse of the domain. Which actually makes sense to me.
But at the end of the day, does it really matter? We are a small shop so maybe we don't see the benefits of proper domain naming.
So, is it good practice to name it to match the domain? If so, why?

Extracted from the link to Naming a Package (Java Tutorial) in Andrew's comment: (I claim no originality or ownership of the following).
Naming a Package
With programmers worldwide writing classes and interfaces using the Java programming language, it is likely that many programmers will use the same name for different types. In fact, the previous example does just that: It defines a Rectangle class when there is already a Rectangle class in the java.awt package. Still, the compiler allows both classes to have the same name if they are in different packages. The fully qualified name of each Rectangle class includes the package name. That is, the fully qualified name of the Rectangle class in the graphics package is graphics.Rectangle, and the fully qualified name of the Rectangle class in the java.awt package is java.awt.Rectangle.
This works well unless two independent programmers use the same name for their packages. What prevents this problem?
Naming Conventions
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use [their] reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).
Packages in the Java language itself begin with java. or javax.
In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore. For example:
Legalizing Package Names Domain Name Package Name Prefix
hyphenated-name.example.org org.example.hyphenated_name
example.int int_.example
123name.example.com com.example._123name
Happy coding.

Matching the domain gives you greater confidence against name collisions. It's probably more important to designers of 3rd party libraries than you and your app.

Yes, that's the suggested convention in the Java Language Specification, section 7.7.
If unique package names are not used, then package name conflicts may arise far from the point of creation of either of the conflicting packages. This may create a situation that is difficult or impossible for the user or programmer to resolve. The class ClassLoader can be used to isolate packages with the same name from each other in those cases where the packages will have constrained interactions, but not in a way that is transparent to a naïve program.
You form a unique package name by first having (or belonging to an organization that has) an Internet domain name, such as sun.com. You then reverse this name, component by component, to obtain, in this example, com.sun, and use this as a prefix for your package names, using a convention developed within your organization to further administer package names.
You don't have to follow the convention, but it's generally considered good practice. After all, suppose at some point in the future you want to release some of your code as open source - but you want to avoid naming collisions. At that point, you really ought to follow the same conventions as everyone else - and as it doesn't hurt to do so from the start...

The idea behind using domain name is to avoid namespace collisions in packaging. This only works if everyone follows the convention. So, yes, the convention is important. That said, if you never plan on exporting your code as an API or providing it to a third party, it's likely there is little downside to using whatever package name you feel like.

Practically speaking I like it for a number of reasons:
It gives users an easy place to go to just from looking at the package name
It avoids collisions between packet names (i.e. two "media" packages could be very likely otherwise)
It helps identify the same author over separate pieces of software
It keeps package names roughly the same length (ok, this is just an aesthetic point but I like it!)
As well as this, it's also recommended in the JLS. It's not a requirement, but when it's practically 0 effort to do, I'd do it unless there's a good reason otherwise.
Perhaps a better question to ask is why don't you want to follow that convention? If there's no real reason, there's no harm in following it!

The main aim is to guarantee uniqueness of package names, but if you're never going to release code for others to use then it probably doesn't matter, but there is a lot to be said for sticking with convention and worrying about the stuff that does matter. Otherwise come the day that you realise you have a great library that you want to share you could be kicking yourself for going against the flow.

Yes, it is sensible to always use a naming scheme. As a counter-example, assume that everyone would use the default package for their classes.
Common classes like User or Address would be used by several libraries, but in the end there can be only one class of a certain name in the runtime environment. (loosely speaking, it is not completely correct.)
In big projects you will likely use many external libraries, like Apache Commons, Google Guava, Spring, Hibernate, Terracotta. It's good that these libraries all use their own namespace, so that their internal classes do not accidentally conflict.

Related

Should I avoid commonly used class names?

Some class names are so "generic" that they are often found in several different packages, including in libraries and application code. Some examples:
Comment
Component
Factory
Location
Region
In my IDE, attempting to auto-complete the import for a class like one of these summons several competing suggestions.
When naming classes, is it a good idea to avoid class names already used elsewhere?
For some of these examples, I would imagine that using such class name is discouraged because it is simply not meaningful enough (e.g. Factory), but I am wondering whether it is discouraged to use a class name because it is used (frequently) elsewhere.
You should use class names where they make the most sense for you. None of the names above that you've proposed are off limits, and there's no reason why you can't use them (assuming a language that supports namespaces and can avoid naming conflicts in this way).
However, you may consider drilling down to class names that are more specific and precise, which will better describe the meaning of the objects in your code. For example:
Instead of Comment: LineComment or BreakComment could easily be class names in a compiler project where you would like to create semantic blocks for comments.
Instead of Component: ListComponent, CalendarComponent, or ViewComponent make particular sense when implementing a UI library where you have class-based components.
Instead of Factory: PizzaFactory makes more sense if you're trying to make pizzas!
Instead of Location: GeographicLocation or SemanticLocation makes more sense when implementing a directions based navigation app, and you're trying to distinguish between '45 deg N, 77 deg W' and 'next to the pizza place'.
Region: CodeRegion could be used in a compiler, and GeographicRegion could be used in a Maps app.
If you're afraid to be specific, namespaces and packages help. However, there is nothing discouraging you from using the same name for a class as another package where it makes sense. The class names specifically aren't copyrighted, and most IDEs now are smart enough to make distinctions between what packages you're referring to when using autocompletion.
For the most part, specificity is helpful in assisting other developers to read your code, which every developer can appreciate!
Comment, Region, and Location seem fine. Personally, so subjectively, Component and Factory are definitely too common to use but objectively I can't think of any conventional reason not to use them as names. I'd definitely try and couple those names with their respective usage, for example; TaskFactory, WidgetComponent, ButtonFactory, etc.
Depends if we are talking about business or technical part.
In technical part: using common names is actually a way to let others know about the patterns used, Factory is a good example - when you see a class named like SomethingFactory, you can expect a Factory Pattern. It goes further to frameworks, libraries etc. - SomethingAutoConfiguration with Spring-Boot, SomethingEntity with JPA, I think with frontend frameworks (React, Angular) Component is a really common word. So ye, by all means, use them, as long as you use them correctly.
In business part: simple, if those words describe your business domain, then by all means use them. Don't try to invent some fancy names (or thesaurus!) just because the words seem common, it's your business domain - it's sacred.

Java package naming. Underscores: A special case

Today I was naming a package in a project which would contain code related to a concept called an "access structure".
Now, naming this package "com.myemployer.project.component.accessstructures" seems unappealing and difficult to read because of the triple "S". (The higher level packages are not actually named "project" and "component").
I was tempted to use "...component.access_structures"
I couldn't find anything mentioned in the Java conventions on Oracle's site . And a brief web search brought up nothing.
What is the official convention for names like this?
From Oracle Docs
Package names are written in all lower case to avoid conflict with the names of classes or interfaces.
Companies use their reversed Internet domain name to begin their package names—for example, com.example.mypackage for a package named mypackage created by a programmer at example.com.
Name collisions that occur within a single company need to be handled by convention within that company, perhaps by including the region or the project name after the company name (for example, com.example.region.mypackage).
In some cases, the internet domain name may not be a valid package name. This can occur if the domain name contains a hyphen or other special character, if the package name begins with a digit or other character that is illegal to use as the beginning of a Java name, or if the package name contains a reserved Java keyword, such as "int". In this event, the suggested convention is to add an underscore
Although this text doesn't specify your exact case, it does say that for an invalid package name we should use an underscore. One could argue that accessStructures is how we would define a method in Java and thus naming a package like that could be confusing.
Overall, it is really up to you.
If you want to keep with this convention, I believe you should name your package:
com.myemployer.project.component.access_structures
Also you can look up synonyms and find alternatives that would give less confusion. Some I quickly found:
accessframework
accessfactory
accessarch (accessarchitecture)
accessconstructs
I dont think there is any standard for that. People follow different naming conventions as per there convenience and readability. But most of the programmers find camel case naming as the most convenient. You can name it like accessStructure
Found one Oracle Doc which recommends to use the package name with all small letters
Package names are written in all lower case to avoid conflict with the
names of classes or interfaces.
According to docs you can't use camelCase for package naming. It's ok to use snake_case for package naming in some cases, but it is more appropriate if you can't use your domain properly, because of the hyphen sign in it or it starts with numbers. But it has to be rather an exception from the rule than the rule.
If I were you I would rephrase it. For example: accessstructures -> accesscore

Naming small storage classes in java

i often have in java projects a lot of small helper("storage") classes like
2-Tuple, 3-Tuple, Point, .. (think you know what i mean)
Classes that mostly only have class variables, a constructor and getters/setters.
And in my current project, i wanted to store those small classes, that are often used in a lot of other classes in the project in a seperate package. But i do not really know how to name it (my motherlanguage is not english, but code should be for english readers.)
Hope you can give me an answer on this little questions.
Greetings
:)
Different people would name these differently as the names are a matter of personal choice.
A few options:
If the storage classes conform to the Javabeans conventions, you could add the suffix "Bean" eg PointBean
I have also seen a suffix of "DO" or "VO" being used to denote a "data object" or "value object". eg PointDO
You could leave the class name as is eg Point. However if you feel that it does not convey the fact it is a storage class, try to make the package name convey that fact eg
com.xyz.valueobjects.Point
or
com.xyz.dataobjects.Point
or
com.xyz.storage.Point
Personally I like to use style #3.
I'd stick those kinds of classes in a *.util package.
I'd go with something like:
utils or the more verbose utilities
you can then break that down further if you need to:
utils.data for data-related utility classes, for example.
Additionally, there's a question here on whether to pluralise or not: Naming convention for utility classes in Java
For your information the "storage classes" you are referring to are called Java Beans. Using the popular model view controller design pattern; these would be your model. So lets say you want to put them in a package called model and the domain name of your company is mycompany.com, then the propper java naming convention would be com.mycompany.model; add this line as the first line of code (before any import statements) to all of your Java bean classes:
package com.mycompany.model;
You must also move your Java bean files into a folder structure that is the same. Lets say the file with your main method is in the directory /%ProjectHome%/, then your Java Beans go in a folder /%ProjectHome%/com/mycompany/model/
To compile these files you will now have to change to your /%ProjectHome%/ directory then type javac com/mycompany/model/*.java
Then you will be able to import these files from your other java classes by typing
import com.mycompany.model.*;
Also note, that the Java convention for package names is all lower case, as not to clash with the name space of Class names.
Hope this helps.
I believe what you're doing is using objects purely for storing data (no behaviour). And since you're talking about tuples, I assume these are used for transferring data to/from your database, so perhaps just "data objects"?

What is the significance of the reverse domain name for java package structure

Why do we use reverse domain name like com.something. or org.something. structure for java packages?
I understand this brings in some sort of uniqueness, but why do we need this uniqueness?
About why we do it reversed: Imagine you have two important packages, an accounting package and a graphics package. If you specified these in 'straight' order:
accounting.mycompany.org
graphics.mycompany.org
Then it implies there is a major accounting package, a subsection of which is for mycompany, and a subsection of that package is called the org package which you actually use. However, you want this:
org.mycompany.accounting
org.mycompany.graphics
This makes more sense. Out of all packages from organizations (org), you look at mycompany in particular, and it has two sub-packages, the accounting and the graphics ones.
Globally unique package names avoid naming collisions between libraries from different sources. Rather than creating a new central database of global names, the domain name registry is used. From the JLS:
The suggested convention for
generating unique package names is
merely a way to piggyback a package
naming convention on top of an
existing, widely known unique name
registry instead of having to create a
separate registry for package names.
As you say, reverse domain names as base package name ensures uniqueness. Suppose two companies with DN example.com and example.org both define the class Employee in their framework. Now if you are using both frameworks you will not be able pinpoint which Employee you want to use in your code, but if they are defined in packages com.example and org.example respectively you can tell the compiler/JVM specifically which class you are referring to. If unique packages are not defined you will get compilation errors or runtime errors, e.g. if you are using the com employee class, but the org employee class gets loaded first from the classpath you will get a runtime error, since the two employee classes may not have same structure.
The uniqueness is needed for Class Loading.
It helps by avoiding naming collisions. If there are classes with same package name and class name, Collision will occur while trying to load the classes.
This generally happens if there are multiple libraries(jar) that contain classes with same names.
Also see this.
You need the uniqueness if you might need to integrate your code with third party software, or provide it to someone else for integration. If you don't follow the rules, you increase the risk that at some point you will have a class naming collision, and that you will need to rename lots of your classes to address it. Or worse still, that your customers will have to do the code renaming.
This also applies when code is produces as part of different projects in an organization.
As you said, it brings uniqueness, something that is needed especially when working with third party code. For example, consider that you are using a library I've made. I've used the package "foo" and have a class named Bar there. Now if you are also using the package name "foo" AND you have a class named Bar, this would mean that your implementation would override my Bar implementation, making my implementation inaccessible. On the other hand, if my package were "com.mydomain.foo" and I'd had by Bar class there, then you can freely use the name Bar in one of your classes and both classes could still be uniquely identified and used separately.
Why use the reverse domain name as the package name? I guess that is just a convention to make sure that everybody uses a unique namespace, as you shouldn't use someone else's domain in your package name.

designing Java interfaces with ordinary-sounding names, that "play nicely" with other packages

I'd like to define an interface called Tag in a Java package I am working on, but am hesitant to use such an ordinary-sounding name because of the collision issue. (e.g. you can import only one class or interface with a particular name; if there are more than one that share the same name, you can use import for one of them, but the rest you have to explicitly refer to with the entire package name e.g. com.yoyodyne.games.outdoors.Tag)
I also don't really have a more detailed name for it (it's supposed to represent a tag like the tags in StackOverflow posts or other online websites); the closest I can think of is maybe TaxonomyTag.
Are there strategies for dealing with this? The only one I can think of is to define a static class (like Collections) that contains a public interface Tag, e.g. if I call it Taxonomy then I can import Taxonomy and refer to Tag as Taxonomy.Tag -- but that doesn't sound much more helpful.
edit: one widely-known example of this collision is ca.odell.glazedlists.matchers.Matcher and java.util.regex.Matcher which is a pain if you are trying to use regular expressions with the GlazedLists library.
I don't see a problem with naming the class Tag. Your package name makes it universally unique and that is one of the purposes of packages - to resolve naming conflicts.
Even within the Java API there are multiple classes with the same name: java.util.Date, java.sql.Date for example. If you need both in your code then use the fully qualified name.
How many people are going to be using this class? If it's meant to be a general purpose library, I would go with a less-generic name to avoid collisions. If it's just you, and you really don't bite the bullet and go with fully-qualified names for now.
If it becomes a problem before you release the package, just refactor it to a new name.
In similar situations I have found some alternate name for short class names because I hate using FQNs. Even something like JasonSTag can work as a temporary fix; just don't release it that way. Often halfway through implementation I'll find a better way to describe the class, something more descriptive than "Tag".
Are you being lazy? If your class is using imports such that "Tag" could be misconstrued by someone reading your code, even momentarily, then it is worthwhile to think of a better name, despite the package naming convention. Don't underestimate the power of naming---or renaming as the class changes.
I wouldn't really be concerned with this.
What you should be concerned with is how well your class/interface name matches what the piece of code actually does. If Tag succinctly describes what the class/interface does and/or is meant to model, then I think it is a great name.
I can't really see the situation where you'd be using this Tag type in the same class along with other Tag types declared in different packages. But, if you have to, then it's not really that much of a pain to refer to the other Tag types by their fully qualified name.
I believe that how well you named something is greater than making things convenient.
The best strategy is to write classes which do one thing well. These classes do need the minimum of imports, so you have the reduction of import statements.
I looked for standard Tag interfaces; found one in java.swing..html, another one deep in servlet API, and another in tapestry library. I am sure that your class should not directly use one of these (or similar APIs), so you may not be afraid of namespace pollution.
Other solution is to prefix tag with the object it will be used on. E.g. ArticleTag. But you must carefully choose the object name. Or, anyway, you can always refactor it later.
Generally the number of conflicts, even with "ordinary" sounding names, is low. I'd chose a meaningful name within the context of the package.
Do not do somethiong "silly" like prefix it with the company name, eg: YoYoDyneTag.
It has gone out of style to use adjectives/adverbs as interface names recently, however, in your case it wouldn't sound that bad if you used 'Tagable' or 'TaxonomyTagable'.
This only tend to be a problem if you need to use more than one class with the same name in a single class. Examples: java.awt.List and java.util.List, java.util.Date and java.sql.Date.
If you stay away from those already used in the standard Java runtime you will most likely not have a problem.
Whatever you do - make the name you choose a good and descriptive one - this goes especially for those in a public API. You will live with them forever.

Categories