Fundamentals 47 min read

Mastering Alibaba’s Java Coding Standards: Essential Rules for Clean, Scalable Code

This article provides a comprehensive English interpretation of Alibaba’s Java Development Manual, detailing mandatory and recommended naming conventions, constant definitions, formatting rules, OOP guidelines, collection handling, concurrency practices, control statements, and comment standards, all illustrated with clear code examples and practical explanations.

21CTO
21CTO
21CTO
Mastering Alibaba’s Java Coding Standards: Essential Rules for Clean, Scalable Code

1 Naming Conventions

1.1 Mandatory: Identifiers must not start or end with an underscore or dollar sign. Example of violations: name, __name, Object$.

1.2 Mandatory: Do not mix pinyin and English or use Chinese characters directly in identifiers. Use clear English names; e.g., alibaba / taobao / youku / hangzhou are acceptable.

1.3 Mandatory: Class names must follow UpperCamelCase, except for domain model suffixes such as DO, BO, DTO, VO.

1.4 Mandatory: Method, parameter, member, and local variable names must use lowerCamelCase.

1.5 Mandatory: Constant names must be all uppercase with underscores separating words.

1.6 Mandatory: Abstract classes start with Abstract or Base; exception classes end with Exception; test classes end with Test.

1.7 Mandatory: Array types use brackets after the type, e.g., String[] args.

1.8 Mandatory: Boolean fields in POJOs must not be prefixed with is to avoid serialization issues.

1.9 Mandatory: Package names must be lowercase, single‑word, and use singular forms unless the class name itself is plural.

1.10 Mandatory: Avoid obscure abbreviations; use clear, full words.

1.11 Recommended: Include the design pattern name in class names when applicable.

2 Constant Definitions

2.1 Mandatory: Do not use magic numbers; define them as constants.

2.2 Mandatory: Use uppercase L for long literals.

2.3 Recommended: Group constants by functional area (e.g., CacheConsts, ConfigConsts) instead of a single monolithic class.

2.4 Recommended: Define a hierarchy of constant sharing levels: cross‑application, application‑wide, module‑level, package‑level, and class‑level.

2.5 Recommended: Use Enum types for a fixed set of values with optional extra fields.

2.6 Mandatory: Do not modify serialVersionUID unless the class becomes incompatible.

2.7 Mandatory: Constructors must not contain business logic; move initialization to an init method.

2.8 Mandatory: POJOs must implement toString() for easier debugging.

3 Formatting Rules

3.1 Mandatory: Braces style – opening brace on the same line, then newline; closing brace on its own line. No newline before opening brace.

3.2 Mandatory: No spaces before opening parenthesis or after closing parenthesis.

3.3 Mandatory: Reserve a single space between keywords (if, for, while, switch, do) and their parentheses.

3.4 Mandatory: All operators must be surrounded by a single space.

3.5 Mandatory: Indent with four spaces; never use tab characters.

3.6 Mandatory: Limit line length to 120 characters; break lines after commas, operators, or method‑call dots.

3.7 Mandatory: In method signatures, place parameters on the same line unless they exceed the length limit.

3.8 Recommended: Order methods as public/protected, then private, then getters/setters.

3.9 Recommended: Use StringBuilder for string concatenation inside loops; avoid String concatenation.

3.10 Recommended: Mark variables that never change as final.

3.11 Recommended: Avoid using Object.clone(); prefer copy constructors or factory methods.

3.12 Recommended: Apply strict access modifiers: private for internal members, protected for subclass access, and public only when necessary.

4 OOP Guidelines

4.1 Mandatory: Access static members via the class name, not an instance.

4.2 Mandatory: All overridden methods must be annotated with @Override.

4.3 Mandatory: Use varargs only when all parameters share the same type and meaning; avoid Object... varargs.

4.4 Mandatory: Do not change the signature of public or third‑party interfaces; deprecate with @Deprecated and provide a replacement.

4.5 Mandatory: Do not use outdated classes or methods.

4.6 Mandatory: Call equals() on a constant or known non‑null object to avoid NullPointerException.

4.7 Mandatory: Use equals() for comparing wrapper objects; == only for reference equality.

4.8 Mandatory: POJO fields must use wrapper types; RPC methods must also use wrappers; local variables may use primitives.

4.9 Mandatory: Do not assign default values to POJO fields; let callers set them explicitly.

5 Collection Handling

5.1 Mandatory: When overriding equals(), also override hashCode(). Collections like Set and Map rely on both.

5.2 Mandatory: Do not cast the result of subList() to ArrayList; it returns a view.

5.3 Mandatory: Modifying the original list while iterating a sub‑list causes ConcurrentModificationException.

5.4 Mandatory: Convert collections to arrays using toArray(T[] a) with an appropriately sized array.

5.5 Mandatory: Arrays.asList() returns a fixed‑size list; do not invoke add, remove, or clear on it.

5.6 Mandatory: Use proper generic wildcards: ? extends T for producers (read‑only), ? super T for consumers (write‑only).

5.7 Mandatory: Do not modify a collection inside a foreach loop; use an Iterator and its remove() method.

5.8 Mandatory: Comparator implementations must be consistent, antisymmetric, and transitive; handle equality explicitly.

5.9 Recommended: Initialize collections with an estimated capacity to improve performance.

5.10 Recommended: Iterate Map with entrySet() rather than keySet() for efficiency.

5.11 Recommended: Be aware of whether a map implementation permits null keys/values (e.g., HashMap allows, ConcurrentHashMap does not).

5.12 Recommended: Use Set for deduplication; consider Bloom filters for large‑scale approximate deduplication.

6 Concurrency

6.1 Mandatory: Singleton access must be thread‑safe; all methods of the singleton must also be thread‑safe.

6.2 Mandatory: Give threads meaningful names for easier debugging.

6.3 Mandatory: Use thread pools instead of creating raw threads.

6.4 Mandatory: Prefer ThreadPoolExecutor over Executors factory methods to avoid unbounded queues or thread counts.

6.5 Mandatory: SimpleDateFormat is not thread‑safe; use thread‑local instances or DateUtils.

6.6 Mandatory: Prefer lock‑free data structures; if locking is required, lock the smallest possible scope.

7 Control Statements

7.1 Mandatory: Every switch case must end with break, return, or a comment indicating fall‑through; include a default case.

7.2 Mandatory: Always use braces for if, else, for, while, and do statements.

7.3 Recommended: Reduce nesting of else by returning early.

7.4 Recommended: Extract complex boolean expressions into well‑named variables.

7.5 Recommended: Move invariant operations out of loops (object creation, DB connections, try‑catch blocks).

7.6 Recommended: Validate method parameters in high‑risk or public APIs; skip validation for low‑cost internal methods.

8 Comment Conventions

8.1 Mandatory: Use Javadoc ( /** ... */) for classes, fields, and methods; avoid line comments ( //) for documentation.

8.2 Mandatory: Abstract methods and interface methods must have Javadoc describing purpose, parameters, return values, and exceptions.

8.3 Mandatory: Include author information in class Javadoc.

8.4 Mandatory: Single‑line comments inside methods should be placed on a separate line above the code; multi‑line comments should be aligned with the code.

8.5 Mandatory: Enum constants must have Javadoc explaining each value.

8.6 Recommended: Write explanatory comments in the native language (Chinese) when it conveys meaning better; keep technical terms in English.

8.7 Recommended: Keep comments in sync with code changes, especially for signatures and core logic.

8.8 Recommended: When commenting out code, include a reason; otherwise delete it (version control retains history).

8.9 Recommended: Comments should be concise, accurate, and add value; avoid redundant comments that restate obvious code.

8.10 Recommended: Use TODO/FIXME tags with author and date for pending work, and clean them up regularly.

9 Miscellaneous

9.1 Mandatory: Pre‑compile regular expressions to improve performance.

9.2 Mandatory: In Velocity templates, access POJO properties directly; boolean getters use isXxx() for primitive boolean and getXxx() for Boolean.

9.3 Mandatory: Use ${var} in Velocity to output variables safely.

9.4 Mandatory: Prefer Random.nextInt() / nextLong() over scaling Math.random() for integer random numbers.

9.5 Mandatory: Use System.currentTimeMillis() instead of new Date().getTime() for timestamps.

9.6 Recommended: Keep Velocity templates free of complex logic; perform calculations in Java code.

9.7 Recommended: Specify initial capacities for data structures to avoid uncontrolled memory growth.

9.8 Recommended: Remove dead code and obsolete configurations to keep the codebase clean.

Author: Li Yanpeng
Map nullability table
Map nullability table
Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Javacoding standards
21CTO
Written by

21CTO

21CTO (21CTO.com) offers developers community, training, and services, making it your go‑to learning and service platform.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.