JAVA编程规范

合集下载

Java编程规范总结

Java编程规范总结

Java编程规范总结命名:1. 为包、类、⽅法、变量取⼀个好名字,使代码易于理解2. 禁⽌使⽤魔⿁数字3. 常量命名,由全⼤写单词组成,单词间⽤下划线分隔,且使⽤ static final修饰4. 变量、属性命名,使⽤名词,并采⽤⾸字母⼩写的驼峰命名法5. ⽅法的命名,⽤动词和动宾结构,并采⽤⾸字母⼩写的驼峰命名法6. 类和接⼝的命名,采⽤⾸字母⼤写的驼峰命名法7. 包的命名,由⼀个或若⼲个单词组成,所有的字母均为⼩写8. 数组声明的时候使⽤ int[] index,⽽不要使⽤ int index[]注释:1. 尽量⽤代码来解释⾃⼰2. 注释应解释代码的意图,⽽不是描述代码怎么做的3. 保证注释与代码⼀致,避免产⽣误导4. 注释应与其描述代码位置相邻,放在所注释代码上⽅或右⽅,并与代码采⽤同样缩进5. 不要⽤注释保留废弃代码6. 不要⽤注释记录修改⽇志7. ⼀般单⾏注释⽤//,块注释⽤,JavaDoc注释⽤排版:1. 团队应遵守⼀致的排版风格2. 将排版风格固化到IDE的代码格式化配置⽂件中,并让整个团队使⽤3. 在不同的概念之间,增加空⾏4. 将逻辑紧密相关的代码放在⼀起5. 控制⼀⾏的宽度,不要超过120个字符6. 在不同的概念间(关键字、变量、操作符等)增加空格,以便清楚区分概念7. 采⽤缩进来区分不同层次的概念8. 将局部变量的作⽤域最⼩化9. 给if、for、do、while、switch等语句的执⾏体加⼤括号{}10. 控制⽂件的长度,最好不要超过500⾏变量和类型:1. 谨慎使⽤静态成员变量2. 避免随意进⾏类型强制转换,应改善设计,或在转换前⽤instanceof进⾏判断33. 需要精确计算时不要使⽤float和double4. 不能⽤浮点数作为循环变量5. 浮点型数据判断相等不能直接使⽤==6. 避免同⼀个局部变量在前后表达不同的含义7. 不要在单个的表达式中对相同的变量赋值超过⼀次8. 基本类型优于包装类型,注意合理使⽤包装类型⽅法:1. ⽅法设计的第⼀原则是要短⼩2. ⽅法设计应遵循单⼀职责原则(SRP),⼀个⽅法仅完成⼀个功能3. ⽅法设计应遵循单⼀抽象层次原则(SLAP)4. ⽅法设计应遵循命令与查询职责分离原则(CQRS)5. 不要把⽅法的⼊参当做⼯作变量/临时变量,除⾮特别需要6. 使⽤类名调⽤静态⽅法,⽽不要使⽤实例或表达式来调⽤7. 应明确规定对接⼝⽅法参数的合法性检查由调⽤者负责还是由接⼝⽅法本⾝负责8. ⽅法的参数个数不宜过多9. 谨慎使⽤可变数量参数的⽅法包、类和接⼝:1. 类和接⼝的设计应遵循⾯向对象SOLID设计原则2. 类的设计应遵循迪⽶特法则3. 类的设计应遵循“Tell,Don't ask”原则4. 类设计时优选组合⽽不是继承5. 除提供给外部使⽤的全局常量外,应尽量避免类成员变量被外部直接访问6. 避免在⽆关的变量或⽆关的概念之间重⽤名字,避免隐藏(hide)、遮蔽(shadow)和遮掩(obscure)7. 覆写(override)——⼦类与⽗类间8. 重载(overload)——类内部9. 隐藏(hide)——⼦类与⽗类间10. 遮蔽(shadow)——类内部11. 遮掩(obscure)——类内部12. 不要在⽗类的构造⽅法中调⽤可能被⼦类覆写的⽅法13. 覆写equals⽅法时,应同时覆写hashCode⽅法14. ⼦类覆写⽗类⽅法时应加上@Override注解15. 接⼝定义中去掉多余的修饰词16. 设计时,考虑类的可变性最⼩化异常:1. 只针对真正异常的情况才使⽤exception机制2. 在抛出异常的细节信息中,应包含能捕获失败的信息3. 对可恢复的情况使⽤受检异常(checked exception),对编程错误使⽤运⾏时异常(runtime exception)4. 不要忽略异常5. ⽅法注释和⽂档中要包含所抛出异常的说明6. ⽅法抛出的异常,应该与本⾝的抽象层次相对应7. 对第三⽅API抛出⼤量各类异常进⾏封装8. 使⽤异常来做错误处理,⽽⾮错误码9. 在finally块中不要使⽤return、break或continue使finally块⾮正常结束10. 不要直接捕获受检异常的基类Exception11. ⼀个⽅法不应抛出太多类型的异常12. 充分利⽤断⾔⽇志:1. ⽇志信息准确、繁简得当,满⾜快速定位的需要2. ⽇志的记录,不要使⽤ System.out 与 System.err 进⾏控制台打印,应该使⽤专⽤的⽇志⼯具(⽐如:slf4j+logback)进⾏处理3. ⽇志⼯具对象logger应声明为private static final4. ⽇志应分等级5. ⽇志中不要记录敏感信息多线程并发:1. 多线程访问同⼀个可变变量,需增加同步机制2. 禁⽌不加控制地创建新线程3. 创建新线程时需指定线程名4. 使⽤Thread对象的setUncaughtExceptionHandler⽅法注册Runtime异常的处理者(v1.5+)5. 不要使⽤Thread.stop⽅法,因为该⽅法本质是不安全的,使⽤它可能会导致数据遭到破坏6. 不要依赖线程调度器、线程优先级和yield()⽅法7. 采⽤Java1.5提供新并发⼯具代替wait和notify(v1.5+)8. 使⽤线程安全集合在多线程间共享可变数据9. 多线程操作同⼀个字符串相加,应采⽤StringBuffer10. 针对线程安全性,需要进⾏⽂档(javadoc)说明运算和表达式:1. 不要写复杂的表达式2. 运算时应避免产⽣溢出3. 采⽤括号明确运算的优先级控制语句:1. 采⽤for-each代替传统的for循环(v1.5+)2. 在switch语句的每⼀个case、和default中都放置⼀条break语句序列化:1. 尽量不要实现Serializable接⼝2. 序列化对象中的HashMap、HashSet或HashTable等集合不能包含对象⾃⾝的引⽤3. 实现Serializable接⼝的可序列化类应该显式声明 serialVersionUID泛型:1. 在集合中使⽤泛型(v1.5+)2. 类的设计可优先考虑泛型(v1.5+)3. ⽅法的设计可优先考虑泛型(v1.5+)4. 优先使⽤泛型集合,⽽不是数组(v1.5+)其他语⾔特性:1. 新代码不要使⽤已标注为@deprecated的⽅法2. 使⽤JDK⾃带的API或⼴泛使⽤的开源库,不要⾃⼰写类似的功能。

java 开发规范

java 开发规范

java开发规范(一)java命名规范1、变量、成员、方法名统一采用驼峰命名(lowerCamelCase),做到见语知其义例子:变量——用户数据(userList)、方法——getUserData(int type)等。

说明:正常变量定义使用驼峰命名,特殊的如DTO\VO\DO等除外。

2、类名的定义(1)普通类名采用大写字母开始;(2)抽象类采用Abstract或Base开头。

例子:普通类——class UserModel,抽象类——abstract class AbstractUserDefinition等。

3、常量、类型、接口、子类的定义(1)常量使用全大写且单词之间用"_“隔开; (2)boolean变量不能使用is开头;(3)接口尽量不要修饰符、子类紧跟接口追加Impl。

例子:常量——SORT_TYPE,布尔类型——flag,接口——UserService,实现类——UserServiceImpl等。

说明:常量不可组装,需要原子性定义,不能出现"KEY”+SORT_TYPE 这种内部出现。

4、包名、异常、枚举、方法名称的定义(1)包名一律采用小写; (2)异常都采用_Exception结尾; (3)枚举都是以Enum结尾;(4)方法名称——根据方法内容采用如插入insert-*。

例子:异常——UserException,包名——com.test,枚举——UserEnum,方法名称——insertUser等。

5、领域模型定义规范:主要是以VO\DTO\DO等结尾例子:用户数据——UserDTO等(1)数据对象:xxxDO,xxx 即为数据表名。

(2)数据传输对象:xxxDTO,xxx为业务领域相关的名称。

(3)展示对象:xxxVO,xxx一般为网页名称。

(4)POJO是DO/DTO/BO/VO的统称,禁止命名成xxxPOJO。

(二)代码格式规范1、括号代码要求左大括号前不换行、左大括号后换行、右大括号前换行、右大括号后还有else等代码则不换行;表示终止的右大括号后必须换行。

JAVA编程规范(修订)

JAVA编程规范(修订)

JAVA编程规范1.1 Java文件名与文件组织结构1.一个java源文件不应该超过2 000行。

2.在Java源文件中应该包含一个单一的公共类(class)或接口(interface),这个公共类或公共接口,应该是这个源文件的第一个类或接口。

3.一个Java源文件一般由下面的顺序构成:(1)文件注释头(2)包名(package)(3)引入(import)声明(4)类(class)或接口(interface)的声明部分1.2 Java文件注释头Java类文件注释头是用来描述该类功能及其特点,以及相关开发信息的,如该类的关联类(通常情况下不描述Java系统核心类如java.util.Vector, ng.Thread等)、开发公司或单位、版权、作者、代码审定人该类所支持的JDK版本、该类版本、开发日期、最后更改日期、修改人、复审人等信息,下面就是一个Java类文件注释头:/****************************************************************** 该类功能及其特点的描述(例如:该类是用来……)** 该类未被编译测试过。

** @see(与该类相关联的类):(AnatherClass.java)*** 开发公司或单位:××软件有限公司研发中心** 版权:本文件版权归属××公司研发中心*** @author(作者):必胜利** @since(该文件所支持的JDK版本):Jdk1.3 或JDK1.42.在重点同时难以理解的地方另加注释。

方法体内的注释应该与其所描述的代码位于同一个层次上。

在一个块注释之前一般有一空白行用于做区分代码与注释的边界。

1.7 变量的声明初始化与放置1.7.1 变量声明1.在一般情况下我们建议每一行代码,只声明一个变量;2.如果变量名称较短并且又是同一数据类型同一结构类型,并且没有给变量初始化则可以在同一行声明;1.7.2 变量初始化尽量在变量声明的地方初始化,如果变量的初始化与有待于计算或处理后的值有关,则我们可以在取得这个值后对变量做初始化。

java 编程规范

java 编程规范

java 编程规范Java编程规范是为了促进Java代码的可读性、可维护性和可扩展性而制定的标准。

以下是一些常见的Java编程规范:一、命名规范1. 类名、接口名、枚举名首字母大写,采用驼峰命名法。

2. 变量名、方法名首字母小写,采用驼峰命名法。

3. 常量名全部大写,使用下划线分割单词。

4. 包名全部小写,使用点号分割单词。

二、代码格式1. 使用4个空格缩进。

2. 每行代码长度不超过80个字符。

3. 在二元运算符(如赋值、算术运算、逻辑运算)两侧添加空格。

4. 在逗号、冒号、分号之后添加空格。

5. 在左花括号之后和右花括号之前添加空格。

6. 在注释之前添加空格。

三、代码结构1. 类的成员按照作用域排列,先是静态成员,然后是实例成员。

2. 类的方法按照功能排列,先是构造方法,然后是其他方法。

3. 每个类只负责一个功能,遵循单一职责原则。

4. 使用适当的访问修饰符控制成员变量和方法的访问级别。

四、异常处理1. 不要捕获异常而不做任何处理,应该记录日志或者抛出更高级别的异常。

2. 不要将整个方法体放在try-catch块中,应该只捕获需要处理的异常。

3. 不要使用异常控制程序的流程,应该使用条件语句或者循环结构。

五、注释规范1. 使用Javadoc注释对类、方法、参数、返回值进行说明。

2. 在每个类的头部使用Javadoc注释描述该类的功能。

3. 使用内联注释对代码进行解释、补充和说明。

4. 注释应该清楚、简明、不冗余,遵循自然语言的习惯。

六、其他规范1. 避免使用魔法数值,应该使用常量或者枚举来表示。

2. 使用块注释对重要的代码块进行标注,方便阅读和查找。

3. 使用业界公认的缩写和术语,避免拼写错误和歧义。

4. 使用合适的数据结构和算法来解决问题,避免低效的代码。

以上仅是Java编程规范的一部分,具体的规范还需要根据具体的项目和团队来制定。

遵循编程规范可以提高代码质量和可维护性,提升团队的协作效率。

Java语言编程规范(华为公司)

Java语言编程规范(华为公司)

Java语言编程规范(华为公司)DKBA华为技术有限公司企业技术规范DKBAXXXX-2001.12代替(DKBA200106-003)Java语言编程规范2001-12-XX发布2001-12-XX实施华为技术有限公司发布VVVVVVV VVVVVVVVVVVX。

XVX.X VX.X VX.X VX.XVX.X 目次前言 .............................................................................. .. (3)1 范围112 规范性引用文件113 术语和定义114 排版规范124.1 规则121.*程序块要采用缩进风格编写,缩进12的空格数为4个。

122.*分界符(如大括号‘{’和‘}’)应各独占一行并且位于同一列,同时与引用它们的语句左对齐。

在函数体的开始、类和接口的定义、以及if、for、do、while、switch、case语句中的程序都要采用如上的缩进方式。

133.*较长的语句、表达式或参数(>80字符)要分成多行书写,长表达式要在低优先级操作符处划分新行,操作符放在新行之首,划分出的新行要进行适当的缩进,使排版整齐,语句可读。

134.*不允许把多个短语句写在一行中,即一行只写一条语句5.*if, for, do, while, case,13switch, default 等语句自占一行,且if, for, do, while等语句的执行语句无论多少都要加括号{}。

6.*相对独立的程序块之间、变量说明13之后必须加空行。

7.*对齐只使用空格键,不使用TAB键。

14VVVVVVV VVVVVVVVVVVX。

XVX.X VX.X VX.X VX.XVX.X 8.*在两个以上的关键字、变量、常量14进行对等操作时,它们之间的操作符之前、之后或者前后要加空格;进行非对等操作时,如果是关系密切的立即操作符(如.),后不应加空格。

java代码规范

java代码规范

java代码规范Java代码规范是一套约定俗成的编程规范,旨在提高代码的可读性、可维护性和可重用性。

以下是一些常见的Java代码规范:命名规范:1. 类名使用大驼峰命名法,例如MyClass。

2. 方法名和变量名使用小驼峰命名法,例如myMethod。

3. 常量名使用全大写字母和下划线,例如MAX_VALUE。

4. 包名使用全小写字母,例如com.example.mypackage。

代码格式规范:1. 使用四个空格缩进,避免使用制表符。

2. 每行代码不超过80个字符,超出则换行。

3. 使用空格将运算符、逗号和分号与操作数分开,例如"int a =b + c;"。

4. 在左括号前后加一个空格,例如"if (condition) {"。

5. 在方法的左花括号前加空格,例如"public void myMethod() {"。

6. 使用大括号括起的代码块独占一行。

7. 在逻辑上相关的代码块之间使用空行分隔。

注释规范:1. 在类、方法和成员变量定义之前使用Javadoc注释说明其作用、参数和返回值。

2. 在方法内部使用注释解释代码的逻辑。

3. 避免使用不必要的注释,代码应尽可能自解释。

代码质量规范:1. 遵循SOLID原则,尽量将代码设计为松耦合、高内聚的模块。

2. 避免使用魔术数字,使用常量代替。

3. 使用异常处理机制来处理可预料的异常情况,不要捕获所有异常。

4. 避免使用全局变量,尽量将变量的作用范围限制在最小范围内。

5. 避免代码冗余和重复,尽量使用工具类和设计模式来重用代码。

测试规范:1. 使用单元测试框架(例如JUnit)编写测试用例,并确保每个方法都有相应的测试用例。

2. 使用断言来验证预期结果和实际结果是否一致。

3. 测试方法的命名应描述被测试方法的功能和预期结果。

版本管理规范:1. 使用版本管理工具(例如Git)来管理代码的版本和变更历史。

java代码规则标准

java代码规则标准

java代码规则标准Java代码规则标准可以参考以下内容:- 类命名:- 抽象类:适用的设计模式为模板模式。

抽象是自下往上的设计。

由具体实现推断出抽象方法。

建议以`Abstract`开头。

- 枚举类:枚举是由JVM来保证的单例。

可以用来做单例类。

枚举类常用来做值判断,不建议每次进行循环判断得到实例。

建议由内部维护一个`map`类型,当做`cache`。

此方法建议放在`static`静态代码块中实现。

- 工具类:工具类常为无状态对象,无状态对象都是线程安全对象,建议使用`final`修饰。

工具类中避免出现业务属性,如果出现业务属性,抽象出领域层。

- 异常类:建议保持异常链。

- 接口实现类:众所周知。

- 设计模式相关类:- 处理特定功能的:其主要的目的是代码可重复使用。

- 测试类:- 领域模型载体:- 方法命名:- 布尔判断方法:- 检查的方法:- 按需求才执行的方法:- 异步相关方法:- 回调方法:- 操作对象生命周期的方法:- 与集合操作相关的方法:- 数据增删改查相关的方法:- 成对出现的动词:- 获取必须的参数:- 获取数据并对数据进行某种处理:- 方法编程建议:- 方法复杂度:凡事逻辑判断语句均为复杂度。

当一个方法中出现了大于等于10个复杂度,建议根据方法实现进行业务抽离。

在编写Java代码时,需要遵循一定的规则和标准,以提高代码的可读性、可维护性和可扩展性。

你可以根据项目的具体需求和团队的约定来选择合适的规范。

(完整word版)JAVA代码规范详细版

(完整word版)JAVA代码规范详细版

JAVA代码规范本Java代码规范以SUN的标准Java代码规范为基础,为适应我们公司的实际需要,可能会做一些修改。

本文档中没有说明的地方,请参看SUN Java标准代码规范。

如果两边有冲突,以SUN Java标准为准。

1. 标识符命名规范1.1 概述标识符的命名力求做到统一、达意和简洁。

1.1.1 统一统一是指,对于同一个概念,在程序中用同一种表示方法,比如对于供应商,既可以用supplier,也可以用provider,但是我们只能选定一个使用,至少在一个Java项目中保持统一。

统一是作为重要的,如果对同一概念有不同的表示方法,会使代码混乱难以理解。

即使不能取得好的名称,但是只要统一,阅读起来也不会太困难,因为阅读者只要理解一次。

1.1.2 达意达意是指,标识符能准确的表达出它所代表的意义,比如:newSupplier, OrderPaymentGatewayService等;而supplier1, service2,idtts等则不是好的命名方式。

准确有两成含义,一是正确,而是丰富。

如果给一个代表供应商的变量起名是order,显然没有正确表达。

同样的,supplier1, 远没有targetSupplier意义丰富。

1.1.3 简洁简洁是指,在统一和达意的前提下,用尽量少的标识符。

如果不能达意,宁愿不要简洁。

比如:theOrderNameOfTheTargetSupplierWhichIsTransfered 太长,transferedTargetSupplierOrderName则较好,但是transTgtSplOrdNm就不好了。

省略元音的缩写方式不要使用,我们的英语往往还没有好到看得懂奇怪的缩写。

1.1.4 骆驼法则Java中,除了包名,静态常量等特殊情况,大部分情况下标识符使用骆驼法则,即单词之间不使用特殊符号分割,而是通过首字母大写来分割。

比如: supplierName, addNewContract,而不是supplier_name, add_new_contract。

java 代码规范

java 代码规范

java 代码规范Java代码规范是指在Java程序设计中遵循的一些规则和约定,旨在提高代码的可读性、可维护性和可移植性。

遵守代码规范可以帮助团队成员更好地理解和协作开发,提高代码的质量和可靠性。

本文将围绕Java代码规范展开讨论,包括命名规范、代码风格、注释规范、异常处理等方面的内容。

一、命名规范1.包名规范包名应该全小写,连接符可以使用小写字母和下划线,不推荐使用数字。

包名应该能够清晰地表达包所包含的内容,不要使用太长或者太短的包名。

2.类名规范类名应该采用驼峰命名法,首字母大写,类名应该能够清晰地表达类的用途,不要使用太长或者太短的类名。

如果类名由多个单词组成,应该遵循每个单词首字母大写的命名规范。

3.接口名规范接口名应该采用驼峰命名法,首字母大写,接口名应该能够清晰地表达接口的用途,不要使用太长或者太短的接口名。

如果接口名由多个单词组成,应该遵循每个单词首字母大写的命名规范。

4.变量名规范变量名应该采用驼峰命名法,首字母小写,变量名应该能够清晰地表达变量的用途,不要使用太长或者太短的变量名。

如果变量名由多个单词组成,应该遵循每个单词首字母小写的命名规范。

5.常量名规范常量名应该全大写,单词之间使用下划线分隔,常量名应该能够清晰地表达常量的用途,不要使用太长或者太短的常量名。

6.方法名规范方法名应该采用驼峰命名法,首字母小写,方法名应该能够清晰地表达方法的用途,不要使用太长或者太短的方法名。

如果方法名由多个单词组成,应该遵循每个单词首字母小写的命名规范。

二、代码风格1.缩进和空格缩进使用4个空格,不使用tab键。

在操作符前后使用空格,增强代码的可读性。

2.大括号的使用在类定义、方法定义、控制结构等的语句块后面使用大括号,增强代码的可读性。

3.代码行长度每行代码的长度不要超过80个字符,超过80个字符的代码应该使用换行符进行分割。

4.引号的使用字符串常量应该使用双引号,字符常量应该使用单引号。

华为JAVA编程规范

华为JAVA编程规范
规则5 if, for, do, while, case, switch, default 等语句自占一行,且if, for, do, while,switch等语句 的执行语句无论多少都要加括号{},case 的执行语句中如果定义变量必须加括号{}。 (1.42+)
说明:阅读代码更加清晰,减少错误产生 示例: if (a>b) {
说明:异常注释用@exception或@throws表示,在JavaDoc中两者等价,但推荐用@exception标注 Runtime异常,@throws标注非Runtime异常。异常的注释必须说明该异常的含义及什么条件下抛 出该异常。
Page 5 , Total 19
密级:内部公开
规则7 注释应与其描述的代码相近,对代码的注释应放在其上方,并与其上面的代码用空行隔 开,注释与所描述内容进行同样的缩排。(1.42+)
规则12 对重载父类的方法必须进行@Override声明(5.0+)
Page 6 , Total 19
密级:内部公开
说明:可清楚说明此方法是重载父类的方法,保证重载父类的方法时不会因为单词写错而造成错 误(写错方法名或者参数个数,类型都会编译无法通过) 示例: @Override public void doRequest(SipServletRequest req) throws ServletException,
分配对应日志类型的logreader指定类型查询时间段条件和反复器缓冲数查询时间为左包含原则即starttimeendtimeparamlogtypename日志类型名在配置文件中定义的paramstarttime查询日志的开始时间paramendtime查询日志的结束时间paramloglevel查询日志的级别paramusername查询该用户的日志parambuffernum日志反复器缓冲记录数return结果集日志反复器since12publicstaticlogiteratorreadstringlogtypedatestarttimedateendtimeintloglevelstringusernameintbuffernum规则6对于方法内部用throw语句抛出的异常必须在方法的注释中标明对于所调用的其他方法所抛出的异常选择主要的在注释中说明

Java编程规范(10页)免费下载.pdf

Java编程规范(10页)免费下载.pdf

程序注释
程序注释有四种格式:块注释格式,单行注释,跟随注释,行尾注释
¾ 块注释格式 块注释主要用于描述:文件、方法、数据结构和算法。一般在文件或者方法定义的
之前使用。也可以用在方法定义里面,如果块注释放在函数或者方法定义里,它必须与 它所描述的代码具有相同的缩进形式。
块注释应该用一个空行开头,以便于代码部分区分开来。 块注释举例:
会打字、5分钟快速自助建网站易启建站网免费提供建站平台,商业网站1年仅60元
简单语句
每行最多包含一个语句。
例如:
argv++;
// 正确
argc++;
// 正确
argv++; argc--; // 错误,应该避免这样写
组合语句
组合语句使用大括号括起来的一串语句。
1. 大括号中的语句比组合语句多一级缩进。
命名规则为: com.sinosoft.系统名[.模块名].xxx.xxx 具体参错误!未找到引用源。
包命名举例: com.sinosoft.platform.bl.facade com.sinosoft.platform.dto.domain
类命名规范 类名应该是名词,并且是大小写混合的。首字母要大写。尽量保证类名简单并且描
}
¾ 行尾注释 注释标记“//”能够注释一行或者该行由“//”开始直到行尾的部分。行尾注释不
能用在多行文本注释中。但它可以将多行代码注释掉。这三种注释方法举例如下。
if (foo > 1) {
// Do a double-flip.
...
}
else{
return false;
// Explain why here.

Java编程规范(DOC)

Java编程规范(DOC)

Java编程规范(DOC)预览说明:预览图片所展示的格式为文档的源格式展示,下载源文件没有水印,内容可编辑和复制Java编程规范目录Java编程规范 (1)1编码规则 (1)2命名规范 (7)2.1类名、变量名(非final)、方法名 (7)2.2驼峰式命名 (7)2.3不能使用没有任何含义的英文字母进行命名 (7)2.4不能使用拼音进行命名,统一使用准确的英文进行命名 (8)2.5包名 (8)2.6接口与类的命名 (8)2.7抽象类命名 (8)2.8实现类命名 (8)2.9工具类命名 (8)2.10变量命名 (8)2.115、方法命名 (9)2.12系统的命名约定 (9)1编码规则1、数据库操作、IO操作等需要使用结束close()的对象必须在try -catch-finally 的finally中close(),如果有多个IO对象需要close(),需要分别对每个对象的close()方法进行try-catch,防止一个IO对象关闭失败其他IO对象都未关闭。

手动控制事务提交也要进行关闭,对大对象进行关闭操作示例:try{// ... ...}catch(IOException ioe){//... ...}finally{try{out.close();}catch(IOException ioe){//... ...}try{in.close();}catch(IOException ioe){//... ...}}2、系统非正常运行产生的异常捕获后,如果不对该异常进行处理,则应该记录日志。

说明:此规则指通常的系统非正常运行产生的异常,不包括一些基于异常的设计。

若有特殊原因必须用注释加以说明。

logger.error(ioe,“[类.方法]描述”,参数);示例:try{//.... ...}catch(IOException ioe){logger.error(ioe);}3、自己抛出的异常必须要填写详细的描述信息。

java代码开发规范

java代码开发规范

java代码开发规范Java代码开发规范(Java Coding Convention)是一组编写Java 代码的规范和约定,以提高代码的可读性、可维护性和可重用性。

下面是一个包含大约1000字的Java代码开发规范概述:1. 命名规范:- 类名使用大写开头的驼峰式命名法,如MyClass。

- 方法名和变量名使用小写开头的驼峰式命名法,如myMethod。

- 常量名使用全大写字母和下划线的命名法,如MY_CONSTANT。

- 包名使用全小写字母,可以使用多级包名,如com.example.myproject。

2. 缩进和空格:- 使用4个空格进行代码块缩进。

- 除了特殊情况,每行代码最多120个字符。

- 操作符前后加上空格,如a + b。

3. 注释:- 使用Javadoc风格的类、方法和变量注释。

- 注释应该简洁明了,不要使用废话或无关信息。

- 注释应该更新以反映代码的变化。

4. 源文件:- 每个源文件只包含一个公有类。

- 源文件应该以UTF-8编码保存。

- 导入语句应该按照字母顺序排序。

5. 类的结构:- 每个类应该包含类的成员变量、构造方法、公有方法和私有方法,按照这个顺序。

- 成员变量应该使用private修饰,并提供相应的getter和setter方法。

- 公有方法应该提供必要的参数检查和异常处理。

6. 代码块:- 使用大括号包围代码块,即使代码块只有一行。

- 尽量减少嵌套层次,避免深层次的if-else或循环嵌套。

- switch语句应该包含default情况,并在每个case结束后加上break。

7. 异常处理:- 每个抛出异常的方法都应该声明可能抛出的异常类型。

- 在需要捕获异常的地方使用try-catch语句,并处理异常。

8. 并发编程:- 尽量使用线程安全的类和方法。

- 保护共享资源时使用synchronized关键字或者Lock对象。

9. 测试代码:- 每个公有类应该有相应的单元测试类。

jtg规范

jtg规范

jtg规范JTG规范,全称是《Java编码规范》,是由中国石油天然气股份有限公司集团技术开发中心(简称JTG)制定的一套用于Java编程的规范和指南。

该规范旨在提高代码的质量、可读性和可维护性,促进团队协作,降低项目风险和成本。

一、命名规范1. 类、接口、枚举的命名应使用大驼峰式命名法,即每个单词的首字母大写,无下划线或缩写。

2. 方法、变量、参数的命名应使用小驼峰式命名法,即第一个单词小写,后续单词首字母大写,无下划线或缩写。

二、代码风格规范1. 缩进使用4个空格。

2. 每行代码的长度不超过80个字符。

3. 使用花括号括起的代码块,左花括号和首个代码字符在一行,右花括号独占一行,并且与左花括号的首个字符对齐。

4. 一行只写一条语句,不要使用逗号表达式。

5. 避免行尾空格和多余的空行。

6. 注释应使用Javadoc注释格式,给出功能描述、参数说明和返回值说明。

三、Java语言规范1. 类和接口的顺序依次是:类注释、import语句、类声明,各部分之间用空行分隔。

2. 方法的顺序依次是:方法注释、修饰符、方法名、参数列表、返回值类型、方法体,各部分之间用空行分隔。

3. 代码编写避免使用魔法值,应定义常量代替,提高可读性和可维护性。

4. 使用try-catch块处理异常,不要将异常抛出。

5. 在使用循环控制语句时,应使用带标签的break和continue,避免混淆和错误。

四、代码注释规范1. 类和接口的注释应包含以下内容:功能描述、作者信息、创建日期、修改日志等。

2. 方法的注释应包含以下内容:方法功能、参数说明、返回值说明、抛出异常说明等。

并对特殊情况进行说明。

3. 变量和常量的注释应包含定义说明、用途说明等。

4. 注释内容清晰明了,不要出现错误或低效的注释。

五、命名约定1. 类和接口的命名应表达清晰的含义,避免使用无意义的命名。

2. 变量的命名应具有描述性,不要使用单个字符或数字作为变量名。

3. 基本数据类型和常量的命名应使用全部大写,单词间用下划线连接。

java代码编写规范

java代码编写规范

java代码编写规范Java代码编写规范是为了保持代码的一致性、可读性、可维护性和可扩展性而制定的一套规则。

以下是一些常见的Java代码编写规范:1. 命名规范:- 类名使用大写字母开头的驼峰命名法,如MyClass。

- 方法名使用小写字母开头的驼峰命名法,如myMethod。

- 变量名使用小写字母开头的驼峰命名法,并能直观地描述变量的含义,如myVariable。

- 常量名使用全大写的下划线命名法,如MAX_SIZE。

2. 缩进和空格:- 使用4个空格进行缩进,不要使用Tab键。

- 运算符之间加空格,如 a + b。

- 逗号之后加空格,如int a, int b。

- 括号之间加空格,如if (condition)。

- 方法和类的左括号不另起一行。

3. 注释规范:- 使用Javadoc格式进行注释,包括类、方法和成员变量的说明。

- 每个方法需说明参数、返回值和可能抛出的异常。

- 不要保留没有用的注释。

- 注释应该与代码保持一致,不要误导阅读者。

4. 类和方法的设计:- 类应该具有单一的职责,不要包含无关的功能。

- 方法应该具有清晰的目的和语义,不要过长或过于复杂。

- 类和方法应该尽量避免过多的参数,如果参数过多,可以考虑使用封装对象。

5. 异常处理:- 对于可能抛出的异常,应该根据情况进行合理的处理,而不是简单地忽略或抛出异常。

- 使用try-catch语句来捕获并处理异常,避免在代码中出现不受控制的异常。

6. 代码重构:- 定期进行代码重构,提高代码的可读性和可维护性。

- 删除无用的代码和注释。

- 提取公共代码块,避免重复的代码。

7. 包名和导入:- 包名应该以小写字母开头,使用有意义的命名。

- 导入语句应该只导入使用到的类,不要使用通配符导入。

8. 代码格式化:- 使用自动代码格式化工具来保持代码的一致性,如Eclipse 的代码格式化功能。

9. 单元测试:- 编写单元测试来验证代码的正确性和可靠性。

java 编程规范(Java Programming Style Guidelines)

java 编程规范(Java Programming Style Guidelines)

此为英文版,英文好些的,可以看看英文。

除此之外,例子也很详细,直观,一看就懂。

大家看看可以提高自己的编程风格和交流代码。

Java Programming Style GuidelinesVersion 6.1, March 2008 Array Geotechnical Software ServicesCopyright © 1998 - 2008This document is available at http://geosoft.no/development/javastyle.htmlTable of Content1 Introductiono 1.1 Layout of theRecommendationso 1.2 Recommendations Importanceo 1.3 Automatic Style Checking∙ 2 General Recommendations3 Naming Conventionso 3.1 General Naming Conventionso 3.2 Specific naming Conventions∙ 4 Files5 Statementso 5.1 Package and Import Statementso 5.2 Classes and Interfaceso 5.3 Methodso 5.4 Typeso 5.5 Variableso 5.6 Loopso 5.7 Conditionalso 5.8 Miscellaneous6 Layout and Commentso 6.1 Layouto 6.2 White spaceo 6.3 Comments∙7 References1 IntroductionThis document lists Java coding recommendations common in the Java development community.The recommendations are based on established standards collected from a number of sources, individual experience, local requirements/needs, as well as suggestions given in [1], [2], [3], [4] and [5].There are several reasons for introducing a new guideline rather than just referring to the ones above. Main reason is that these guides are far too general in their scope and that more specific rules (especially naming rules) need to be established. Also, the present guide has an annotated form that makes it easier to use during project code reviews than most other existing guidelines. In addition, programming recommendations generally tend to mix style issues with language technical issues in a somewhat confusing manner. The present document does not contain any Java technical recommendations at all, but focuses mainly on programming style.While a given development environment (IDE) can improve the readability of code by access visibility, color coding, automatic formatting and so on, the programmer should never rely on such features. Source code should always be considered larger than the IDE it is developed within and should be written in a way that maximize its readability independent of any IDE.1.1 Layout of the Recommendations.The recommendations are grouped by topic and each recommendation is numbered to make it easier to refer to during reviews.Layout for the recommendations is as follows:n. Guideline short descriptionExample if applicableMotivation, background and additional information.The motivation section is important. Coding standards and guidelines tend to start "religious wars", and it is important to state the background for the recommendation.1.2 Recommendation ImportanceIn the guideline sections the terms must, should and can have special meaning. A must requirement must be followed, a should is a strong recommendation, and a can is a general guideline.1.3 Automatic Style CheckingMany tools provide automatic code style checking. One of the most popular and feature rich one is Checkstyle by Oliver Burn.Checkstyle is configured through an XML file of style rules which is applied to the source code. It is most useful if it is integrated in the build process or the development environment. There are Checkstyle plugins for all the popular IDEs available.To use Checkstyle with the GeoSoft style rules below, use this configuration file: geosoft_checks.xml.2 General Recommendations1. Any violation to the guide is allowed if it enhances readability.The main goal of the recommendation is to improve readability and thereby the understanding and the maintainability and general quality of the code. It is impossible to cover all the specific cases in a general guide and the programmer should be flexible.3 Naming Conventions3.1 General Naming Conventions2. Names representing packages should be in all lower case.mypackage, pany.application.uiPackage naming convention used by Sun for the Java core packages. The initial package name representing the domain name must be in lower case.3. Names representing types must be nouns and written in mixed case starting with upper case.Line, AudioSystemCommon practice in the Java development community and also the type naming convention used by Sun for the Java core packages.4. Variable names must be in mixed case starting with lower case.line, audioSystemCommon practice in the Java development community and also the naming convention for variables used by Sun for the Java core packages. Makes variables easy to distinguish from types, and effectively resolves potential naming collision as in the declaration Line line;5. Names representing constants (final variables) must be all uppercase using underscore to separate words.MAX_ITERATIONS, COLOR_REDCommon practice in the Java development community and also the naming convention used by Sun for the Java core packages.In general, the use of such constants should be minimized. In many cases implementing the value as a method is a better choice:int getMaxIterations() // NOT: MAX_ITERATIONS = 25{return 25;}This form is both easier to read, and it ensures a uniform interface towards class values.6. Names representing methods must be verbs and written in mixed case starting with lower case.getName(), computeTotalWidth()Common practice in the Java development community and also the naming convention used by Sun for the Java core packages. This is identical to variable names, but methods in Java are already distinguishable from variables by their specific form.7. Abbreviations and acronyms should not be uppercase when used as name.exportHtmlSource(); // NOT: exportHTMLSource();openDvdPlayer(); // NOT: openDVDPlayer();Using all uppercase for the base name will give conflicts with the naming conventions given above. A variable of this type whould have to be named dVD, hTML etc. which obviously is not very readable. Another problem is illustrated in the examples above; When the name is connected to another, the readability is seriously reduced; The word following the acronym does not stand out as it should.8. Private class variables should have underscore suffix.class Person { private String name_; ... }Apart from its name and its type, the scope of a variable is its most important feature. Indicating class scope by using underscore makes it easy to distinguish class variables from local scratch variables. This is important because class variables are considered to have higher significance than method variables, and should be treated with special care by the programmer.A side effect of the underscore naming convention is that it nicely resolves the problem of finding reasonable variable names for setter methods:void setName(String name){name_ = name;}An issue is whether the underscore should be added as a prefix or as a suffix. Both practices are commonly used, but the latter is recommended because it seem to best preserve the readability of the name.It should be noted that scope identification in variables have been a controversial issue for quite some time. It seems, though, that this practice now is gaining acceptance and that it is becoming more and more common as a convention in the professional development community.9. Generic variables should have the same name as their type.void setTopic(Topic topic) // NOT: void setTopic(Topic value)// NOT: void setTopic(Topic aTopic)// NOT: void setTopic(Topic t)void connect(Database database) // NOT: void connect(Database db)// NOT: void connect(Database oracleDB)Reduce complexity by reducing the number of terms and names used. Also makes it easy todeduce the type given a variable name only.If for some reason this convention doesn't seem to fit it is a strong indication that the type name is badly chosen.Non-generic variables have a role. These variables can often be named by combining role and type:Point startingPoint, centerPoint;Name loginName;10. All names should be written in English.English is the preferred language for international development.11. Variables with a large scope should have long names, variables with a small scope can have short names [1].Scratch variables used for temporary storage or indices are best kept short. A programmer reading such variables should be able to assume that its value is not used outside a few lines of code. Common scratch variables for integers are i, j, k, m, n and for characters c and d.12. The name of the object is implicit, and should be avoided in a method name.line.getLength(); // NOT: line.getLineLength();The latter might seem natural in the class declaration, but proves superfluous in use, as shown in the example.3.2 Specific Naming Conventions13. The terms get/set must be used where an attribute is accessed directly.employee.getName(); employee.setName(name); matrix.getElement(2, 4); matrix.setElement(2, 4, value);Common practice in the Java community and the convention used by Sun for the Java core packages.14. is prefix should be used for boolean variables and methods.isSet, isVisible, isFinished, isFound, isOpenThis is the naming convention for boolean methods and variables used by Sun for the Java core packages.Using the is prefix solves a common problem of choosing bad boolean names like status or flag. isStatus or isFlag simply doesn't fit, and the programmer is forced to chose more meaningful names.Setter methods for boolean variables must have set prefix as in:void setFound(boolean isFound);There are a few alternatives to the is prefix that fits better in some situations. These are has, can and should prefixes:boolean hasLicense();boolean canEvaluate();boolean shouldAbort = false;15. The term compute can be used in methods where something is computed.puteAverage(); puteInverse()Give the reader the immediate clue that this is a potential time consuming operation, and if used repeatedly, he might consider caching the result. Consistent use of the term enhances readability.16. The term find can be used in methods where something is looked up.vertex.findNearestVertex(); matrix.findSmallestElement(); node.findShortestPath(Node destinationNode);Give the reader the immediate clue that this is a simple look up method with a minimum of computations involved. Consistent use of the term enhances readability.17. The term initialize can be used where an object or a concept is established.printer.initializeFontSet();The American initialize should be preferred over the English initialise. Abbreviation init must be avoided.18. JFC (Java Swing) variables should be suffixed by the element type.widthScale, nameTextField, leftScrollbar, mainPanel, fileToggle, minLabel, printerDialogEnhances readability since the name gives the user an immediate clue of the type of the variable and thereby the available resources of the object.19. Plural form should be used on names representing a collection of objects.Collection<Point> points; int[] values;Enhances readability since the name gives the user an immediate clue of the type of the variable and the operations that can be performed on its elements.20. n prefix should be used for variables representing a number of objects.nPoints, nLinesThe notation is taken from mathematics where it is an established convention for indicating anumber of objects.Note that Sun use num prefix in the core Java packages for such variables. This is probably meant as an abbreviation of number of, but as it looks more like number it makes the variable name strange and misleading. If "number of" is the preferred phrase, numberOf prefix can be used instead of just n. num prefix must not be used.21. No suffix should be used for variables representing an entity number.tableNo, employeeNoThe notation is taken from mathematics where it is an established convention for indicating an entity number.An elegant alternative is to prefix such variables with an i: iTable, iEmployee. This effectively makes them named iterators.22. Iterator variables should be called i, j, k etc.for (Iterator i = points.iterator(); i.hasNext(); ) { : } for (int i = 0; i < nTables; i++) { : }The notation is taken from mathematics where it is an established convention for indicating iterators.Variables named j, k etc. should be used for nested loops only.23. Complement names must be used for complement entities [1].get/set, add/remove, create/destroy, start/stop, insert/delete, increment/decrement, old/new, begin/end, first/last, up/down, min/max, next/previous, old/new, open/close, show/hide, suspend/resume, etc.Reduce complexity by symmetry.24. Abbreviations in names should be avoided.computeAverage(); // NOT: compAvg();ActionEvent event; // NOT: ActionEvent e;catch (Exception exception) { // NOT: catch (Exception e) {There are two types of words to consider. First are the common words listed in a language dictionary. These must never be abbreviated. Never write:cmd instead of commandcomp instead of computecp instead of copye instead of exceptioninit instead of initializept instead of pointetc.Then there are domain specific phrases that are more naturally known through their acronym or abbreviations. These phrases should be kept abbreviated. Never write: HypertextMarkupLanguage instead of htmlCentralProcessingUnit instead of cpuPriceEarningRatio instead of peetc.25. Negated boolean variable names must be avoided.bool isError; // NOT: isNoError bool isFound; // NOT: isNotFoundThe problem arise when the logical not operator is used and double negative arises. It is not immediately apparent what !isNotError means.26. Associated constants (final variables) should be prefixed by a common type name.final int COLOR_RED = 1; final int COLOR_GREEN = 2; final int COLOR_BLUE = 3;This indicates that the constants belong together, and what concept the constants represents. An alternative to this approach is to put the constants inside an interface effectively prefixing their names with the name of the interface:interface Color{final int RED = 1;final int GREEN = 2;final int BLUE = 3;}27. Exception classes should be suffixed with Exception.class AccessException extends Exception { : }Exception classes are really not part of the main design of the program, and naming them like this makes them stand out relative to the other classes. This standard is followed by Sun in the basic Java library.28. Default interface implementations can be prefixed by Default.class DefaultTableCellRenderer implements TableCellRenderer { : }It is not uncommon to create a simplistic class implementation of an interface providing default behaviour to the interface methods. The convention of prefixing these classes by Default has been adopted by Sun for the Java library.29. Singleton classes should return their sole instance through method getInstance.class UnitManager { private final static UnitManager instance_ = new UnitManager(); private UnitManager() { ... } public static UnitManager getInstance() // NOT: get() or instance() or unitManager() etc. { return instance_; } }Common practice in the Java community though not consistently followed by Sun in the JDK. The above layout is the preferred pattern.30. Classes that creates instances on behalf of others (factories) can do so through method new[ClassName]class PointFactory { public Point newPoint(...) { ... } }Indicates that the instance is created by new inside the factory method and that the construct is a controlled replacement of new Point().31. Functions (methods returning an object) should be named after what they return and procedures (void methods) after what they do.Increase readability. Makes it clear what the unit should do and especially all the things it is not supposed to do. This again makes it easier to keep the code clean of side effects.4 Files32. Java source files should have the extension .java.Point.javaEnforced by the Java tools.33. Classes should be declared in individual files with the file name matching the class name. Secondary private classes can be declared as inner classes and reside in the file of the class they belong to.Enforced by the Java tools.34. File content must be kept within 80 columns.80 columns is the common dimension for editors, terminal emulators, printers and debuggers, and files that are shared between several developers should keep within these constraints. It improves readability when unintentional line breaks are avoided when passing a file between programmers.35. Special characters like TAB and page break must be avoided.These characters are bound to cause problem for editors, printers, terminal emulators or debuggers when used in a multi-programmer, multi-platform environment.36. The incompleteness of split lines must be made obvious [1].totalSum = a + b + c + d + e; method(param1, param2, param3); setText ("Long line split" + "into two parts."); for (int tableNo = 0; tableNo < nTables; tableNo += tableStep) { ... }Split lines occurs when a statement exceed the 80 column limit given above. It is difficult to give rigid rules for how lines should be split, but the examples above should give a general hint.In general:∙Break after a comma.∙Break after an operator.∙Align the new line with the beginning of the expression on the previous line.5 Statements5.1 Package and Import Statements37. The package statement must be the first statement of the file. All files should belong toa specific package.The package statement location is enforced by the Java language. Letting all files belong to an actual (rather than the Java default) package enforces Java language object oriented programming techniques.38. The import statements must follow the package statement. import statements should be sorted with the most fundamental packages first, and grouped with associated packages together and one blank line between groups.import java.io.IOException; import .URL; import java.rmi.RmiServer; import java.rmi.server.Server; import javax.swing.JPanel; import javax.swing.event.ActionEvent; import org.linux.apache.server.SoapServer;The import statement location is enforced by the Java language. The sorting makes it simple to browse the list when there are many imports, and it makes it easy to determine the dependiencies of the present package The grouping reduce complexity by collapsing related information into a common unit.39. Imported classes should always be listed explicitly.import java.util.List; // NOT: import java.util.*;import java.util.ArrayList; import java.util.HashSet;Importing classes explicitly gives an excellent documentation value for the class at hand and makes the class easier to comprehend and maintain.Appropriate tools should be used in order to always keep the import list minimal and up to date.5.2 Classes and Interfaces40. Class and Interface declarations should be organized in the following manner:1Class/Interface documentation.2class or interface statement.3Class (static) variables in the order public, protected, package (no access modifier), private.4Instance variables in the order public, protected, package (no access modifier), private.5Constructors.6Methods (no specific order).Reduce complexity by making the location of each class element predictable.5.3 Methods41. Method modifiers should be given in the following order:<access> static abstract synchronized <unusual> final nativeThe <access> modifier (if present) must be the first modifier.public static double square(double a); // NOT: static public double square(double a);<access>is one of public, protected or private while <unusual> includes volatile and transient. The most important lesson here is to keep the access modifier as the first modifier. Of the possible modifiers, this is by far the most important, and it must stand out in the method declaration. For the other modifiers, the order is less important, but it make sense to have a fixed convention.5.4 Types42. Type conversions must always be done explicitly. Never rely on implicit type conversion.floatValue = (int) intValue; // NOT: floatValue = intValue;By this, the programmer indicates that he is aware of the different types involved and that the mix is intentional.43. Array specifiers must be attached to the type not the variable.int[] a = new int[20]; // NOT: int a[] = new int[20]The arrayness is a feature of the base type, not the variable. It is not known why Sun allows both forms.5.5 Variables44. Variables should be initialized where they are declared and they should be declared in the smallest scope possible.This ensures that variables are valid at any time. Sometimes it is impossible to initialize a variable to a valid value where it is declared. In these cases it should be left uninitialized rather than initialized to some phony value.45. Variables must never have dual meaning.Enhances readability by ensuring all concepts are represented uniquely. Reduce chance of error by side effects.46. Class variables should never be declared public.The concept of Java information hiding and encapsulation is violated by public variables. Use private variables and access functions instead. One exception to this rule is when the class is essentially a data structure, with no behavior (equivalent to a C++ struct). In this case it is appropriate to make the class' instance variables public [2].47. Arrays should be declared with their brackets next to the type.double[] vertex; // NOT: double vertex[]; int[] count; // NOT: int count[]; public static void main(String[] arguments) public double[] computeVertex()The reason for is twofold. First, the array-ness is a feature of the class, not the variable. Second, when returning an array from a method, it is not possible to have the brackets with other than the type (as shown in the last example).48. Variables should be kept alive for as short a time as possible.Keeping the operations on a variable within a small scope, it is easier to control the effects and side effects of the variable.5.6 Loops49. Only loop control statements must be included in the for() construction.sum = 0; // NOT: for (i = 0, sum = 0; i < 100; i++) for (i = 0; i < 100; i++) sum += value[i]; sum += value[i];Increase maintainability and readability. Make a clear distinction of what controls and what is contained in the loop.50. Loop variables should be initialized immediately before the loop.isDone = false; // NOT: bool isDone = false;while (!isDone) { // :: // while (!isDone) { } // :// }51. The use of do-while loops can be avoided.do-while loops are less readable than ordinary while loops and for loops since the conditional is atthe bottom of the loop. The reader must scan the entire loop in order to understand the scope of the loop.In addition, do-while loops are not needed. Any do-while loop can easily be rewritten into a while loop or a for loop. Reducing the number of constructs used enhance readbility.52. The use of break and continue in loops should be avoided.These statements should only be used if they prove to give higher readability than their structured counterparts.5.7 Conditionals53. Complex conditional expressions must be avoided. Introduce temporary boolean variables instead [1].bool isFinished = (elementNo < 0) || (elementNo > maxElement); bool isRepeatedEntry = elementNo == lastElement; if (isFinished || isRepeatedEntry) { : } // NOT: if ((elementNo < 0) || (elementNo > maxElement)|| elementNo == lastElement) { : }By assigning boolean variables to expressions, the program gets automatic documentation. The construction will be easier to read, debug and maintain.54. The nominal case should be put in the if-part and the exception in the else-part of an if statement [1].boolean isOk = readFile(fileName); if (isOk) { : } else { : }Makes sure that the exceptions does not obscure the normal path of execution. This is important for both the readability and performance.55. The conditional should be put on a separate line.if (isDone) // NOT: if (isDone) doCleanup(); doCleanup();This is for debugging purposes. When writing on a single line, it is not apparent whether the test is really true or not.56. Executable statements in conditionals must be avoided.InputStream stream = File.open(fileName, "w"); if (stream != null) { : } // NOT: if (File.open(fileName, "w") != null)) { : }Conditionals with executable statements are simply very difficult to read. This is especially true for programmers new to Java.5.8 Miscellaneous57. The use of magic numbers in the code should be avoided. Numbers other than 0 and 1can be considered declared as named constants instead.private static final int TEAM_SIZE = 11; : Player[] players = new Player[TEAM_SIZE]; // NOT: Player[] players = new Player[11];If the number does not have an obvious meaning by itself, the readability is enhanced by introducing a named constant instead.58. Floating point constants should always be written with decimal point and at least one decimal.double total = 0.0; // NOT: double total = 0; double speed = 3.0e8; // NOT: double speed = 3e8; double sum; : sum = (a + b) * 10.0;This emphasize the different nature of integer and floating point numbers. Mathematically the two model completely different and non-compatible concepts.Also, as in the last example above, it emphasize the type of the assigned variable (sum) at a point in the code where this might not be evident.59. Floating point constants should always be written with a digit before the decimal point.double total = 0.5; // NOT: double total = .5;The number and expression system in Java is borrowed from mathematics and one should adhere to mathematical conventions for syntax wherever possible. Also, 0.5 is a lot more readable than .5; There is no way it can be mixed with the integer 5.60. Static variables or methods must always be refered to through the class name and never through an instance variable.Thread.sleep(1000); // NOT: thread.sleep(1000);This emphasize that the element references is static and independent of any particular instance. For the same reason the class name should also be included when a variable or method is accessed from within the same class.6 Layout and Comments6.1 Layout61. Basic indentation should be 2.for (i = 0; i < nElements; i++) a[i] = 0;Indentation is used to emphasize the logical structure of the code. Indentation of 1 is to small to acheive this. Indentation larger than 4 makes deeply nested code difficult to read and increase the chance that the lines must be split. Choosing between indentation of 2, 3 and 4; 2 and 4 are the more common, and 2 chosen to reduce the chance of splitting code lines. Note that the Sun recommendation on this point is 4.62. Block layout should be as illustrated in example 1 below (recommended) or example 2, and must not be as shown in example 3. Class, Interface and method blocks should usethe block layout of example 2.while (!done) { doSomething(); done = moreToDo(); } while (!done){ doSomething();done = moreToDo(); }while (!done) { doSomething(); done =moreToDo(); }Example 3 introduce an extra indentation level which doesn't emphasize the logical structure of the code as clearly as example 1 and 2.63. The class and interface declarations should have the following form:class Rectangle extends Shape implements Cloneable, Serializable { ... }This follows from the general block rule above. Note that it is common in the Java developer community to have the opening bracket at the end of the line of the class keyword. This is not recommended.64. Method definitions should have the following form:public void someMethod() throws SomeException { ... }See comment on class statements above.65. The if-else class of statements should have the following form:if (condition) { statements; } if (condition) { statements; } else { statements; } if (condition) { statements; } else if (condition) { statements; } else { statements; }This follows partly from the general block rule above. However, it might be discussed if an else clause should be on the same line as the closing bracket of the previous if or else clause:if (condition) {statements;} else {statements;}This is equivalent to the Sun recommendation. The chosen approach is considered better in the way that each part of the if-else statement is written on separate lines of the file. This should make it easier to manipulate the statement, for instance when moving else clauses around.66. The for statement should have the following form:for (initialization; condition; update) { statements; }This follows from the general block rule above.67. An empty for statement should have the following form:for (initialization; condition; update) ;This emphasize the fact that the for statement is empty and it makes it obvious for the reader that this is intentional.。

java开发规范文档

java开发规范文档

java开发规范文档Java开发规范文档一、命名规范:1.类名使用大驼峰命名法,首字母大写。

2.方法名使用小驼峰命名法,首字母小写。

3.变量名使用小驼峰命名法,首字母小写。

4.常量名使用全大写字母,多个单词之间用下划线连接。

二、代码风格规范:1.代码缩进使用4个空格,不使用制表符。

2.每行代码尽量不超过80个字符。

3.每个方法应该有注释说明其作用。

4.使用行注释或块注释对代码进行注释。

三、类结构规范:1.每个源文件只包含一个类,类名与文件名保持一致。

2.类的字段应该在声明处进行初始化。

3.类的方法按照功能进行分组,相似功能的方法放在一起。

4.类的字段和方法应该用private修饰,对外提供访问的方法使用public修饰。

四、包规范:1.包名采用小写英文字母,多个单词之间用点号(.)分隔。

2.包名应该能够反映出所包含类的功能和用途。

五、注释规范:1.源文件开头应该包含版权声明和作者信息。

2.对于每个类、方法及其参数,应该提供注释,说明其作用和用途。

3.注释应该简洁明了,尽量使用英文。

六、异常处理规范:1.不要在catch块中使用空的catch块。

2.能够处理的异常应该在模块内进行处理,不能处理的异常应该抛出。

七、代码排版规范:1.应该将相关的变量和方法放在一起。

2.应该根据代码逻辑来进行代码的排版,让代码易于阅读。

八、代码复用规范:1.不要重复编写相同功能的代码,应该进行代码复用。

2.可以将公共的代码封装成方法或类,供其他地方使用。

九、版本控制规范:1.使用版本控制工具进行源代码的管理。

2.提交代码前进行代码的版本比较和合并。

以上是Java开发规范的一些常见规范,开发人员应该遵守这些规范,以便提高代码的可维护性和可读性。

规范的遵守可以减少代码的错误和提高代码的质量,有助于团队的合作和项目的开发进度。

java语言规范

java语言规范

java语言规范Java语言规范是指用于指导Java程序设计的一系列准则和规范。

遵循Java语言规范可以帮助程序员编写出清晰、可读性强、稳定、可维护和易于理解的Java代码。

以下是Java语言规范的一些重要准则和规范:1. 标识符:Java中的标识符是用于命名变量、类、方法等的。

标识符必须以字母、下划线或者美元符号开头,后面可以使用字母、数字、下划线或者美元符号。

标识符不能是Java的保留字。

2. 区分大小写:Java是区分大小写的语言,变量名、方法名等的大小写是敏感的。

3. 缩进和空格:为了提高代码可读性,应该在代码块开始和结束处适当缩进,并且在关键字、运算符等之间使用空格,不要把多个语句写在同一行。

4. 注释:Java有三种注释方式:块注释,行注释和文档注释。

块注释用/* ... */包围,行注释用//开头,文档注释是指以/** ... */包围的注释,一般用于生成API文档。

5. 常量:Java中的常量是指在程序执行期间不能被改变的值。

常量一般使用关键字final声明,并采用全大写字母的命名方式。

6. 类和接口命名:类和接口的命名一般采用大驼峰命名法,即每个单词首字母大写,例如MyClass,而不是myClass或者MYClass。

7. 变量和方法命名:变量和方法的命名一般采用小驼峰命名法,即第一个单词的首字母小写,后面的单词首字母大写,例如myVariable,myMethod。

8. 方法长度和复杂性:为了提高代码的可读性和可维护性,一个方法的长度应该适度,并且控制方法的复杂性。

推荐一个方法的长度不超过一屏,并且只做一件事情。

9. 异常处理:Java提供了异常机制来处理程序运行时产生的异常。

程序员应该适当捕捉和处理异常,并给用户提供友好的提示信息。

10. 类设计:一个类应该有清晰的职责和功能,并且遵循高内聚、低耦合的设计原则。

一个类的命名应该反映它的功能,并且应该保持单一职责原则。

以上只是Java语言规范的一部分,还有很多准则和规范可以帮助程序员编写高质量的Java代码。

java代码开发规范

java代码开发规范

java代码开发规范⼀编码规范1.1 命名规范1. 代码中的命名均不能以特殊字符(如下划线、$#符号)开始或结束。

反例: _name / #Object2. 代码中的命名严禁使⽤拼⾳与英⽂混合的⽅式,更不允许直接使⽤中⽂的⽅式。

反例: toubao / lipei。

3. 类名使⽤UpperCamelCase风格,必须遵从驼峰形式。

正例:CommonUtils / BaseVo4. ⽅法名、参数名、成员变量、局部变量都统⼀使⽤lowerCamelCase风格,必须遵从驼峰形式。

正例: orderService / getOrderService()5. 常量命名全部⼤写,单词间⽤下划线隔开,⼒求语义表达完整清楚,不要嫌名字长。

正例: ZK_CONFIG_ROOTNODE6. 抽象类命名使⽤Abstract或Base开头;异常类命名使⽤Exception结尾;测试类命名以它要测试的类的名称开始,以Test结尾。

7. 包名使⽤com.hetai.服务名.分层名。

正例: oauth系统的DAO, com.hetai.oauth.dao8. 如果使⽤到了设计模式或具有明确职责,建议在类名中体现出具体模式或职责。

正例:ExecutorFactory / AbstractProducer9. 各分层都需要接⼝和实现类,实现类⽤Impl作后缀与接⼝区别。

正例:OrderServiceImpl实现OrderService接⼝。

10. 枚举类名建议带上Enum后缀,枚举成员名称需要全⼤写,单词间⽤下划线隔开。

正例:枚举名字:PolicyIdTypeEnum,成员名称:ID_CARD/ PASSPORT。

11. 各层⽅法命名规范: 1)查询的⽅法⽤get/ query做前缀。

2)插⼊的⽅法⽤add 或insert做前缀。

3)删除的⽅法⽤remove 或delete做前缀。

4)修改的⽅法⽤modify/ update做前缀。

  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

1 Java 编程规范1.1 排版1.1.1 规则规则1程序块要采用缩进风格编写,使用TAB缩进,而不是替换为空格。

(1.42+)规则2分界符(如大括号‘{’和‘}’)左大括号“{”与函数名或上文语句在同一行,而不是独占一行。

(1.42+)示例:if (a>b) {doStart();}规则3较长的语句、表达式或参数(>80字符)要分成多行书写,长表达式要在低优先级操作符处划分新行,操作符放在新行之首,划分出的新行要进行适当的缩进,使排版整齐,语句可读。

(1.42+)示例:if (logger.isDebugEnabled()){logger.debug("Session destroyed,call-id"+ event.getSession().getCallId());}规则4不允许把多个短语句写在一行中,即一行只写一条语句(1.42+)说明:阅读代码更加清晰示例:如下例子不符合规范。

Object o = new Object(); Object b = null;规则5if, for, do, while, case, switch, default 等语句自占一行,且if, for, do, while,switch等语句的执行语句无论多少都要加括号{},case 的执行语句中如果定义变量必须加括号{}。

(1.42+)说明:阅读代码更加清晰,减少错误产生示例:if (a>b){doStart();}case x:{int i = 9;}规则6相对独立的程序块之间、变量说明之后必须加空行。

(1.42+)说明:阅读代码更加清晰示例:if(a > b){doStart();}//此处是空行return;规则7在两个以上的关键字、变量、常量进行对等操作时,它们之间的操作符之前、之后或者前后要加空格;进行非对等操作时,如果是关系密切的立即操作符(如.),后不应加空格。

(1.42+)说明:阅读代码更加清晰示例:if (a == b){objectA.doStart();}a *= 2;1.1.2 建议建议1类属性和类方法不要交叉放置,不同存取范围的属性或者方法也尽量不要交叉放置。

(1.42+)格式:类定义{类的公有属性定义类的保护属性定义类的私有属性定义类的公有方法定义类的保护方法定义类的私有方法定义}建议2修饰词按照指定顺序书写:[访问权限][static][final] 。

(1.42+)示例:public static final String str = “abc”;1.2 注释1.2.1 规则规则1类定义,公有方法,公有属性必须要有注释必须在30%。

(1.42+)规则2包的注释:写入一个名为package.html的HTML格式的说明文件放入包所在路径。

包的注释内容:简述本包的作用、详细描述本包的内容、产品模块名称和版本、公司版权。

(1.42+)说明:方便JavaDoc收集,方便对包的了解示例:com/huawei/iin/websmap/comm/package.html<html><body><p>一句话简述。

<p>详细描述。

<p>产品模块名称和版本<br>公司版权信息</body></html>示例:<html><body><P>为 WEBSMAP 提供通信类,上层业务使用本包的通信类与 SMP-B 进行通信。

<p>详细描述。

<p>IIN V100R001 WEBSMAP<br>(C) 版权所有 2000-2001 华为技术有限公司</body></html>规则3类和接口的注释放在class或者interface 关键字之前,import 关键字之后。

注释主要是一句话功能简述与功能详细描述。

类注释使用“/** */”注释方式(1.42+)说明:方便JavaDoc收集,没有import可放在package之后。

注释可根据需要列出:作者、内容、功能、与其它类的关系等。

功能详细描述部分说明该类或者接口的功能、作用、使用方法和注意事项,每次修改后增加作者和更新版本号和日期,@since 表示从那个版本开始就有这个类或者接口,@deprecated 表示不建议使用该类或者接口。

/*** 〈一句话功能简述〉* 〈功能详细描述〉* @author [作者](必须)* @see [相关类/方法](可选)* @since [产品/模块版本] (必须)* @deprecated (可选)*/示例:package m;import java.util.*;/*** LogManager 类集中控制对日志读写的操作。

* 全部为静态变量和静态方法,对外提供统一接口。

分配对应日志类型的读写器,* 读取或写入符合条件的日志纪录。

* @author 张三,李四,王五* @see LogIteraotor* @see BasicLog* @since CommonLog1.0*/public class LogManager规则4类属性(成员变量)、公有和保护方法注释:写在类属性、公有和保护方法上面,注释方式为“/** */”.(1.42+)示例:/*** 注释内容*/private String logType;/*** 注释内容*/public void write()规则5公有和保护方法注释内容:列出方法的一句话功能简述、功能详细描述、输入参数、输出参数、返回值、异常等。

(1.42+)格式:/*** 〈一句话功能简述〉* 〈功能详细描述〉* @param [参数1] [参数1说明]* @param [参数2] [参数2说明]* @return [返回类型说明]* @exception/throws [异常类型] [异常说明]* @see [类、类#方法、类#成员]* @since [起始版本]* @deprecated*/说明:@since 表示从那个版本开始就有这个方法,如果是最初版本就存在的方法无需说明;@exception或throws 列出可能仍出的异常;@deprecated 表示不建议使用该方法。

示例:/*** 根据日志类型和时间读取日志。

* 分配对应日志类型的LogReader,指定类型、查询时间段、条件和反复器缓冲数,* 读取日志记录。

查询条件为null或0的表示没有限制,反复器缓冲数为0读不到日志。

* 查询时间为左包含原则,即 [startTime, endTime) 。

* @param logTypeName 日志类型名(在配置文件中定义的)* @param startTime 查询日志的开始时间* @param endTime 查询日志的结束时间* @param logLevel 查询日志的级别* @param userName 查询该用户的日志* @param bufferNum 日志反复器缓冲记录数* @return 结果集,日志反复器* @since 1.2*/public static LogIterator read(String logType, Date startTime, Date endTime, int logLevel, String userName, int bufferNum)规则6对于方法内部用throw语句抛出的异常,必须在方法的注释中标明,对于所调用的其他方法所抛出的异常,选择主要的在注释中说明。

对于非RuntimeException,即throws 子句声明会抛出的异常,必须在方法的注释中标明。

(1.42+)说明:异常注释用@exception或@throws表示,在JavaDoc中两者等价,但推荐用@exception标注Runtime异常,@throws标注非Runtime异常。

异常的注释必须说明该异常的含义及什么条件下抛出该异常。

规则7注释应与其描述的代码相近,对代码的注释应放在其上方,并与其上面的代码用空行隔开,注释与所描述内容进行同样的缩排。

(1.42+)说明:可使程序排版整齐,并方便注释的阅读与理解。

示例:/** 注释*/public void example2( ){// 注释CodeBlock One// 注释CodeBlock Two}/** 注释*/public void example( ){// 注释CodeBlock One// 注释CodeBlock Two}规则8对于switch语句下的case语句,必须在每个case分支结束前加上break语句。

(1.42+)说明:break才能真正表示该switch执行结束,不然可能会进入该case以后的分支。

至于语法上合法的场景“一个case后进入下一个case处理”,应该在编码设计上就避免。

规则9修改代码同时修改相应的注释,以保证注释与代码的一致性。

不再有用的注释要删除。

(1.42+)规则10注释的内容要清楚、明了,含义准确,防止注释二义性。

(1.42+)说明:错误的注释不但无益反而有害。

规则11避免在注释中使用缩写,特别是不常用缩写。

(1.42+)说明:在使用缩写时或之前,应对缩写进行必要的说明。

规则12对重载父类的方法必须进行@Override声明(5.0+)说明:可清楚说明此方法是重载父类的方法,保证重载父类的方法时不会因为单词写错而造成错误(写错方法名或者参数个数,类型都会编译无法通过)示例:@Overridepublic void doRequest(SipServletRequest req) throws ServletException, IOException1.2.2 建议建议1避免在一行代码或表达式的中间插入注释。

(1.42+)说明:除非必要,不应在代码或表达中间插入注释,否则容易使代码可理解性变差。

建议2在代码的功能、意图层次上进行注释,提供有用、额外的信息。

(1.42+)说明:注释的目的是解释代码的目的、功能和采用的方法,提供代码以外的信息,帮助读者理解代码,防止没必要的重复注释信息。

示例:如下注释意义不大。

// 如果 receiveFlag 为真if (receiveFlag)而如下的注释则给出了额外有用的信息。

// 如果从连结收到消息if (receiveFlag)建议3对关键变量的定义和分支语句(条件分支、循环语句等)必须编写注释。

(1.42+)说明:这些语句往往是程序实现某一特定功能的关键,对于维护人员来说,良好的注释帮助更好的理解程序,有时甚至优于看设计文档。

相关文档
最新文档