Java class naming – The ultimate guideline

Every programmer agrees naming classes is highly important for code readability. Proper naming decrease the time needed to understand the code base. Many developers will also agree that class naming isn’t easy. There are numerous queries around the best practices which come not only from the beginners.

The aim of this article is to put in one place answers for the most popular questions around Java class name conventions and community standards. I’ll cover technical Java language restrictions, common conventions, and popular class naming best practices.

So much by way of introduction. Let’s get down into it.

Advertisement

Class name rules and restrictions

When it comes to technical limitations for class names, the Java language is pretty flexible. But realistically, programmers rarely use this flexibility.

Java class max length

The specification of the programming language states that the length of a Java class name is unlimited. In practice, however, the first limit comes from the JVM specification. For the current JVM it’s 65535 characters.

Moreover, the class name is usually the same as the filename in which you define the type. Because of that, there is one more factor affecting the max length of the class name. It’s Operating System and underlying filesystem.

In Windows, the limit for a single filename is 260 characters. The .java file extension takes 5 characters which leaves us with 255 character limit for class names. For UNIX based system most file systems also restrict the length of a file to 255 characters.

Characters allowed in Java class name

The language specification states that a class name should be a sequence of so-called Java letters or Java digits. The first character should be a Java letter.

What is a Java letter? Or Java digit?

A Java letter is a set of Unicode characters, underscore (_), and dollar sign ($). A Java digit is a collection of numbers from 0 to 9

The idea behind the Unicode characters as a valid part of Java class names is to allow programming in the native language of developers all over the world. However, this isn’t commonly practiced. Usually, programmers limit themselves to the English alphabet.


Once I’ve seen an app write in my native language and it was a pretty hilarious experience. Especially some plural variable names generated by IDE.

Java class name conventions and standards

Java is already a pretty old programming language. Over the years, developers created several commonly agreed standards for naming classes. These standards are much more restrictive than limitations from the Java language specification. Naming conventions allow other to read your code easily.

Please note almost all naming conventions are opinion based and not technically imposed. You may meet developers who disagree with some of the presented conventions (especially if they have a background in different programming languages). However, you definitely should discuss and agree on standards your team will follow inside a single project.

Below you can find the list of answers for the most popular questions around class naming conventions. If something in your opinion is missing on the list, please let me know about it in a comment.

Class name should be noun

In Object Oriented Programming, a class represents an existing entity from the real world that you model in your application. Classes describe things. Just think about classic examples like User, Message, or Event.

But single word class names are rather rare. Usually, we use noun phrases to provide more descriptive names for classes such as AnonymousUser, DirectMessage, or UserCreatedEvent. The less abstract a class is, the more details are present in its name.

You should reserve verbs for method names as they represent actions executed by things.

Singular or plural nouns?

When you think of a class as a template for objects, the choice should be obvious. In almost all cases objects we create represent singular entities. Just one item of something.

When we work with multiple instances, we usually use collections which are available in the Java Class Library. Collections always use singular nouns for their names. Think of List, Set, or Map to name a few. While working with multiple instances of some class, we usually manipulate them with some kind of singular container.

But hold on a second.

Don’t we have counterexamples inside JDK? What about classes like Objects, Arrays or Collections?

Unlike most classes we create, these JDK classes don’t represent any entities. What they all have in common is that you can’t create an instance of them. Try calling Objects constructor if you need proof. These types are just containers for static methods. These utility methods don’t belong to any particular instance.

On the other side of the coin, JDK has the String class which you can instantiate and which also contains static utility methods. It seems like an inconsistency in the design of JDK and maybe that’s why we’re all confused.

When it comes to static methods, it’s just a matter of choice. You can put such methods in a class with a singular name or create a plural named class as a namespace. As long as your team is consistent, you can’t go wrong with either option.

UserDao vs. UsersDao

The dilemma from the above subtitle is probably popular only amongst non-native English speaker (like myself). It extends on the previous point about singular and plural nouns in class names.

Imagine you have a class which manipulates multiple instances of some type, e.g. a repository class for the database access layer. Should you use a plural or a singular form of that type?

Let me answer the question with the picture:

Screwdriver

Do you know the English name of this tool?

It’s a screwdriver.

You can screw multiple screws with a screwdriver. Yet, in the name of the tool, there is only a singular screw. Can you see the analogy for the DAO class?

Class name same as filename

The Java compiler expects that the class name matches the filename in which it’s defined. However, this requirement is true only for public classes.

You technically can define a non-public class in a file with a different name or even write several classes in a single file. The Java compiler won’t prevent you from doing this.

But just because you can name files differently than classes, it doesn’t mean you should.

Java programmers commonly agree the class name and the filename should be the same. Having only a single class defined in a file is also considered as a standard. Such an approach is simpler for navigation around project’s file structure.

Class name starts with capital letter

As I already mentioned, a class name must start with a Java letter. The language specification sets this requirement. But, it doesn’t specify the case of this letter.

It’s just a common agreement amongst Java developers for easy readability of the code to start class names with a capitalized letter. When you create a class name with several words, you should capitalize each word. The upper case letter acts as a separator.

Can Java class name contain underscore?

Technically it’s possible to use the underscore in a class name, but there’s no practical reason to do so.

If the underscore were used in a class name, it would act as a separator between words. In Java, we achieve optical separation between words with the camel case. By using the underscore, we would only unnecessarily enlarged name’s length.

Class name length best practice

When a class name is too long?

A name of a class is too long when another shorter name with exactly the same meaning exists.

There’s no exact number which you should set in your static code analysis tool. The main aim of a class name is to describe the purpose of this class. The lesser short words you can use to name the class, the better for the code readability.

But why short names are so important?

Long names (not only of classes but method and variables too) affects the readability of code blocks. Vertical scroll bars in IDEs or simple line breaks are considered as distractors.

Our brain associates text lines with programming instructions. When an instruction spans multiple lines, many programmers find it hard to skim over code blocks.

Abbreviation in class name

The compiler only cares if names are unique. The code is written to be read by humans, not computers.

We already discussed short class names are important. Abbreviations seem like a way to achieve shorter names. Yet, most Java programmers prefer to avoid abbreviations.

However, some teams accept abbreviations for certain words. Especially, if these words appear in the numerous number of classes with similar purpose. An example of such word might be Config or Id. If your team belongs to this group, make sure all classes in a project follow the same rule.

Acronym in class name

An acronym is a word made from the first letters of other words. All letters in an acronym are capitalized, e.g. HTML.

Should an acronym be capitalized when used in a class name?

Unfortunately, if you check conventions in the Java Class Library, you’ll find examples for both approaches. Because of that, some people simply think it doesn’t really matter.
However, in Effective Java, Joshua Bloch suggests sticking to camel case also for acronyms. The example which illustrates benefits for readability is when a class name contains several acronyms next to each other, for instance HttpUrl. Using the upper case for both words would make the class name blurry and hard to read.

Blurry HTTP URL

Java class naming best practices

We already discussed technical restrictions and popular naming conventions. Now it’s time to present a handful of tips which should make naming classes easier for you.

Follow Single Responsibility Principle

The most important piece of advice you can ever get for Java class naming is to understand and apply the Single Responsibility Principle.

In brief, SRP tells us that a class should have only one reason to change. The name of a class should explain this reason.

Of course, SRP doesn’t only influence class naming. It changes the whole way you design your code. When you are new to SRP, it might seem odd and redundant to create numerous small classes. Fortunately, the more you practice SRP, the more benefits you’ll see.

Start with name placeholder

When you create a class and can’t come up with a name for it right away, give it a temporary name line ClassX and start implementing its body. Once you finish, the purpose of the class should be more obvious and naming shouldn’t be a problem.

But beware:

Without a name and a clear goal for a class, you can easily create a typical God object. If after implementation you still have a problem to name a class because it does several things, it might be a sign the class should be separated into a few smaller classes.

Avoid synonyms

It very common to have several classes which have the same purpose but in a different context. For example, let’s consider classes responsible for creating different objects. We can call such class as Creator, Constructor, or Factory.

The word you select to describe the purpose is a personal preference but keep the choice consistent across your whole application. Your team newcomers will thank you. It will be easier for them to see code conventions in the project at a glance.

Naming interface implementers

If you have an interface which is implemented only by one class and the name of this class is the same as interface’s name followed by the Impl suffix, you should be aware that something is wrong. It’s highly possible this interface is totally useless and the code would be much more readable with just a class named as this interface.

When a class implements an interface, it probably has specific traits that you can reflect in the name of this class. Just look at concrete implementations of the List interface from the Java Class Library. Names like ArrayList or LinkedList give you an overview of differences between them.

Conventions for naming service classes

Naming classes which model your domain objects is usually pretty straightforward. These names come from domain experts who know business very well. But these classes are just a small part of an application.

Yet, every application needs some glue code in which we create and manipulate aforementioned business objects. Such glue code usually resides in classes called Services.

Glue layer

You can find a lot of bad opinions about such service classes and numerous suggestions to avoid them.

But let’s be frank.

When you try to give a structure to your application, you can’t get rid of some sort of service classes. The name you choose for the glue layer doesn’t really matter. Service, Manager, Coordinator, sometimes Controller. Whatever. Pick your poison. You need a place in your application for coordinating work on business objects.

The general idea of service classes isn’t bad when you think of them as a glue layer. The problem with this type of service classes is at the pace they grow. Programmers tend to add way too many responsibilities to these classes which make them hard to maintain God objects.

The word Service is pretty generic and maybe that’s why developers assign so many responsibilities to these classes. But this word is used in our industry for so long that I don’t think it will ever change.

But there’s one thing we can improve.

We can split the responsibilities of service classes into smaller, better named and more focused classes. In other words, we apply the already discussed Single Responsibility Principle.

Util and helper class naming convention

Unfortunately, the Java Class Library doesn’t give us a clear guideline on naming utility method holders. Once again, the word you choose doesn’t really matter as long as you’re consistent inside your project.

Having classes called AccountUtils,  Accounts, and AccountUtilities will only confuse readers. Pick one convention and stick to it.

Conclusion

At this point, you should be familiar with the most popular Java naming conventions, standards, and best practices. We went through the technical restrictions, commonly agreed opinion based naming approaches, and finally covered a few class naming hints.

I strongly encourage you to leave a comment if you think something is missing on the list of mentioned topics. I’ll glad to extend the article to make it more accurate. Different opinions are also very welcome. If you find the post useful, don’t forget to spread the word.

Facebooktwittergoogle_plusredditlinkedinmail

Articles you may like

Advertisement