P3C - Alibaba Java Coding Guidelines

repository·master·Indexed 12 days ago

https://github.com/alibaba/p3c

A static analysis toolset that implements the Alibaba Java Coding Guidelines to help developers maintain code quality, prevent performance risks, and avoid security vulnerabilities. It provides plugins for IntelliJ IDEA and Eclipse, as well as a PMD-based implementation (p3c-pmd v2.1.1) for Maven and Gradle projects. The tool enforces standards across programming conventions, exception logging, unit testing, security, engineering structure, and MySQL database usage.

Tokens
25.4K
Snippets
63
Records
149
Agent score
98%

What's inside P3C

  1. Overview of P3C components

    master

    P3C is a toolset based on the Alibaba Java Coding Guidelines designed to enforce programming best practices. It is composed of three main components that allow you to integrate these rules into your development workflow:

    1. PMD implementations (p3c-pmd): A set of 49 rules implemented via PMD for static code analysis.
    2. IntelliJ IDEA plugin (idea-plugin): An IDE plugin for real-time feedback within IntelliJ IDEA.
    3. Eclipse plugin (eclipse-plugin): An IDE plugin for real-time feedback within the Eclipse IDE.

    For the full set of guidelines, you can refer to the Alibaba Java Coding Guidelines English Version.

  2. Overview of the Alibaba Java Development Manual

    master

    The Alibaba Java Development Manual is a systematic collection of coding standards and best practices derived from Alibaba's technical teams' real-world experience. It aims to improve software delivery quality by addressing dimensions beyond just programming syntax, such as database design, engineering structure, and security.

    Core Dimensions

    The manual is organized into six key dimensions:

    1. Programming Conventions (编程规约)
    2. Exception Logging (异常日志)
    3. Unit Testing (单元测试)
    4. Security Conventions (安全规约)
    5. Engineering Structure (工程结构)
    6. MySQL Database (MySQL数据库)

    Rule Classifications

    Rules are categorized by their level of enforcement and sensitivity to failures:

    • Mandatory (强制): Must be followed.
    • Recommended (推荐): Highly suggested practices.
    • Reference (参考): General guidance.

    Each rule entry typically includes:

    • Description (说明): Extended explanation of the rule.
    • Positive Example (正例): The preferred way to implement or code.
    • Negative Example (反例): Common pitfalls and error cases to avoid.
  3. Use domain model objects correctly across layers

    master

    P3C defines specific object types to manage data flow between layers. Use the appropriate object based on the context:

    • DO (Data Object): Maps 1:1 to database table structures; transmitted upwards from the DAO layer.
    • DTO (Data Transfer Object): Used by the Service or Manager layers to transfer data to external callers.
    • BO (Business Object): Encapsulates business logic; output by the Service layer.
    • AO (Application Object): An abstraction used between the Web and Service layers; closely tied to the display layer and has low reusability.
    • VO (View Object): Used by the Web layer to transfer data to the template rendering engine.
    • Query: Represents data query requests received from upper layers. Note: If a query has more than 2 parameters, it must be encapsulated in a Query object. Do not use Map for parameter transmission.
  4. Guidelines for parameter validation

    master

    Deciding when to perform parameter validation depends on the method's context.

    When to perform parameter validation:

    1. Low-frequency methods: Methods that are called infrequently.
    2. High-cost methods: Methods with high execution time overhead. The cost of validation is negligible compared to the cost of rolling back a failed execution due to bad parameters.
    3. High-stability requirements: Methods requiring extremely high availability and stability.
    4. Public interfaces: Any exposed RPC, API, or HTTP interface.
    5. Sensitive entry points: Methods handling sensitive permissions.

    When parameter validation can be omitted:

    1. High-frequency loop calls: If the method is likely to be called in a loop, validation can be omitted provided the method documentation explicitly states the requirement for external parameter checking.
    2. Low-level internal methods: Methods at the bottom of the call stack (e.g., DAO layer) where errors are unlikely to reach the bottom without being caught earlier in the Service layer.
    3. Private methods: If a private method is only called by code that is guaranteed to have already performed validation.
  5. API Design constraints for secondary libraries

    master

    When designing the public interface of a secondary library, adhere to these constraints:

    • Enum Usage: You may define enum types and use them as method parameters. However, interface return values are not allowed to use enums or POJO objects that contain enums. This prevents tight coupling and potential serialization/compatibility issues.
    • Configuration Minimization: Secondary libraries should avoid having configuration items. At a minimum, do not add unnecessary configuration options.
    • Library Slimming (For Publishers): To avoid conflicts for consumers, library publishers should follow the 'Lean and Controllable' principle: remove unnecessary APIs and dependencies. Include only Service APIs, essential domain models, Utils, constants, and enums. If depending on other libraries, use provided scope so the consumer can manage the specific version. Do not include specific logging implementations; depend only on the logging framework (e.g., SLF4J).
  6. Follow the AIR principle for unit testing

    master

    To ensure high-quality unit tests, they must adhere to the AIR principle. High-quality unit tests are characterized by being:

    • A: Automatic: Tests must be fully automated and non-interactive. They should be executable via CI/CD without manual intervention. Do not use System.out for manual verification; use assert statements instead.
    • I: Independent: Test cases must not call each other or depend on the execution order. Each test should be able to run in isolation.
    • R: Repeatable: Tests must be repeatable and not affected by the external environment (network, services, middleware, etc.). Use Dependency Injection (DI) to inject local (in-memory) or Mock implementations instead of relying on real external dependencies.
  7. Understand the recommended application layering structure

    master

    P3C recommends a layered architecture where upper layers depend on lower layers. The standard hierarchy is:

    1. 开放接口层 (Open Interface Layer): Encapsulates Service methods into RPC interfaces or Web methods into HTTP interfaces. Handles gateway security and traffic control.
    2. 终端显示层 (Terminal Display Layer): Handles template rendering (e.g., Velocity, JS, JSP) and mobile display.
    3. Web层 (Web Layer): Manages access control forwarding, basic parameter validation, and simple non-reusable business logic.
    4. Service层 (Service Layer): Contains specific business logic services.
    5. Manager层 (Manager Layer): A general business processing layer used for:
      • Encapsulating third-party platforms (preprocessing results and converting exceptions).
      • Sinking common capabilities from the Service layer (e.g., caching schemes, middleware handling).
      • Interacting with the DAO layer to compose and reuse multiple DAOs.
    6. DAO层 (Data Access Layer): Handles data interaction with databases like MySQL, Oracle, or Hbase.
    7. 外部接口或第三方平台 (External Interfaces/Third-party Platforms): Includes RPC interfaces from other departments, base platforms, or external HTTP interfaces.
  8. Common Misconceptions in Indexing

    master

    Avoid these extreme misunderstandings when creating indexes:

    1. Over-indexing: Do not create an index for every single query.
    2. Under-indexing: Do not avoid indexes solely because they consume space or slow down INSERT/UPDATE operations.
    3. Resisting Unique Indexes: Do not rely solely on application-layer 'check-then-insert' logic to handle uniqueness; always use a UNIQUE index at the database level.
  9. Use PECS principle for Generic Wildcards

    master

    When using generic wildcards, follow the PECS (Producer Extends, Consumer Super) principle to avoid errors:

    1. <? extends T> (Producer): Use this when you are frequently reading items from the collection. You cannot use the add() method with this wildcard.
    2. <? super T> (Consumer): Use this when you are frequently inserting items into the collection. You cannot use the get() method (with specific type safety) effectively as an interface caller.
  10. Code Comments and Documentation standards

    master

    Requirements for maintaining code documentation:

    • Javadoc: Use /** ... */ format for classes, class variables, and methods.
    • Abstract Methods: Must include Javadoc describing instructions, parameters, return values, and possible exceptions.
    • Metadata: Every class should include author(s) and date information.
    • Single Line Comments: Use // for comments above code and /* ... */ for multi-line comments within methods.
    • Enums: All enumeration fields must be documented using Javadoc style.
  11. Avoid casting ArrayList.subList to ArrayList

    master

    The subList method of an ArrayList returns an internal class java.util.RandomAccessSubList, which is a view of the original list, not an ArrayList itself. Attempting to cast it will result in a ClassCastException.

    Warning: Modifying the original collection (adding or removing elements) while a sublist is in use will cause a ConcurrentModificationException during iteration, addition, or removal in the sublist.