Item 56 - Adhere to generally accepted naming conventions

From Effective Java 2/e by Joshua Bloch

  • The Java platform has a well-established set of naming conventions, many of which are contained in The Java Language Specification

Typographical

Identifier Type Examples
Package com.google.inject, org.joda.time.format
Class or Interface Timer, FutureTask, LinkedHashMap, HttpServlet
Method or Field remove, ensureCapacity, getCrc
Constant Field MIN_VALUE, NEGATIVE_INFINITY
Local Variable i, xref, houseNumber
Type Parameter T, E, K, V, X, T1, T2

Grammatical

  • Classes, including enum types, are generally named with a singular noun or noun phrase

    Timer
    BufferedWriter
    ChessPiece
    
  • Interfaces are named like classes

    Collection
    Comparator
    Runnable
    Iterable
    Accessible
    
  • Because annotation types have so many uses, no part of speech predominates

    BindingAnnotation
    Inject
    ImplementedBy
    Singleton
    
  • Methods that perform some action are generally named with a verb or verb phrase

    append
    drawImage
    
  • Methods that return a boolean value usually have names that begin with the word is or has

    isDigit
    isProbablePrime
    isEmpty
    isEnabled
    hasSiblings
    
  • Methods that return a non-boolean function or attribute of the object on which they’re invoked are usually named with a noun, a noun phrase, or a verb phrase beginning with the verb get

    size
    hashCode
    getTime
    
  • The form beginning with get is mandatory if the class containing the method is a Bean

    getAttribute
    setAttribute
    
  • A few method names deserve special mention. Methods that convert the type of an object, returning an independent object of a different type, are often called toType

    toString
    toArray
    
  • Methods that return a view (Item 5) whose type differs from that of the receiving object are often called asType

    asList
    
  • Methods that return a primitive with the same value as the object on which they’re invoked are often called typeValue

    valueOf
    of
    getInstance
    newInstance
    getType
    newType
    
  • Grammatical conventions for field names are less well established and less important than those for class, interface, and method names, as well-designed APIs contain few if any exposed fields

Posted by The Finest Artist