Java package naming convention

Java Guides

Java naming conventions are sort of guidelines that application programmers are expected to follow to produce a consistent and readable code throughout the application.

Table of contents

Video

Let’s discuss package,class,variable,method,constant,abstract class and exception class naming conventions with examples.

1. Packages naming conventions

A package should be named in lowercase characters. There should be only one English word after each dot.

The prefix of a unique package name is always written in all-lowercase ASCII letters and should be one of the top-level domain names, like com, edu, gov, mil, net, org.

package org.springframework.core.convert; package org.hibernate.criterion; package org.springframework.boot.actuate.audit; package org.apache.tools.ant.dispatch;

Package naming convention used by Oracle for the Java core packages. The initial package name representing the domain name must be in lower case.

package java.lang; package java.util;

2. Classes naming conventions

Class names should be nouns in UpperCamelCase (in mixed case with the first letter of each internal word capitalized). Try to keep your class names simple and descriptive.

class Employee class Student class EmployeeDao class CompanyService
class String class Color class Button class System class Thread class Character class Compiler class Number

3. Interfaces naming conventions

In Java, interfaces names, generally, should be adjectives. Interfaces should be in titlecase with the first letter of each separate word capitalized. In some cases, interfaces can be nouns as well when they present a family of classes e.g. List and Map.

Runnable Remote ActionListener Appendable AutoCloseable CharSequence Cloneable Comparable Readable

4. Methods naming conventions

Methods always should be verbs. They represent action and the method name should clearly state the action they perform. The method name can be single or 2-3 words as needed to clearly represent the action. Words should be in camel case notation.
Examples:

public List Customer> getCustomers(); public void saveCustomer(Customer theCustomer); public Customer getCustomer(int theId); public void deleteCustomer(int theId);
getName() computeTotalWidth() actionPerformed() main() print() println(),

5. Variables naming conventions

The variable name should start with a lowercase letter. Parameter names, member variable names, and local variable names should be written in lowerCamelCase.

firstName orderNumber lastName phoneNo id counter temp

6. Constants naming conventions

Constant variable names should be written in upper characters separated by underscores. These names should be semantically complete and clear.

RED, YELLOW, MAX_PRIORITY, MAX_STOCK_COUNT

7. Abstract classes naming conventions

I observed in many standard libraries, the naming conventions used for Abstract class is class name must start with Abstract or Base prefix. This naming convention can vary from organization to organization.

AbstractHibernateDao AbstractCommonDao AbstractBase
AbstractBean AbstractBeanDefinition AbstractUrlBasedView AbstractIdentifiable

8. Exception classes naming conventions

I observed in many standard libraries, the naming conventions used for custom Exception class is class name must end with Exception suffix.

TransactionException SQLDataException ResourceNotFountException ResourceAlreadyExistException
ArithmeticException ArrayIndexOutOfBoundsException ArrayIndexOutOfBoundsException ClassNotFoundException CloneNotSupportedException EnumConstantNotPresentException Exception IllegalAccessException IllegalArgumentException IllegalMonitorStateException IllegalStateException IllegalThreadStateException IndexOutOfBoundsException

9. Enumeration naming conventions

public enum Day < SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY; >

10. Generic types naming conventions

Generic type parameter names should be uppercase single letters. The letter ‘T’ for a type is typically recommended. In JDK classes, E is used for collection elements, S is used for service loaders, and K and V are used for map keys and values.

public interface Map <> public interface List extends CollectionE> <> IteratorE> iterator() <>

11. Annotations naming conventions

Annotation names follow title case notation. They can be adjective, verb or noun based on the requirements.

public @interface FunctionalInterface <> public @interface Deprecated <> public @interface Documented <> public @Async Documented < public @Test Documented 

Specific Naming Conventions(Good to know)

Apart from the above java standard naming conventions, there are few more naming conventions that would be followed in many standard libraries such as Spring, Apache, Hibernate etc.

isSet, isVisible, isFinished, isFound, isOpen

This is the naming convention for boolean methods and variables used by Oracle for the Java core packages.

Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to choose more meaningful names.

void setFound(boolean isFound);

There are a few alternatives to the is a prefix that fits better in some situations. These have, can and should prefixes:

boolean hasLicense(); boolean canEvaluate(); boolean shouldAbort = false;
valueSet.computeAverage(); matrix.computeInverse()

Give the reader the immediate clue that this is a potentially time-consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability.

vertex.findNearestVertex(); matrix.findSmallestElement(); node.findShortestPath(Node destinationNode);

Give the reader the immediate clue that this is a simple lookup method with a minimum of computations involved. Consistent use of the term enhances readability.

CollectionPoint> points; int[] values;

Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements.

void setTopic(Topic topic) // NOT: void setTopic(Topic value) // NOT: void setTopic(Topic aTopic) // NOT: void setTopic(Topic t) void connect(Database database) // NOT: void connect(Database db) // NOT: void connect(Database oracleDB)
line.getLength(); // NOT: line.getLineLength();

Please write comments, if you want to give any suggestions or feedback about my articles would be appreciated.

If you like my articles and want similar kind of stuff, connect with me on Google +, Facebook, GitHub, and StackOverflow.

Check out our top viewed Java Guides and Java/J2EE Best practices. I hope you like it.

Happy Learning and Keep Coding .

Conclusion

In this article, we discussed the Java naming conventions to be followed for consistent writing of code which makes the code more readable and maintainable.

Naming conventions are probably the first best practice to follow while writing clean code in any programming language.

Источник

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? Convention.

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

Источник

Java Naming Conventions

Java naming conventions are sort of guidelines that application programmers are expected to follow to produce consistent and readable code throughout the application. If teams do not follow these conventions, they may collectively write an application code that is hard to read and difficult to understand.

Java heavily uses Camel Case notations for naming the methods, variables etc. and TitleCase notations for classes and interfaces.

Let’s understand these naming conventions in detail with examples.

Package names must be a group of words starting with all lowercase domain names (e.g. com, org, net, etc). Subsequent parts of the package name may be different according to an organization’s own internal naming conventions.

package com.howtodoinjava.webapp.controller; package com.company.myapplication.web.controller; package com.google.search.common;

In Java, class names generally should be nouns, in title-case with the first letter of each separate word capitalized. e.g.

public class ArrayList <> public class Employee <> public class Record <> public class Identity <>

In Java, interfaces names, generally, should be adjectives. Interfaces should be in the title case with the first letter of each separate word capitalized. In some cases, interfaces can be nouns as well when they present a family of classes e.g. List and Map .

public interface Serializable <> public interface Clonable <> public interface Iterable <> public interface List <>

Methods always should be verbs. They represent action and the method name should clearly state the action they perform. The method name can be single or 2-3 words as needed to clearly represent the action. Words should be in camel case notation.

public Long getId() <> public void remove(Object o) <> public Object update(Object o) <> public Report getReportById(Long id) <> public Report getReportByName(String name) <>

All instance, static and method parameter variable names should be in camel case notation. They should be short and enough to describe their purpose. Temporary variables can be a single character e.g. the counter in the loops.

public Long id; public EmployeeDao employeeDao; private Properties properties; for (int i = 0; i

6. Constant Naming Conventions

Java constants should be all UPPERCASE where words are separated by underscore character (“_”). Make sure to use the final modifier with constant variables.

public final String SECURITY_TOKEN = ". "; public final int INITIAL_SIZE = 16; public final Integer MAX_SIZE = Integer.MAX;

Generic type parameter names should be uppercase single letters. The letter 'T' for type is typically recommended. In JDK classes, E is used for collection elements, S is used for service loaders, and K and V are used for map keys and values.

public interface Map <> public interface List extends Collection <> Iterator iterator() <>

Similar to class constants, enumeration names should be all uppercase letters.

Annotation names follow title case notation. They can be adjectives, verbs, or nouns based on the requirements.

public @interface FunctionalInterface <> public @interface Deprecated <> public @interface Documented <> public @Async Documented

In this post, we discussed the naming conventions in Java to be followed for consistent writing of code which makes the code more readable and maintainable.

Naming conventions are probably the first best practice to follow while writing clean code in any programming language.

Источник

Читайте также:  Php конвертация utf 8
Оцените статью