Explain Codes LogoExplain Codes Logo

Java Naming Convention with Acronyms

java
best-practices
naming-conventions
java-standards
Nikita BarsukovbyNikita Barsukov·Sep 16, 2024
TLDR

In Java, follow the naming convention that capitalizes two-letter acronyms (HTTPError), while capitalizing only the first letter in longer acronyms (XmlParser). This maintains readability and stays true to the camelCase/PascalCase style.

Example:

  • HttpUrl (not HTTPURL)
  • IoStream (not IOSTREAM)

Clarity and Ease of Use

Always prefer understandable acronyms. For instance, while XmlHttpRequest is widely understood, unnecessary abbreviations can confuse people. Hence, always opt for unambiguous acronyms that are widely recognized, ensuring your code speaks for itself.

Rules for 3-letter acronyms:

  • UrlEncoder (not URLEncoder)
  • TcpSession (either all uppercase or mixed-case)

Readability Over Rules

Strive for readability by choosing names that offer clarity. SvgImage reads more fluently than SVGImage, aligning with how humans read and write. This also ensures compatibility with Java tools and libraries following the PascalCase and camelCase standards.

Consistency is Queen

Keep your naming consistent. If you choose TcpSession in one place, avoid using TCPSession in another. Consistent naming conventions improve navigation and maintainability of your codebase.

Learn from Library Precedents

Refer to established Java libraries like JavaSE, Apache, and Spring for guidance. Following the conventions observed in these libraries can serve as practical examples for naming in your own code.

Choosing the Right Identifier

While choosing an identifier, remember the following principles:

  • Clearly communicate intent
  • Avoid ambiguous abbreviations
  • Ensure compatibility with tools and standards
  • Aim for maintainability within your team

CamelCase for Harmonious Code

For instance variable or method names containing acronyms, using camel case (jsonValue) preserves the standard Java naming convention. Plus, it won't make your code look like it's shouting at you! 😛

Instance Naming: Consistency Matters

When naming class instances, align with these conventions for a consistent look and feel across your codebase. So if you have a class JsonParser, a good instance name would be jsonParser.

Breaking the Rule: When and Why

On occasions, when established terms or product names require deviation in acronyms in class names, prioritize team consensus and document the exception. Remember, rules are made for the guidance of wise men and the obedience of fools. 😉