alibaba-java-manual

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

阿里巴巴 Java 开发手册(黄山版)

Alibaba Java Development Manual (Huangshan Edition)

码出高效,码出质量。本 Skill 只描述什么情况下需要什么规范及对应参考文档;规约正文(含说明/正例/反例)见
references/
目录各文件。
Code efficiently, code with quality. This Skill only describes which convention is needed in which situation and the corresponding reference document; the full convention text, including explanations, positive examples, and negative examples, is available in each file in the
references/
directory.

何时激活此 Skill

When to Activate This Skill

  • 编写或审查 Java 代码时(命名、格式、OOP、集合、并发、控制语句、注释)
  • 处理异常、日志、错误码时
  • 编写单元测试、评估测试覆盖率时
  • 做安全审计、权限校验、敏感数据脱敏时
  • 设计 MySQL 表结构、索引、编写 SQL、使用 ORM 时
  • 规划工程分层、二方库依赖、服务器配置时
  • 进行系统设计、用例/状态/时序/类/活动图选型时
  • 制定项目编码规范、团队开发标准、Code Review 时
  • When writing or reviewing Java code, including naming, formatting, OOP, collections, concurrency, control statements, and comments
  • When handling exceptions, logs, and error codes
  • When writing unit tests or evaluating test coverage
  • When conducting security audits, permission checks, or sensitive data masking
  • When designing MySQL schemas and indexes, writing SQL, or using an ORM
  • When planning application layers, second-party library dependencies, or server configurations
  • When conducting system design or selecting use case, state, sequence, class, or activity diagrams
  • When defining project coding standards, team development standards, or conducting a Code Review

规约等级

Convention Levels

等级标识含义
强制【强制】必须遵守,违反将导致故障或严重问题
推荐【推荐】建议遵守,提升质量与可维护性
参考【参考】可选遵守,按实际情况灵活处理

LevelIndicatorMeaning
Mandatory【Mandatory】Must be followed; violations may cause failures or serious problems
Recommended【Recommended】Recommended to improve quality and maintainability
Reference【Reference】Optional; apply flexibly according to the actual situation

场景速查:什么情况查什么规范

Scenario Quick Reference: Which Convention to Consult

按场景定位需要遵守的规约及对应参考文档。审查/编写代码时对照下表,命中即去对应
references/
文件查阅正例反例。
Locate the conventions that should be followed and their corresponding reference documents according to the scenario. When reviewing or writing code, compare against the table below; whenever an item applies, consult the corresponding
references/
file for positive and negative examples.

1. 命名

1. Naming

场景规约要点参考文档
给类/接口命名UpperCamelCase;DO/PO/DTO/BO/VO/UID 例外01 § 命名风格
给方法/变量/参数命名lowerCamelCase01 § 命名风格
给常量命名全大写+下划线,语义完整不嫌长(MAX_STOCK_COUNT)01 § 命名风格
命名是否可用下划线/美元符开头结尾禁止01 § 命名风格
命名是否可拼音英文混用/纯中文禁止;国际通用名(taobao/hangzhou)可视同英文01 § 命名风格
命名是否可用歧视性词语禁止(blackList→blockList,slave→secondary)01 § 命名风格
布尔变量是否加 is 前缀POJO 禁止加 is(防框架序列化错误)01 § 命名风格
抽象类/异常类/测试类命名抽象类 Abstract/Base 开头;异常 Exception 结尾;测试 Test 结尾01 § 命名风格
数组定义方式
int[] arrayDemo
(类型紧挨中括号)
01 § 命名风格
包名规范全小写、点分隔单数、单词01 § 命名风格
Service/DAO 接口与实现命名实现类用 Impl 后缀与接口区分01 § 命名风格
枚举类与成员命名类名带 Enum 后缀;成员全大写下划线01 § 命名风格
各层方法命名get/list/count/save·insert/remove·delete/update 前缀01 § 命名风格
领域模型命名xxxDO/xxxDTO/xxxVO;禁止 xxxPOJO01 § 命名风格
ScenarioConvention SummaryReference Document
Naming a class/interfaceUpperCamelCase; DO/PO/DTO/BO/VO/UID are exceptions01 § Naming Style
Naming a method/variable/parameterlowerCamelCase01 § Naming Style
Naming a constantUppercase letters plus underscores; keep the meaning complete even if the name is long, such as MAX_STOCK_COUNT01 § Naming Style
Whether underscores/dollar signs may appear at the beginning or endProhibited01 § Naming Style
Whether Pinyin may be mixed with English or Chinese may be used aloneProhibited; internationally recognized names such as taobao/hangzhou may be treated as English01 § Naming Style
Whether discriminatory terms may be usedProhibited, such as blackList→blockList and slave→secondary01 § Naming Style
Whether Boolean variables should have an is prefixProhibited in POJOs to prevent framework serialization errors01 § Naming Style
Naming abstract classes, exception classes, and test classesAbstract classes start with Abstract/Base; exception classes end with Exception; test classes end with Test01 § Naming Style
Array declaration style
int[] arrayDemo
, with the type immediately adjacent to the brackets
01 § Naming Style
Package naming conventionsLowercase, dot-separated, singular words01 § Naming Style
Naming Service/DAO interfaces and implementationsUse the Impl suffix for implementation classes to distinguish them from interfaces01 § Naming Style
Naming enum classes and membersClass names end with Enum; member names use uppercase letters and underscores01 § Naming Style
Method naming at each layerUse the get/list/count/save·insert/remove·delete/update prefixes01 § Naming Style
Domain model namingUse xxxDO/xxxDTO/xxxVO; xxxPOJO is prohibited01 § Naming Style

2. 常量

2. Constants

场景规约要点参考文档
代码中出现未定义的字面量禁止魔法值,必须预定义常量01 § 常量定义
long 赋值后缀大写 L,禁止小写 l01 § 常量定义
浮点数后缀统一大写 D/F01 § 常量定义
常量类组织按功能归类分开维护,禁止一个大而全常量类01 § 常量定义
固定范围取值变量优先用 enum01 § 常量定义
ScenarioConvention SummaryReference Document
An undefined literal appears in codeMagic values are prohibited; constants must be predefined01 § Constant Definitions
long assignment suffixUse uppercase L; lowercase l is prohibited01 § Constant Definitions
Floating-point suffixUse uppercase D/F consistently01 § Constant Definitions
Organizing constant classesMaintain separate classes by function; a single catch-all constant class is prohibited01 § Constant Definitions
Variables with a fixed value rangePrefer an enum01 § Constant Definitions

3. 代码格式

3. Code Formatting

场景规约要点参考文档
大括号/缩进/空格/换行非空块左括号前不换行后换行;4 空格缩进禁 Tab01 § 代码格式
运算符/关键词空格二目三目运算符两边加空格;if/for/while 与括号间加空格01 § 代码格式
单行长度不超 120 字符,超长按规则换行01 § 代码格式
方法行数单方法不超 80 行01 § 代码格式
文件编码/换行符UTF-8;Unix 换行01 § 代码格式
方法参数逗号后必须加空格01 § 代码格式
ScenarioConvention SummaryReference Document
Braces/indentation/spaces/line breaksFor non-empty blocks, do not insert a line break before the opening brace and insert one after it; use four spaces for indentation; Tab is prohibited01 § Code Formatting
Spaces around operators and keywordsAdd spaces on both sides of binary and ternary operators; add a space between if/for/while and its parentheses01 § Code Formatting
Single-line lengthMust not exceed 120 characters; wrap long lines according to the rules01 § Code Formatting
Method lengthA method must not exceed 80 lines01 § Code Formatting
File encoding/line endingsUTF-8; Unix line endings01 § Code Formatting
After commas in method parametersA space is required01 § Code Formatting

4. OOP

4. OOP

场景规约要点参考文档
覆写父类方法必须 @Override01 § OOP 规约
equals 调用常量或确定有值对象调 equals;推荐 Objects#equals01 § OOP 规约
整型包装类比较用 equals 不用 ==01 § OOP 规约
浮点数等值判断禁 == 与 equals;用误差范围或 BigDecimal01 § OOP 规约
BigDecimal 比较用 compareTo 不用 equals01 § OOP 规约
BigDecimal 构造禁 BigDecimal(double);用 String 构造或 valueOf01 § OOP 规约
DO 属性类型与字段类型必须匹配(bigint→Long)01 § OOP 规约
POJO/局部变量基本类型 vs 包装类型POJO 与 RPC 必须包装类型;局部变量推荐基本类型01 § OOP 规约
POJO 默认值/toString/serialVersionUID不设默认值;必须 toString;新增属性不改 serialVersionUID01 § OOP 规约
POJO 是否同时有 isXxx/getXxx禁止并存01 § OOP 规约
构造方法是否含业务逻辑禁止,放 init 方法01 § OOP 规约
循环内字符串拼接用 StringBuilder.append01 § OOP 规约
访问控制从严工具类无私有构造;成员最小可见性01 § OOP 规约
ScenarioConvention SummaryReference Document
Overriding a parent class method@Override is required01 § OOP Conventions
Calling equalsCall equals on constants or objects guaranteed to have a value; Objects#equals is recommended01 § OOP Conventions
Comparing wrapper integer typesUse equals instead of ==01 § OOP Conventions
Testing floating-point equalityBoth == and equals are prohibited; use a tolerance range or BigDecimal01 § OOP Conventions
Comparing BigDecimal valuesUse compareTo instead of equals01 § OOP Conventions
Constructing BigDecimalBigDecimal(double) is prohibited; use a String constructor or valueOf01 § OOP Conventions
DO property type and field typeMust match, such as bigint→Long01 § OOP Conventions
Primitive versus wrapper types for POJOs and local variablesPOJOs and RPC parameters must use wrapper types; primitive types are recommended for local variables01 § OOP Conventions
POJO default values/toString/serialVersionUIDDo not set default values; toString is required; do not change serialVersionUID when adding properties01 § OOP Conventions
Whether a POJO may contain both isXxx and getXxxThey must not coexist01 § OOP Conventions
Business logic in constructorsProhibited; use an init method instead01 § OOP Conventions
String concatenation inside a loopUse StringBuilder.append01 § OOP Conventions
Strict access controlUtility classes require a private constructor; members should have the minimum possible visibility01 § OOP Conventions

5. 日期时间

5. Date and Time

场景规约要点参考文档
日期格式化年份小写 y(禁 YYYY 跨年)01 § 日期时间
月/分/时大小写月=M,分=m,24时=H,12时=h01 § 日期时间
取毫秒数System.currentTimeMillis(),禁 new Date().getTime()01 § 日期时间
java.sql.Date/Time/Timestamp禁止使用01 § 日期时间
硬编码一年 365 天禁止,用 LocalDate.lengthOfYear()01 § 日期时间
ScenarioConvention SummaryReference Document
Year in date formattingUse lowercase y; YYYY is prohibited because it may cross year boundaries01 § Date and Time
Case for month/minute/hourMonth=M, minute=m, 24-hour=H, 12-hour=h01 § Date and Time
Obtaining millisecondsUse System.currentTimeMillis(); new Date().getTime() is prohibited01 § Date and Time
java.sql.Date/Time/TimestampProhibited01 § Date and Time
Hard-coding 365 days per yearProhibited; use LocalDate.lengthOfYear()01 § Date and Time

6. 集合

6. Collections

场景规约要点参考文档
覆写 equals 是否覆写 hashCode必须同时覆写01 § 集合处理
判集合是否空isEmpty(),禁 size()==001 § 集合处理
Stream toMap 重复 key必须传 mergeFunction01 § 集合处理
Stream toMap value 为 null会抛 NPE,注意防范01 § 集合处理
subList 强转 ArrayList禁止01 § 集合处理
集合转数组toArray(new T[0])01 § 集合处理
Arrays.asList 修改禁 add/remove/clear01 § 集合处理
foreach 中 remove/add禁止,用 Iterator01 § 集合处理
集合初始化容量指定初始大小(HashMap 默认 16)01 § 集合处理
遍历 MapentrySet 或 forEach01 § 集合处理
ConcurrentHashMap 存 null禁止(抛 NPE)01 § 集合处理
ScenarioConvention SummaryReference Document
Overriding equals without overriding hashCodehashCode must also be overridden01 § Collection Handling
Checking whether a collection is emptyUse isEmpty(); size()==0 is prohibited01 § Collection Handling
Stream toMap with duplicate keysA mergeFunction must be provided01 § Collection Handling
Stream toMap with a null valueIt throws an NPE; guard against this case01 § Collection Handling
Casting subList to ArrayListProhibited01 § Collection Handling
Converting a collection to an arrayUse toArray(new T[0])01 § Collection Handling
Modifying the result of Arrays.asListadd/remove/clear are prohibited01 § Collection Handling
Calling remove/add inside foreachProhibited; use an Iterator01 § Collection Handling
Initial capacity of a collectionSpecify an initial size, such as the default HashMap size of 1601 § Collection Handling
Iterating over a MapUse entrySet or forEach01 § Collection Handling
Storing null in ConcurrentHashMapProhibited because it throws an NPE01 § Collection Handling

7. 并发

7. Concurrency

场景规约要点参考文档
单例线程安全必须保证01 § 并发处理
创建线程命名指定有意义线程名01 § 并发处理
显式 new Thread禁止,必须用线程池01 § 并发处理
线程池创建方式用 ThreadPoolExecutor,禁 Executors(OOM 风险)01 § 并发处理
SimpleDateFormat 线程安全线程不安全,禁 static 或加锁;JDK8 用 DateTimeFormatter01 § 并发处理
ThreadLocal 回收线程池场景必须 try-finally remove01 § 并发处理
锁的性能无锁优先;锁区块尽量小;对象锁优于类锁01 § 并发处理
多资源加锁顺序必须一致,防死锁01 § 并发处理
lock 与 try 块位置lock 在 try 之外01 § 并发处理
tryLock 释放前必须判断是否持锁01 § 并发处理
并发更新防丢失加锁或乐观锁(version)01 § 并发处理
资金敏感信息锁策略悲观锁01 § 并发处理
多线程随机数用 ThreadLocalRandom01 § 并发处理
双重检查锁目标属性须 volatile01 § 并发处理
ScenarioConvention SummaryReference Document
Thread safety of singletonsMust be guaranteed01 § Concurrency Handling
Naming newly created threadsSpecify a meaningful thread name01 § Concurrency Handling
Explicitly creating a Thread with new ThreadProhibited; use a thread pool01 § Concurrency Handling
Creating a thread poolUse ThreadPoolExecutor; Executors is prohibited because of OOM risks01 § Concurrency Handling
Thread safety of SimpleDateFormatIt is not thread-safe; do not define it as static without locking; use DateTimeFormatter on JDK801 § Concurrency Handling
Cleaning up ThreadLocalIn thread-pool scenarios, remove it in a try-finally block01 § Concurrency Handling
Lock performancePrefer lock-free approaches; keep lock blocks as small as possible; prefer object locks over class locks01 § Concurrency Handling
Lock ordering for multiple resourcesThe order must be consistent to prevent deadlocks01 § Concurrency Handling
Position of lock relative to tryPlace the lock outside the try block01 § Concurrency Handling
Before releasing a tryLockCheck whether the lock is still held01 § Concurrency Handling
Preventing lost updates during concurrent updatesUse locking or optimistic locking with a version01 § Concurrency Handling
Locking strategy for financially sensitive informationUse pessimistic locking01 § Concurrency Handling
Random numbers in multiple threadsUse ThreadLocalRandom01 § Concurrency Handling
Double-checked lockingThe target property must be volatile01 § Concurrency Handling

8. 控制语句

8. Control Statements

场景规约要点参考文档
switch 缺 break/default必须终止或注释说明;必须含 default01 § 控制语句
switch 入参 String 为 null必须先判空01 § 控制语句
if/else/for/while 大括号必须用大括号01 § 控制语句
三目运算符 NPE注意自动拆箱01 § 控制语句
高并发等值判断退出禁用等于,用区间判断01 § 控制语句
if-else 层级不超 3 层;用卫语句/策略/状态模式01 § 控制语句
批量接口入参保护必须做01 § 控制语句
参数校验时机低频/高开销/高可用/开放接口/敏感入口须校验01 § 控制语句
ScenarioConvention SummaryReference Document
switch without break/defaultEach branch must terminate or include an explanatory comment; default is required01 § Control Statements
switch argument is a null StringCheck for null first01 § Control Statements
Braces for if/else/for/whileBraces are required01 § Control Statements
NPE caused by a ternary operatorWatch for automatic unboxing01 § Control Statements
Equality-based termination under high concurrencyProhibited; use range comparison01 § Control Statements
if-else nesting depthMust not exceed three levels; use guard clauses, the Strategy pattern, or the State pattern01 § Control Statements
Input protection for batch APIsRequired01 § Control Statements
Timing of parameter validationLow-frequency, high-cost, high-availability, open-interface, and sensitive entry-point parameters must be validated01 § Control Statements

9. 注释

9. Comments

场景规约要点参考文档
类/属性/方法注释Javadoc
/** */
,禁
//
01 § 注释规约
抽象方法注释必须说明做什么、实现要求01 § 注释规约
创建者与创建日期所有类必须加01 § 注释规约
枚举字段注释必须有01 § 注释规约
TODO/FIXME注明标记人、时间、预计处理时间01 § 注释规约
注释掉代码上方说明原因或直接删除01 § 注释规约
ScenarioConvention SummaryReference Document
Class/field/method commentsUse Javadoc
/** */
;
//
is prohibited
01 § Comment Conventions
Abstract method commentsMust explain what the method does and what implementations are required to do01 § Comment Conventions
Creator and creation dateRequired for every class01 § Comment Conventions
Enum field commentsRequired01 § Comment Conventions
TODO/FIXMEInclude the marker owner, time, and expected resolution time01 § Comment Conventions
Commented-out codeExplain the reason above it or delete it01 § Comment Conventions

10. 前后端

10. Frontend and Backend

场景规约要点参考文档
API 协议/路径/方法生产 HTTPS;路径名词复数小写下划线;禁后缀01 § 前后端规约
列表接口空返回返回空数组[]/{},禁 null01 § 前后端规约
错误响应体含 HTTP 状态码+errorCode+errorMessage+用户提示01 § 前后端规约
JSON key 命名lowerCamelCase01 § 前后端规约
超大整数返回前端用 String,禁 Long(精度丢失)01 § 前后端规约
URL 参数长度不超 2048 字节01 § 前后端规约
时间格式yyyy-MM-dd HH:mm:ss,GMT01 § 前后端规约
翻页越界前端<1 返首页;后端>总页数返末页01 § 前后端规约
ScenarioConvention SummaryReference Document
API protocol/path/methodUse HTTPS in production; path nouns should be plural, lowercase, and underscore-separated; suffixes are prohibited01 § Frontend and Backend Conventions
Empty response from a list APIReturn an empty array/object such as []/{}; null is prohibited01 § Frontend and Backend Conventions
Error response bodyInclude the HTTP status code, errorCode, errorMessage, and a user-facing message01 § Frontend and Backend Conventions
JSON key naminglowerCamelCase01 § Frontend and Backend Conventions
Returning very large integers to the frontendUse String; Long is prohibited because it may lose precision01 § Frontend and Backend Conventions
URL parameter lengthMust not exceed 2048 bytes01 § Frontend and Backend Conventions
Time formatyyyy-MM-dd HH:mm:ss, GMT01 § Frontend and Backend Conventions
Pagination out of boundsIf the frontend value is less than 1, return the first page; if the backend value exceeds the total number of pages, return the last page01 § Frontend and Backend Conventions

11. 异常

11. Exceptions

场景规约要点参考文档
可预检查的 RuntimeException预检查规避,禁 catch(如 NPE)02 § 异常处理
异常做流程控制禁止02 § 异常处理
捕获后不处理禁止抛弃,须处理或向上抛02 § 异常处理
事务中 catch 后回滚必须手动回滚02 § 异常处理
finally 关闭资源必须;JDK7 用 try-with-resources02 § 异常处理
finally 中 return禁止02 § 异常处理
RPC/二方包/动态类异常用 Throwable 拦截(NoSuchMethodError)02 § 异常处理
防 NPE 场景拆箱/DB结果/集合元素/远程调用/Session/级联调用02 § 异常处理
自定义异常有业务含义,禁直接抛 RuntimeException/Exception/Throwable02 § 异常处理
跨应用 RPC 返回优先 Result+isSuccess()02 § 异常处理
ScenarioConvention SummaryReference Document
Pre-checkable RuntimeExceptionPrevent it in advance; catching it, such as catching NPE, is prohibited02 § Exception Handling
Using exceptions for flow controlProhibited02 § Exception Handling
Catching an exception without handling itDiscarding it is prohibited; handle it or rethrow it02 § Exception Handling
Rolling back after catching an exception in a transactionA manual rollback is required02 § Exception Handling
Closing resources in finallyRequired; use try-with-resources on JDK702 § Exception Handling
Returning from finallyProhibited02 § Exception Handling
RPC/second-party package/dynamic class exceptionsCatch Throwable, such as NoSuchMethodError02 § Exception Handling
NPE prevention scenariosUnboxing, database results, collection elements, remote calls, Session access, and chained calls02 § Exception Handling
Custom exceptionsMust have business meaning; directly throwing RuntimeException/Exception/Throwable is prohibited02 § Exception Handling
Cross-application RPC return valuePrefer Result+isSuccess()02 § Exception Handling

12. 日志

12. Logging

场景规约要点参考文档
日志 API 选择用 SLF4J 门面,禁直接用 Log4j/Logback02 § 日志规约
日志保存期限至少 15 天;敏感操作相关不少于 6 个月02 § 日志规约
字符串拼接用占位符
{}
02 § 日志规约
trace/debug/info 输出前必须日志级别开关判断02 § 日志规约
重复打印additivity=false02 § 日志规约
System.out/printStackTrace生产环境禁止02 § 日志规约
异常日志内容案发现场+堆栈信息02 § 日志规约
日志输出对象禁直接 JSON 工具转 String,用 toString02 § 日志规约
敏感信息日志脱敏02 § 日志规约
ScenarioConvention SummaryReference Document
Selecting a logging APIUse the SLF4J facade; calling Log4j/Logback directly is prohibited02 § Logging Conventions
Log retention periodAt least 15 days; at least six months for sensitive operations02 § Logging Conventions
String concatenationUse the
{}
placeholder
02 § Logging Conventions
Before outputting trace/debug/info logsA log-level switch check is required02 § Logging Conventions
Duplicate loggingSet additivity=false02 § Logging Conventions
System.out/printStackTraceProhibited in production environments02 § Logging Conventions
Exception log contentInclude the incident context and stack trace02 § Logging Conventions
Objects written to logsDo not convert them to strings with a JSON tool; use toString02 § Logging Conventions
Sensitive information in logsMask the data02 § Logging Conventions

13. 错误码

13. Error Codes

场景规约要点参考文档
错误码格式字符串 5 位 = 来源(A/B/C)+4位数字02 § 错误码
全部正常返回 0000002 § 错误码
错误码是否含版本/等级不体现02 § 错误码
错误码直接给用户禁止02 § 错误码
第三方错误码转义C→B,带原错误码02 § 错误码
错误码完整列表175 条08 § 错误码列表
ScenarioConvention SummaryReference Document
Error code formatA five-character string consisting of a source letter A/B/C and four digits02 § Error Codes
Completely successful resultReturn 0000002 § Error Codes
Whether an error code includes a version or levelIt must not02 § Error Codes
Returning an error code directly to the userProhibited02 § Error Codes
Translating a third-party error codeConvert C to B and retain the original error code02 § Error Codes
Complete error code list175 entries08 § Error Code List

14. 单元测试

14. Unit Testing

场景规约要点参考文档
测试基本原则AIR(自动化/独立/可重复)03 单元测试
测试验证方式用 assert,禁 System.out 人肉验证03 单元测试
测试独立性用例间禁互相调用/依赖顺序03 单元测试
测试粒度类级,一般方法级03 单元测试
测试目录src/test/java03 单元测试
覆盖率目标语句覆盖 70%;核心模块语句+分支 100%03 单元测试
测试用例设计BCDE(边界/正确/设计/错误)03 单元测试
DB 相关测试程序准备数据/自动回滚/前后缀标识03 单元测试
ScenarioConvention SummaryReference Document
Basic testing principlesAIR: Automated, Independent, Repeatable03 Unit Testing
Test verification methodUse assertions; manual verification with System.out is prohibited03 Unit Testing
Test independenceTest cases must not call one another or depend on execution order03 Unit Testing
Test granularityGenerally class-level, with method-level tests where appropriate03 Unit Testing
Test directorysrc/test/java03 Unit Testing
Coverage target70% statement coverage; 100% statement and branch coverage for core modules03 Unit Testing
Test case designBCDE: Boundary, Correct, Design, Error03 Unit Testing
DB-related testsPrepare data in the program, roll back automatically, and use prefix/suffix identifiers03 Unit Testing

15. 安全

15. Security

场景规约要点参考文档
用户页面/功能权限必须校验(防水平越权)04 安全规约
敏感数据展示必须脱敏(手机 139****1219)04 安全规约
SQL 参数参数绑定,禁字符串拼接(防注入)04 安全规约
请求参数校验必须有效性验证(防 OOM/慢查询/SSRF/注入)04 安全规约
HTML 输出用户数据必须过滤转义(防 XSS)04 安全规约
表单/AJAX 提交必须 CSRF 校验04 安全规约
URL 外部重定向必须白名单过滤04 安全规约
短信/邮件/支付等平台资源防重放(数量/频率/验证码)04 安全规约
文件上传校验大小与类型04 安全规约
配置文件密码必须加密04 安全规约
ScenarioConvention SummaryReference Document
User page/function permissionsValidation is required to prevent horizontal privilege escalation04 Security Conventions
Displaying sensitive dataMasking is required, such as 139****1219 for a phone number04 Security Conventions
SQL parametersUse parameter binding; string concatenation is prohibited to prevent injection04 Security Conventions
Request parameter validationValidate parameters for validity to prevent OOM, slow queries, SSRF, and injection04 Security Conventions
Rendering user data in HTMLFilter and escape it to prevent XSS04 Security Conventions
Form/AJAX submissionCSRF validation is required04 Security Conventions
External URL redirectionApply whitelist filtering04 Security Conventions
Platform resources such as SMS, email, and paymentsPrevent replay attacks through quantity/frequency limits and verification codes04 Security Conventions
File uploadsValidate the file size and type04 Security Conventions
Passwords in configuration filesEncryption is required04 Security Conventions

16. 建表

16. Table Design

场景规约要点参考文档
是否字段命名is_xxx,unsigned tinyint05 § 建表规约
表名/字段名小写或数字,禁大写、禁数字开头、禁两下划线间仅数字05 § 建表规约
表名复数禁止05 § 建表规约
保留字禁用(desc/range/match 等)05 § 建表规约
索引命名pk_/uk_/idx_05 § 建表规约
小数类型decimal,禁 float/double05 § 建表规约
varchar 长度不超 5000,超则 text 独立表05 § 建表规约
必备字段id/create_time/update_time05 § 建表规约
物理删除禁止,用逻辑删除05 § 建表规约
分库分表时机单表超 500 万行或 2GB05 § 建表规约
ScenarioConvention SummaryReference Document
Boolean field namingis_xxx with unsigned tinyint05 § Table Design Conventions
Table/field namesUse lowercase letters or numbers; uppercase letters, leading numbers, and numbers between two underscores are prohibited05 § Table Design Conventions
Plural table namesProhibited05 § Table Design Conventions
Reserved wordsProhibited, such as desc/range/match05 § Table Design Conventions
Index namingpk_/uk_/idx_05 § Table Design Conventions
Decimal typeUse decimal; float/double are prohibited05 § Table Design Conventions
varchar lengthMust not exceed 5000; use text in a separate table if it exceeds the limit05 § Table Design Conventions
Required fieldsid/create_time/update_time05 § Table Design Conventions
Physical deletionProhibited; use logical deletion05 § Table Design Conventions
When to partition databases or tablesA single table exceeds five million rows or 2 GB05 § Table Design Conventions

17. 索引

17. Indexes

场景规约要点参考文档
唯一业务字段必须建唯一索引(含组合字段)05 § 索引规约
join 表数量不超 3 表05 § 索引规约
varchar 索引必须指定索引长度05 § 索引规约
左模糊/全模糊查询禁止,走搜索引擎05 § 索引规约
order by 利用索引排序字段放组合索引最后05 § 索引规约
覆盖索引利用避免回表05 § 索引规约
组合索引字段顺序区分度最高最左;等号条件列前置05 § 索引规约
ScenarioConvention SummaryReference Document
Unique business fieldA unique index is required, including for composite fields05 § Index Conventions
Number of tables in a joinMust not exceed three05 § Index Conventions
varchar indexThe index length must be specified05 § Index Conventions
Left-fuzzy or fully fuzzy queriesProhibited; use a search engine05 § Index Conventions
Using an index for order byPlace the sorting field last in a composite index05 § Index Conventions
Covering indexUse it to avoid table lookups05 § Index Conventions
Composite index field orderPlace the column with the highest cardinality leftmost; place equality-condition columns first05 § Index Conventions

18. SQL 语句

18. SQL Statements

场景规约要点参考文档
统计行数count(*),禁 count(列名)/count(常量)05 § SQL 语句
判 NULLISNULL()05 § SQL 语句
sum() 的 NPE用 IFNULL(SUM(col),0)05 § SQL 语句
分页 count 为 0直接返回05 § SQL 语句
外键与级联禁止,应用层解决05 § SQL 语句
存储过程禁止05 § SQL 语句
数据订正先 select 确认再 update/delete05 § SQL 语句
多表列名必须加表别名限定05 § SQL 语句
in 集合数量控制 1000 以内05 § SQL 语句
ScenarioConvention SummaryReference Document
Counting rowsUse count(*); count(column)/count(constant) is prohibited05 § SQL Statements
Checking for NULLUse ISNULL()05 § SQL Statements
NPE from sum()Use IFNULL(SUM(col),0)05 § SQL Statements
Pagination count is zeroReturn immediately05 § SQL Statements
Foreign keys and cascadesProhibited; handle them in the application layer05 § SQL Statements
Stored proceduresProhibited05 § SQL Statements
Correcting dataRun select to verify the records before update/delete05 § SQL Statements
Column names from multiple tablesQualify them with table aliases05 § SQL Statements
Size of an IN collectionKeep it within 1,000 items05 § SQL Statements

19. ORM 映射

19. ORM Mapping

场景规约要点参考文档
查询字段禁 select *,明确写明字段05 § ORM 映射
resultMap必须定义,禁 resultClass;布尔 is_→xxx 映射05 § ORM 映射
参数占位符#{},禁 ${}(注入风险)05 § ORM 映射
queryForList(start,size)不推荐(OOM 风险)05 § ORM 映射
结果集载体禁直接用 HashMap/Hashtable 接收05 § ORM 映射
更新记录必须同时更新 update_time05 § ORM 映射
大而全更新接口禁止,只更新改动字段05 § ORM 映射
ScenarioConvention SummaryReference Document
Query fieldsselect * is prohibited; list the fields explicitly05 § ORM Mapping
resultMapMust be defined; resultClass is prohibited; map is_ to xxx for Boolean fields05 § ORM Mapping
Parameter placeholdersUse #{}; ${} is prohibited because of injection risks05 § ORM Mapping
queryForList(start,size)Not recommended because of OOM risks05 § ORM Mapping
Result set containerDirectly receiving results in HashMap/Hashtable is prohibited05 § ORM Mapping
Updating recordsupdate_time must be updated at the same time05 § ORM Mapping
Update interface that modifies every fieldProhibited; update only the fields that changed05 § ORM Mapping

20. 工程分层

20. Application Layering

场景规约要点参考文档
分层结构开放API/终端显示/Web/Service/Manager/DAO06 § 应用分层
分层异常处理DAO 不打日志;Service 记盘;Web 不上抛跳错误页;开放接口返错误码06 § 应用分层
领域模型DO/DTO/BO/Query/VO 各层职责06 § 应用分层
查询参数封装超 2 参数用 Query,禁 Map06 § 应用分层
ScenarioConvention SummaryReference Document
Layered structureOpen API/Terminal Display/Web/Service/Manager/DAO06 § Application Layering
Exception handling by layerDAO does not log; Service writes logs; Web does not rethrow or jump directly to an error page; Open API returns an error code06 § Application Layering
Domain modelsResponsibilities of DO/DTO/BO/Query/VO at each layer06 § Application Layering
Query parameter encapsulationUse a Query object for more than two parameters; Map is prohibited06 § Application Layering

21. 二方库依赖

21. Second-Party Library Dependencies

场景规约要点参考文档
GAV 命名GroupId 最多 4 级;ArtifactId 产品线-模块名06 § 二方库依赖
版本号主.次.修订;起始 1.0.006 § 二方库依赖
线上依赖 SNAPSHOT禁止06 § 二方库依赖
同 GAV 不同 Version禁止06 § 二方库依赖
统一版本变量依赖群定义统一版本变量06 § 二方库依赖
pom 依赖管理依赖放 dependencies,版本仲裁放 dependencyManagement06 § 二方库依赖
接口返回值用枚举禁止06 § 二方库依赖
ScenarioConvention SummaryReference Document
GAV namingGroupId may contain at most four levels; ArtifactId uses product-line-module-name06 § Second-Party Library Dependencies
Version numberUse major.minor.patch and start with 1.0.006 § Second-Party Library Dependencies
SNAPSHOT dependency in productionProhibited06 § Second-Party Library Dependencies
Same GAV with different versionsProhibited06 § Second-Party Library Dependencies
Unified version variablesDefine unified version variables in the dependency group06 § Second-Party Library Dependencies
pom dependency managementPut dependencies in dependencies and perform version arbitration in dependencyManagement06 § Second-Party Library Dependencies
Using an enum as an interface return valueProhibited06 § Second-Party Library Dependencies

22. 服务器

22. Servers

场景规约要点参考文档
远程调用超时必须设置06 § 服务器
高并发 time_wait调小 tcp_fin_timeout06 § 服务器
文件句柄数调大 fd06 § 服务器
OOM dump-XX:+HeapDumpOnOutOfMemoryError06 § 服务器
Xms/Xmx生产环境设为相同06 § 服务器
ScenarioConvention SummaryReference Document
Remote call timeoutMust be configured06 § Servers
High-concurrency time_waitReduce tcp_fin_timeout06 § Servers
File descriptor countIncrease fd06 § Servers
OOM dump-XX:+HeapDumpOnOutOfMemoryError06 § Servers
Xms/XmxSet them to the same value in production environments06 § Servers

23. 系统设计

23. System Design

场景规约要点参考文档
存储方案/数据结构设计评审通过并沉淀文档07 设计规约
用例图选用User>1 类且 UseCase>507 设计规约
状态图选用业务对象状态>307 设计规约
时序图选用调用链涉及对象>307 设计规约
类图选用模型类>5 且依赖复杂07 设计规约
活动图选用>2 对象协作且流程复杂07 设计规约
弱依赖识别必须设计降级/应急预案07 设计规约
设计原则单一职责/聚合优于继承/依赖倒置/开闭/DRY07 设计规约
敏捷开发误区≠讲故事+编码+发布07 设计规约
无障碍设计tab 聚焦/验证码多方式/自定义控件交互07 设计规约

ScenarioConvention SummaryReference Document
Storage solution/data structure designReview and approval are required, followed by documentation07 Design Conventions
Selecting a use case diagramUser>1 and UseCase>507 Design Conventions
Selecting a state diagramBusiness object states>307 Design Conventions
Selecting a sequence diagramObjects involved in the call chain>307 Design Conventions
Selecting a class diagramModel classes>5 with complex dependencies07 Design Conventions
Selecting an activity diagramMore than two collaborating objects with a complex process07 Design Conventions
Identifying weak dependenciesA degradation strategy and contingency plan must be designed07 Design Conventions
Design principlesSingle responsibility, composition over inheritance, dependency inversion, open/closed principle, and DRY07 Design Conventions
Agile development misconceptionAgile is not equivalent to telling stories, writing code, and releasing07 Design Conventions
Accessibility designTab focus, multiple CAPTCHA methods, and custom control interactions07 Design Conventions

反模式红线(出现即停)

Anti-Pattern Red Lines (Stop Immediately When Found)

反模式违反规约参考
变量名拼音英文混用/中文命名01 § 命名风格
代码出现魔法值常量01 § 常量定义
用 Tab 缩进 / 单行超 120格式01 § 代码格式
param.equals("test")
OOP01 § OOP 规约
Integer 用 == 比较OOP01 § OOP 规约
new BigDecimal(0.1)
OOP01 § OOP 规约
POJO 布尔加 is 前缀OOP01 § OOP 规约
new Date().getTime()
日期01 § 日期时间
foreach 里 remove/add集合01 § 集合处理
Executors.newXxx
建线程池
并发01 § 并发处理
SimpleDateFormat 定义为 static 不加锁并发01 § 并发处理
finally 里 return异常02 § 异常处理
catch NPE 而非预检查异常02 § 异常处理
直接用 Log4j API日志02 § 日志规约
生产环境 System.out/printStackTrace日志02 § 日志规约
SQL 字符串拼接参数安全04 安全规约
select * 查询ORM05 § ORM 映射
用 ${} 传参ORM05 § ORM 映射
物理删除建表05 § 建表规约
用外键/级联/存储过程SQL05 § SQL 语句
线上依赖 SNAPSHOT依赖06 § 二方库依赖

Anti-PatternViolated ConventionReference
Variable names mix Pinyin with English or use ChineseNaming01 § Naming Style
Magic values appear in codeConstants01 § Constant Definitions
Tab indentation or a line longer than 120 charactersFormatting01 § Code Formatting
param.equals("test")
OOP01 § OOP Conventions
Comparing an Integer with ==OOP01 § OOP Conventions
new BigDecimal(0.1)
OOP01 § OOP Conventions
Adding an is prefix to a POJO Boolean fieldOOP01 § OOP Conventions
new Date().getTime()
Date and time01 § Date and Time
Calling remove/add inside foreachCollections01 § Collection Handling
Creating a thread pool with Executors.newXxxConcurrency01 § Concurrency Handling
Defining SimpleDateFormat as static without lockingConcurrency01 § Concurrency Handling
Returning from finallyExceptions02 § Exception Handling
Catching NPE instead of checking in advanceExceptions02 § Exception Handling
Calling the Log4j API directlyLogging02 § Logging Conventions
Using System.out/printStackTrace in productionLogging02 § Logging Conventions
Concatenating SQL parameters as stringsSecurity04 Security Conventions
Using a select * queryORM05 § ORM Mapping
Passing parameters with ${}ORM05 § ORM Mapping
Physical deletionTable design05 § Table Design Conventions
Using foreign keys, cascades, or stored proceduresSQL05 § SQL Statements
Using a SNAPSHOT dependency in productionDependencies06 § Second-Party Library Dependencies

参考文档索引

Reference Document Index

详细规约正文(含说明、正例、反例、完整条目)存放于
references/
目录:
文件内容子章节
01-coding-conventions.md一、编程规约命名风格/常量定义/代码格式/OOP 规约/日期时间/集合处理/并发处理/控制语句/注释规约/前后端规约/其他
02-exception-logging.md二、异常日志错误码/异常处理/日志规约
03-unit-testing.md三、单元测试AIR/BCDE/覆盖率/数据准备
04-security.md四、安全规约权限/脱敏/注入/XSS/CSRF/上传/加密
05-mysql-database.md五、MySQL 数据库建表规约/索引规约/SQL 语句/ORM 映射
06-engineering-structure.md六、工程结构应用分层/二方库依赖/服务器
07-design-conventions.md七、设计规约存储评审/各类图选型/设计原则
08-appendix.md附录前言/版本历史/专有名词解释/错误码列表(175条)

来源:阿里巴巴集团技术团队 · 全球 Java 社区开发者
版本:1.7.1 黄山版(2022.02.03)
愿景:码出高效,码出质量
The full convention text, including explanations, positive examples, negative examples, and complete entries, is stored in the
references/
directory:
FileContentSubchapters
01-coding-conventions.mdI. Programming ConventionsNaming Style/Constant Definitions/Code Formatting/OOP Conventions/Date and Time/Collection Handling/Concurrency Handling/Control Statements/Comment Conventions/Frontend and Backend Conventions/Other
02-exception-logging.mdII. Exceptions and LoggingError Codes/Exception Handling/Logging Conventions
03-unit-testing.mdIII. Unit TestingAIR/BCDE/Coverage/Data Preparation
04-security.mdIV. Security ConventionsPermissions/Masking/Injection/XSS/CSRF/Uploads/Encryption
05-mysql-database.mdV. MySQL DatabasesTable Design Conventions/Index Conventions/SQL Statements/ORM Mapping
06-engineering-structure.mdVI. Engineering StructureApplication Layering/Second-Party Library Dependencies/Servers
07-design-conventions.mdVII. Design ConventionsStorage Review/Diagram Selection/Design Principles
08-appendix.mdAppendixPreface/Version History/Glossary of Proper Nouns/Error Code List (175 entries)

Source: Alibaba Group Technical Team · Global Java Community Developers
Version: 1.7.1 Huangshan Edition (2022.02.03)
Vision: Code efficiently, code with quality