Java Programming Style Guidelines and Conventions
This article summarizes key principles, formatting rules, naming conventions, documentation practices, and coding conventions from the book “The Elements of Java Style,” providing practical guidance for developers who want to write clean, consistent, and maintainable Java code.
Inspired by a sudden interest in coding habits and programming style, I gathered material on Java coding style to help both coding enthusiasts and beginners.
The book “The Elements of Java Style” is highly recommended; it saves time on details and makes collaboration smoother.
Core Principles:
Preserve existing style.
Follow the principle of least surprise.
Get it right the first time.
Record all non‑standard behaviors.
Formatting Rules
1. Indent nested code blocks (classes, inner classes, methods, static blocks, loops, conditionals, try/catch/finally, anonymous classes, etc.) to improve readability.
2. Break long statements: start a new line after each comma and align the first character of the following expression; also break before the lowest‑precedence operator.
3. Use whitespace: separate keywords from left parentheses, right parentheses from following keywords, and operators (except ".") from their operands; insert blank lines between logically independent methods, class/interface members, and between classes/interfaces.
4. Avoid using the Tab character directly, as its interpretation varies across environments.
Naming Conventions
1. Names should be meaningful.
2. Use familiar terminology.
3. Avoid overly long names; use concise, common abbreviations when appropriate.
4. Retain vowel letters where possible.
5. Capitalize the first letter of abbreviations.
6. Do not rely on case differences to distinguish names.
Package Naming:
1. Use the reversed, lower‑case domain of your organization as the root package.
2. Use single lower‑case words for each sub‑package.
3. Change the package name only when binary compatibility is broken.
Type Naming:
1. Capitalize the first letter of each word in class and interface names.
Class Naming:
1. Name classes with nouns.
2. Use plural form for classes that group related attributes, static services, or constants.
Interface Naming:
1. Use nouns or adjectives for interfaces.
Method Naming:
1. Start with a lower‑case word; capitalize the first letter of each subsequent word.
2. Use verbs for method names.
3. Follow JavaBean conventions (set, get, is).
Variable Naming:
1. Start with a lower‑case word; capitalize the first letter of each subsequent word.
2. Use nouns for variables.
3. Use plural form for collection references.
4. Use a standard set of short names for insignificant temporary variables.
Field Naming:
1. Use this to distinguish fields from local variables.
Parameter Naming:
1. Constructor or setter parameters should have the same name as the field they assign.
Constant Naming:
1. Write all words in uppercase, separated by underscores.
Documentation Conventions
1. Write documentation for anyone who will use or maintain your code.
2. Keep comments synchronized with code.
3. Use an active voice and omit unnecessary words.
Comment Types
1. Use documentation comments to describe programming interfaces.
2. Use standard comment syntax to hide code without deleting it.
3. Use single‑line comments to explain implementation details.
Documentation Comments:
1. Describe the interface before writing code.
2. Document public, protected, package‑private, and private members.
3. Provide a summary and overview for each package.
4. Provide an overview for each application or module within a package.
Comment Style:
1. Use a consistent format and structure for all documentation comments.
2. Enclose keywords, identifiers, and constants in <code>…</code> tags.
3. Place code snippets inside <pre>…</pre> tags.
4. Use {@link} tags when an identifier first appears.
5. Follow a fixed order for Javadoc tags.
6. Write in third‑person narrative.
7. Write an independent overview.
8. Omit the subject in action descriptions.
9. Omit objects and verbs in abstract statements.
10. Use this instead of the to refer to the current instance.
11. Do not add parentheses to method or constructor names unless emphasizing a special signature.
Comment Content:
1. Provide an overview for every class, interface, field, and method.
2. Fully describe each method’s signature.
3. Include examples.
4. Document pre‑conditions, post‑conditions, and invariants.
5. Document known defects and limitations.
6. Document synchronized syntax.
Internal Comments:
1. Add only comments that help understand the code.
2. Explain why the code does something, not what it does.
3. Avoid end‑of‑line comments.
4. Use end‑of‑line comments to explain local variable declarations.
5. Use a set of keywords to mark unresolved issues.
6. Mark the end of deeply nested control structures.
7. Insert a “fall‑through” comment between case labels lacking a break .
8. Mark empty statements.
Programming Conventions
1. Declare classes that represent primitive data types as final .
2. Build concrete types from primitive and other specific types.
3. Keep classes and methods small.
4. Define subclasses so that any place a superclass can be used, a subclass can be used instead.
5. Make all fields private.
6. Prefer polymorphism over instanceof .
Type Safety:
1. Wrap generic classes with java.lang.Object to provide static type checking.
2. Encapsulate enum types as classes.
3. Use generics wherever possible.
Statements and Expressions:
1. Replace repeated or complex expressions with equivalent methods.
2. Use block statements instead of expression‑based control flow.
3. Use parentheses to make operation order explicit.
4. End the last case in a switch with a break statement.
5. Use equals() instead of == to test object equality.
Construction:
1. Construct objects in a valid state.
2. Do not call non‑final methods from constructors.
3. Use nested constructors to eliminate redundant code.
Exception Handling:
1. Use unchecked (runtime) exceptions for serious, unexpected errors.
2. Use checked exceptions for rare, anticipated errors.
3. Use return codes for predictable state changes.
4. Wrap exceptions only to add information.
5. Do not swallow runtime or error exceptions.
6. Release resources in a finally block.
Assertions:
1. Program according to conventions.
2. Use dead‑code elimination mechanisms to implement assertions.
3. Use assertions to catch logical errors.
4. Use assertions to verify method pre‑conditions and post‑conditions.
Concurrency:
1. Use threads only where appropriate.
Synchronization:
1. Avoid synchronization when possible.
2. Provide synchronized wrappers that expose synchronized interfaces.
3. If only a few operations in a method need synchronization, do not synchronize the entire method.
4. Avoid unnecessary synchronization when reading or writing instance variables.
5. Prefer notify() over notifyAll() .
6. Use double‑checked locking for lazy initialization of synchronized resources.
Efficiency:
1. Use lazy initialization.
2. Avoid creating unnecessary objects.
3. Reuse and reinitialize objects instead of creating new ones.
4. Defer optimization work to later stages.
Packaging Conventions
1. Group types that are frequently used together, changed together, released together, or interdependent into the same package.
2. Apply the common closure principle.
3. Follow the reuse/release equivalence principle.
4. Avoid cyclic dependencies.
5. Isolate unstable classes and interfaces in separate packages.
6. Do not let easily modifiable packages depend on hard‑to‑modify ones.
7. Maximize abstraction to maximize stability.
8. Treat high‑level design and architecture as stable abstractions and organize them into stable packages.
These are just a few simple rules; reading the book is highly recommended.
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.