Java Naming Convention and Best Practices


A Good Name: clear and precise

  • concise, but not too long
  • No surprise
  • Avoid uncommon acronyms/abbreviations and in-team jargon.
  • Select visually distinct names.
  • Match the reader’s expectations
  • Don’t repeat the context
    • don’t add variable type, omit surrounding package name, class or method name.
  • Naming should cover the purpose
    • CODEC > BASE64_ENCODING > PAGE_TOKEN_ENCODING
  • variable names should not hard-code their value. We should be able to change the value without renaming it.

Package Names

  • Components should be short, generally eight or fewer characters.
  • Meaningful abbreviations are encouraged.
  • Acronyms are acceptable

Names for Classes

  • Abbreviations are to be avoided, except for acronyms and certain common abbreviations
  • Class names are typically nouns or noun phrases.
  • Test classes are named starting with the name of the class they are testing, and ending with Test. For example, HashTest or HashIntegrationTest.
  • Avoid class names that are defined by the JDK or other libraries and are widely usded.
    • Client may have to use full qualified name for your class.
  • Name for Util class: Object -> Objects
    • Objects, Collections, Collectors, Executors, Futures
    • When it’s already used: MoreExecutors, MoreObjects
  • Nested classes
    • Remove info already in outer class.

Names for Interfaces

  • Interface names may also be nouns or noun phrases, but may sometimes be adjectives or adjective phrases instead.
    • Runnable, Iterable, Accessible, Readable, Writable, Closable
  • Don’t name interfaces with the “Interface” suffix
  • Don’t name implementations of interfaces with an “Impl” suffix

Name for Annotation Types

  • Can be Nouns, verbs, prepositions and adjectives
  • BindingAnnotation, Inject, ImplementedBy, or Singleton

Name for Methods

  • doesn’t contain parameter information, any terms general to the class
  • a verb, verb phrase for action
  • is or has prefix for methods return boolean.
  • a noun, a noun phrase, or get prefix for methods that return a non-boolean function or attribute:
  • methods returning an independent object of a different type: toType(), toArray()
  • methods that return a view: asType(), asList()
  • methods that return a primitive: typeValue(), intValue()
  • static factories include from, of, valueOf, instance, getInstance, newInstance, getType, and newType
  • methods starting with get or set are trivial methods that execute quickly
    • in other cases: use compute, make, read, find, load prefix.
    • change getAuthToken() to readAuthToken() or loadAuthToken()

Name for Test Methods

  • Underscores may appear in test method names to separate logical components of the name, with each component written in lowerCamelCase.
  • Use 3rd person: throws not throw.
  • methodUnderTest_condition/state_outcome

Constant names

  • all uppercase letters
  • Not a constant if any of its observable state can change.
    • not constant: logger, mutableCollection/Element,
  • enumeration names should be all uppercase letters.
  • Avoid magic number: define it as a constant
  • Avoid the constant that takes format parameters: as it’s unclear how many parameters it takes, and what’s the types, define a method instead.

Type variable names

  • A single capital letter, optionally followed by a single numeral.
    • T for Type, E for the element type in a collection, X for exception, K and V for key and value types of a map.
    • R for the return type of a function. A sequence of arbitrary types can be T, U, V or T1, T2, T3.
  • A name in the form used for classes, followed by the capital letter T: RequestT, ResponseT.

Variables and Method Parameters

  • a noun, doesn’t contain type info, does not include any terms general to the method
  • abbreviations are permitted
  • use positive boolean variables or words. Double negation is confusing
    • isEnabled, not isDisabled
  • use plural if it’s a collection
    • dates, not dataList
  • Method parameters should be named much more carefully.
boolean variables
  • use positive boolean variables or words. Double negation is confusing
    • isEnabled, not isDisabled
  • omit the is prefix for the field of boolean or boolean variable: enabled
  • include the is prefix for method that returns boolean: boolean isEnabled()
Single-letter local variables
  • i, j, k, etc. for counters such as loops.
  • e for exceptions in catch blocks

lambda variable name

  • reveal the type info at the lambda parameters
  • usually just choose the Suggestion from the IDE

Flags

  • flags are a single global namespace, so prefer long descriptive names.

Camel case

  • Acronyms should be camelcased, not fully uppercased.
  • even if multiple acronyms occur back-to-back, you can still tell where one word starts and the next word ends
  • XmlHttpRequest, supportsIpv6OnIos,newCustomerId, innerStopwatch, HttpUrl(not HTTPURL)

Long Names Are Long

  • Omit words that are obvious given a variable’s or parameter’s type
  • Omit words that don’t disambiguate the name
  • Omit words that are known from the surrounding context
    • Remove info already in outer class from outer class name.
    • Remove info already in class name from name of instance, static method, field.
  • Omit words that don’t mean much of anything ##### IdentifierNamingPostForWorldWideWebBlog
  • Omit words that are obvious given a variable’s type declaration. holidayDateList -> holidays
  • Omit irrelevant details.
  • Omit fluff words that could apply to any identifier. > fluff words: data, state, amount, number, value, manager, engine, object, entity, instance, helper, util, broker, metadata, process, handle, context, result

  • all words are necessary in the local context

Add readable name

  • Extract code as a helper method and give it a meaningful, readable name.
  • Extract code like condition and assign it to a viable with meaningful, readable name.

Misc Tips

  • Don’t reuse same variable name in the same class in different contexts
  • Don’t use same variable for different purposes.

Smell for bad names

  • get, set, dir, data, value, CommonXXX, Constants

Examples

  • numElements -> rows -> rowCount
  • Constants.java > RpcErrorMessages.java
  • curXXX: curSum, totalSum
  • hasTragicException -> isTragic
  • CanRetrieve, IsRetrievable
  • xxxNotUpdateForTooLong -> staleXXX
  • ThrowingFunction
  • toXXX
  • expectedXXX, foundXXX

Common Typos in Names

Resources

Labels

adsense (5) Algorithm (69) Algorithm Series (35) Android (7) ANT (6) bat (8) Big Data (7) Blogger (14) Bugs (6) Cache (5) Chrome (19) Code Example (29) Code Quality (7) Coding Skills (5) Database (7) Debug (16) Design (5) Dev Tips (63) Eclipse (32) Git (5) Google (33) Guava (7) How to (9) Http Client (8) IDE (7) Interview (88) J2EE (13) J2SE (49) Java (186) JavaScript (27) JSON (7) Learning code (9) Lesson Learned (6) Linux (26) Lucene-Solr (112) Mac (10) Maven (8) Network (9) Nutch2 (18) Performance (9) PowerShell (11) Problem Solving (11) Programmer Skills (6) regex (5) Scala (6) Security (9) Soft Skills (38) Spring (22) System Design (11) Testing (7) Text Mining (14) Tips (17) Tools (24) Troubleshooting (29) UIMA (9) Web Development (19) Windows (21) xml (5)