Naming Conventions in Java

Naming Conventions in Java refers to the guidelines that application developers are expected to follow so that they can produce consistent and readable code throughout the application.

1. Basic Naming convention standards

To declare variables, constants, methods, classes, interfaces, etc use full descriptors. like customerId, firstName, lastName, etc.

2. Naming Packages

The guideline for Package names in Java is that package names should start from domain names (all lowercase ) like com, org, net, blog, etc. The package name’s other subsequent parts can be finalized according to the company business but all should in lowercase.

package com.w3shcools360.webapp.controller;

package com.w3shcools360.business.service;

3. Naming Classes

Nouns should be used for Class names. Use capitalized words for class names like Customer.

public class Customer{}
public class Supplier{}

4. Naming Interfaces

Adjectives should be used for interface names but Nouns can also be used like List, Map, etc. Like Class names, use capitalized words for interface names like Clonable.

public interface Clonable {}
public interface List {}

5. Naming methods

The method represents the action/events so method names should be Verbs that can clearly describe the action.

a). Naming member methods : 

Use the first word in small letters and all remaining words will be capitalized. E.g. – updateCustomer().

b). Naming accessor methods:

for getters – use get as a prefix to property (for non-Boolean properties). e.g. – getCustomerId().

for setters – use set as a prefix to property. e.g. – setCustomerId().

use is as a prefix to property(for Boolean properties). e.g. – isNewCustomer().

public Customer update(Customer customer) {}

public Customer getCustomerById(Long customerId) {}

public void setCustomerId(Long customerId) {}

public boolean isNewCustomer(Customer customer){}

6. Naming variable

All variables including instance, static, and method parameters should be in camel case. That means the first word is in a small case and all remaining words will be capitalized. E.g. – customerId, customerCode, etc.

public Long customerId;

public String customerCode;

Note: A temporary variable like a loop counter can be of a single character.

for (int i = 0; i <= 10; i++) {

}

7. Naming Constants

Use all uppercase letters and words should be separated by underscore “_”. E.g. MAX_MARKS. The final keyword needs to be used with a constant variable.

public final double PI= 3.14;  

public final Integer MAX_SIZE = Integer.MAX;

8. Naming Generic Types

Use single capital letters for a Generic Type. Normally, T is used for Generic Types. For map key /value pairs K and V are used to represent Generic Types.

public interface Map <K,V> {}

9. Naming Enums

Like class contacts, enumeration names should also be all uppercase letters.

enum Direction {EAST, WEST, NORTH, SOUTH}

 

 

Please follow and like us:
Content Protection by DMCA.com