Java 编程风格指南
- 格式:pdf
- 大小:172.31 KB
- 文档页数:17
Java编程规范指南尽管编写干净、可读且易于维护的代码对于任何编程语言来说都很重要,但对于Java这样的大型编程语言来说尤为重要。
为了确保Java代码的一致性和可读性,许多编程规范指南被提出并广泛采用。
本文将介绍一些常用的Java编程规范指南,以帮助开发人员编写高质量和可维护的Java代码。
什么是编程规范?编程规范是一系列用于指导编程方法和代码风格的建议和准则。
这些规范通常涵盖代码组织结构、标识符命名、代码注释、错误处理、代码格式化等方面。
通过遵循编程规范,开发人员可以编写出具有一致性、可读性和易于维护性的代码。
为什么要遵循编程规范?遵循编程规范有助于提高代码质量和可维护性。
以下是一些遵循编程规范的好处:1.增加代码可读性:通过使用一致的命名约定、代码缩进和代码风格,他人可以更轻松地理解和阅读你的代码。
2.提高团队协作:当多个开发人员共同参与一个项目时,遵循相同的编程规范可以减少在代码集成和维护方面的问题,从而提高团队的协作效率。
3.减少错误和调试时间:规范化的代码结构和风格有助于减少错误和bug的产生,并提供更快的调试和错误排查体验。
4.可移植性和可扩展性:符合编程规范的代码更容易移植到其他平台或扩展到其他项目。
常用的Java编程规范指南接下来,我们将介绍一些常用的Java编程规范指南。
H1:命名规范良好的命名约定是编写可读性高和易于理解的代码的关键。
以下是常用的Java 命名规范:H2:类和接口•类名应该使用首字母大写的驼峰命名法,并且应该是一个名词。
•接口名应该与类名相似,但可以使用形容词或描述性的名词。
H2:变量和方法•变量名应该使用首字母小写的驼峰命名法,并且应该是一个名词或名词短语。
•方法名应该使用首字母小写的驼峰命名法,并且应该是一个动词或动词短语。
H1:代码结构和格式化良好的代码结构和格式化有助于提高代码的可读性。
以下是常用的Java代码结构和格式化指南:H2:缩进•使用四个空格进行缩进,而不是制表符。
Java编程规范和代码风格Java是一种广泛应用于软件开发的编程语言,拥有丰富的代码规范和编程风格。
本文将介绍Java编程规范的基本原则和一些常见的代码风格建议。
一、命名规范合理的命名规范是编写清晰可读的代码的基础。
以下是一些常见的命名规范建议:1. 类名应该采用首字母大写的驼峰命名法,例如:Person、Student。
2. 方法名和变量名应该采用首字母小写的驼峰命名法,例如:getName、setAge。
3. 常量名应该全部大写,使用下划线分隔单词,例如:MAX_VALUE、PI。
4. 包名应该全部小写,且只包含小写字母和点号,例如:com.example.project。
5. 避免使用单个字母作为变量名或者方法名,除非在临时变量的情况下。
二、缩进和空格良好的缩进和空格规范可以提高代码的可读性。
以下是一些常见的缩进和空格建议:1. 使用4个空格作为一个缩进层级,不要使用制表符。
2. 在每个语句的前后添加适当的空格,例如:if (condition) {。
3. 各种运算符前后都应该添加空格,例如:a + b,而不是a+b。
4. 方法之间应该使用空行进行分隔,以提高代码的可读性。
三、注释规范注释是代码中很重要的一部分,它可以提供给其他开发人员很多有价值的信息。
以下是一些常见的注释规范建议:1. 使用Javadoc风格的注释来描述类、方法和字段的作用和用法。
2. 在关键性的算法和复杂逻辑处添加必要的注释,增加代码的可读性。
3. 避免使用无意义的注释,注释应该与代码同步更新,避免产生过时的注释。
四、代码结构和规范良好的代码结构和规范可以提高代码质量和可维护性。
以下是一些常见的代码结构和规范建议:1. 一个源文件应该只包含一个公共类,且类名必须与文件名一致。
2. 方法应该保持简短,每个方法应该只做一件事情。
3. 避免使用魔法数值,应该使用有意义的常量进行替代。
4. 避免使用过长的行,一般不要超过80个字符。
代码规范和风格指南
嘿,你知道吗?代码也有它的“衣服”和“发型”呢!这就是代码规范和风格指南。
想象一下,如果每个程序员都按照自己的方式写代码,那岂不是乱成一锅粥?但有了规范和指南,大家的代码都能“穿”上统一的“衣服”,“剪”出好看的“发型”,这样读起来就舒服多了。
说到代码规范,它就像是那些告诉你该怎么穿衣、怎么走路的“规矩”。
比如变量名应该怎么取、注释该怎么写,还有代码应该怎么缩进。
有了这些“规矩”,代码就能像排队一样整齐。
而风格指南呢,更像是那些时尚达人给你的建议。
比如某个编程语言的特点该怎么用、某个设计模式为什么好用。
这些建议能让你的代码更有个性,就像街头的潮流达人一样。
当然啦,每个团队都有自己的“时尚品味”,所以代码规范和风格指南也要根据团队的实际情况来制定。
太严格了会让人束手束脚,太宽松了又会显得没规矩。
关键是要找到那个平衡点,让代码既好看又实用。
最后,要想让代码规范和风格指南真正发挥作用,还得靠大家自觉遵守。
毕竟,只有每个人都“穿”上好看的“衣服”,“剪”出好看的“发型”,整个团队才能更和谐、更有战斗力嘛!。
Java编程入门指南:基础、高级特性、框架和学习资源Java编程基础Java是一种面向对象编程语言,它是一种高级编程语言,代码容易理解和维护。
Java编程包括变量、条件判断、循环、函数、类和对象等方面。
变量是Java编程中非常基础的概念,它负责存储和操作数据。
Java中有多种类型的变量,包括字符串、整数、浮点数、布尔值等。
在Java中,变量必须声明后才能使用。
条件判断和循环是Java编程中非常重要的概念,可以让程序按照不同的条件执行不同的操作。
比如,使用if语句可以在满足某个条件时执行一段代码块,而while循环可以让一段代码重复执行多次。
函数是Java编程中非常重要的概念,它可以让我们把一段复杂的代码块封装在一个函数中,以便在需要时重复使用。
Java中的函数有很多参数类型,可以根据需要进行选择。
类和对象是Java编程中非常重要的概念,它是面向对象编程的基础。
类是一种模板或蓝图,它描述了对象的属性和方法,而对象是类的实例。
Java高级特性Java编程语言具有许多高级特性,包括多线程编程、反射、泛型、注解等等。
这些高级特性可以帮助开发者更加灵活地编写程序,提高软件的可维护性和复用性。
多线程编程是Java编程中非常重要的高级特性,可以让我们同时运行多个任务。
Java提供了许多关于线程的API,如创建线程、启动线程、暂停和恢复线程等。
反射是一种非常有用的高级特性,可以让我们在运行时获取与操作对象的信息。
Java中的反射API包括Class、Method、Field等类,可以帮助我们动态地调用方法和属性。
泛型是一种非常重要的高级特性,可以让我们编写更通用、更安全的代码。
Java中的泛型可以让我们在编译时检查类型,以避免运行时错误。
注解是Java中非常有用的高级特性,可以帮助我们在代码中添加元数据,以描述程序的各个方面。
Java中有许多内置注解,可以用于描述类、方法、字段等等。
Java框架和JavaScript技术Java框架是一种用于加快Java程序开发的工具套件,其中包括一系列组件、类库和规范。
Java程序设计指南第一章:Java程序设计基础1.1 Java语言概述- Java的起源和发展- Java的特点和优势- Java的应用领域1.2 Java开发环境的搭建- JDK、JRE和JVM的介绍- 安装Java开发工具包(JDK)- 配置Java开发环境变量1.3 第一个Java程序- 编写第一个Java程序- 编译和运行Java程序- 简单的输出和输入操作1.4 Java基本语法- 变量和数据类型- 运算符和表达式- 控制流程(条件语句和循环语句) - 注释和代码规范第二章:面向对象编程2.1 面向对象编程概述- 面向对象的特点和优势- 类和对象的概念- 封装、继承和多态2.2 类和对象- 类的定义和成员- 对象的创建和使用- 构造方法和析构方法2.3 成员变量和成员方法- 成员变量的定义和使用- 成员方法的定义和调用- this关键字的使用2.4 继承和多态- 继承的概念和用法- 方法重写和方法重载- 多态的实现和应用第三章:Java核心API3.1 字符串和常用数据结构 - 字符串的操作和常用方法 - 数组和集合的概念和使用 - 迭代器和泛型的应用3.2 输入和输出操作- 标准输入和输出- 文件的读写操作- 异常处理机制3.3 多线程编程- 多线程的概念和优势- 线程的创建和启动- 线程的同步和通信3.4 Java常用类库- Math类和常用数学函数- 时间和日期类的使用- 正则表达式的应用第四章:高级主题4.1 异常处理与调试技巧- 异常类型和捕获处理- 异常链和自定义异常- 调试技巧和工具的使用4.2 GUI编程与图形界面设计- AWT和Swing的概念和区别 - GUI组件的使用和布局- 事件处理和响应机制4.3 网络编程- 网络编程的基本概念- Socket编程和网络通信- HTTP协议和Web应用开发4.4 数据库编程- JDBC和数据库连接- SQL语句的执行和结果处理- 数据库事务和连接池的应用总结:本文以Java程序设计为主题,按照类别进行了章节划分,从Java语言基础、面向对象编程到Java核心API和高级主题,全面介绍了Java程序设计的基本知识和技能。
史上最全Java编程入门指南Java是一种广泛使用的编程语言,它在现代编程界具有重要地位。
随着计算机科学和技术的发展,越来越多的人开始学习Java 编程。
为了帮助那些初学者快速入门,本文提供了一个史上最全的Java编程入门指南。
一、Java编程语言简介Java是由James Gosling和其他一些开发人员在Sun Microsystems(现在是Oracle Corporation)中在20世纪90年代初创建的。
Java的设计目标是“一次编写,到处运行”。
Java是一种面向对象的编程语言(OOP),可以通过许多操作系统和硬件平台运行。
Java是一种非常强大的编程语言,它可以用于开发各种不同类型的软件,例如:桌面应用程序、Web应用程序和移动应用程序等。
此外,Java还可以用于开发企业级应用程序,例如:客户关系管理系统(CRM)和企业资源计划(ERP)系统等。
二、Java编程入门- 安装Java软件开发工具包(JDK)在您开始学习Java之前,您需要安装Java软件开发工具包(JDK)。
JDK包含Java编译器、Java虚拟机(JVM)和其他必要的开发工具。
您可以从Oracle的官方网站上下载JDK,下载和安装过程非常简单。
- 编写你的第一个Java程序接下来,您可以开始编写您的第一个Java程序了。
您可以使用任何文本编辑器编写Java程序。
此外,您也可以使用一些IDE (集成开发环境)来编写Java程序,例如:Eclipse、NetBeans或IntelliJ IDEA等。
下面是一个简单的Java程序,它将在控制台上打印出“Hello W orld”:```javapublic class HelloWorld {public static void main(String[] args) {System.out.println("Hello World");}}```要编译和运行Java程序,请使用以下命令:```javajavac HelloWorld.javajava HelloWorld```- 学习Java基本语法Java编程语言具有丰富的语法,您需要学习Java的基本语法,以便编写高质量的Java程序。
Java代码风格与规范:编写可读性强的代码引言在软件开发领域,编写可读性强的代码是非常重要的。
无论是个人开发还是团队合作,良好的代码风格和规范可以提高代码的可维护性和可扩展性。
本文将探讨Java代码风格与规范,以帮助开发者编写更加易读的代码。
一、命名规范良好的命名规范是编写可读性强的代码的基础。
在Java中,我们应该遵循以下命名规范:1. 类名应该使用名词或名词短语,采用驼峰命名法,首字母大写。
例如:Student, BookManager。
2. 方法名应该使用动词或动词短语,采用驼峰命名法,首字母小写。
例如:calculateTotal, printInfo。
3. 变量名应该使用名词或名词短语,采用驼峰命名法,首字母小写。
例如:studentName, bookCount。
4. 常量名应该使用大写字母和下划线,多个单词之间用下划线分隔。
例如:MAX_COUNT, DEFAULT_VALUE。
5. 包名应该采用小写字母,多个单词之间用点分隔。
例如:com.example.project。
二、代码缩进和格式化良好的代码缩进和格式化可以提高代码的可读性。
在Java中,我们应该遵循以下格式化规范:1. 使用四个空格进行缩进,而不是制表符。
这样可以在不同的编辑器和IDE中保持一致的缩进。
2. 在代码块之间留出适当的空行,以提高代码的可读性。
3. 在代码中使用适当的空格,例如在操作符周围和逗号后面。
4. 对于较长的代码行,应该在适当的位置进行换行,以避免超出编辑器的可见范围。
三、注释规范良好的注释可以提供代码的上下文和解释,帮助其他开发者理解代码的意图。
在Java中,我们应该遵循以下注释规范:1. 在类、方法和字段的上方使用JavaDoc注释,描述其用途和功能。
2. 在方法内部使用单行或多行注释,解释代码的关键步骤和逻辑。
3. 避免使用无意义的注释,注释应该提供有用的信息而不是重复代码本身。
4. 及时更新注释,保持注释与代码的一致性。
Java规范代码风格(阿⾥开发规范精简)制定代码规约的意义统⼀的代码风格可以让开发⼯程师们没有代码⼼理壁垒,每个⼈可以轻松阅读并快速理解代码逻辑,便于⾼效协作,逐步形成团队代码的风格。
⾼效标准统⼀,提升沟通效率和协作效率,好的编码规范可以最⼤限度的提⾼团队开发的合作效率。
质量长期的规范性编码还可以让开发⼈员养成好的编码习惯,甚⾄锻炼出更加严谨的思维,防患未然,提升质量意识,降低故障率和维护成本,快速定位问题。
情怀程序员应该追求代码的美、系统的美、设计的美,追求卓越的⼯匠精神,打磨精品代码。
命名【规范】类名使⽤UpperCamelCase 风格,必须遵从驼峰形式,但以下情形例外:(领域模型的相关命名)DO / BO / DTO / VO 等。
[正例]: MarcoPolo / UserDO / XmlService / TcpUdpDeal / TaPromotion[反例]: macroPolo / UserDo / XMLService / TCPUDPDeal / TAPromotion【规范】⽅法名、参数名、成员变量、局部变量都统⼀使⽤lowerCamelCase 风格,必须遵从驼峰形式。
[正例]:localValue / getHttpMessage() / inputUserId【规范】常量命名全部⼤写,单词间⽤下划线隔开,⼒求语义表达完整清楚,不要嫌名字长。
public static final String GET_APPLICATION_SETTINGS_BY_MESSAGE_NAME_AND_APP_NAME = "/v1/capp/common/getApplicationSettingsWithMessageNameAndAppName";【规范】抽象类命名使⽤ Abstract 或 Base 开头;异常类命名使⽤ Exception 结尾;测试类命名以它要测试的类的名称开始,以 Test 结尾。
Java编程语言入门指南第1章 Java简介 (2)1.1 Java的发展历程 (2)1.2 Java的主要特性 (3)1.3 Java的应用场景 (3)第2章 Java开发环境搭建 (4)2.1 JDK的与安装 (4)2.2 环境变量配置 (4)2.3 第一个Java程序 (5)第3章 Java基本语法 (5)3.1 标识符与关键字 (5)3.2 数据类型 (6)3.3 变量与常量 (6)3.4 运算符 (7)第4章 Java控制流程 (7)4.1 顺序结构 (7)4.2 分支结构 (7)4.2.1 if语句 (7)4.2.2 ifelse语句 (7)4.2.3 ifelse ifelse语句 (8)4.2.4 switch语句 (8)4.3 循环结构 (8)4.3.1 for循环 (9)4.3.2 while循环 (9)4.3.3 dowhile循环 (9)第5章 Java数组与字符串 (9)5.1 数组的基本概念 (9)5.2 数组的声明与初始化 (9)5.3 字符串的基本概念 (10)5.4 字符串的操作方法 (10)第6章面向对象基础 (12)6.1 类与对象 (12)6.2 构造方法 (12)6.3 成员变量与局部变量 (13)6.4 方法重载与重写 (14)第7章封装、继承与多态 (15)7.1 封装 (15)7.1.1 访问控制符 (16)7.1.2 getter和setter方法 (16)7.2 继承 (16)7.2.1 继承的定义 (16)7.2.2 方法重写 (16)7.3 多态 (16)7.3.1 编译时多态 (17)7.3.2 运行时多态 (17)7.4 抽象类与接口 (17)7.4.1 抽象类 (17)7.4.2 接口 (17)第8章 Java异常处理 (17)8.1 异常的概念 (17)8.2 异常的分类 (17)8.3 异常的捕获与处理 (18)8.4 自定义异常 (19)第9章 Java集合框架 (19)9.1 集合框架概述 (19)9.2 List接口及其实现类 (19)9.3 Set接口及其实现类 (20)9.4 Map接口及其实现类 (20)第10章 Java I/O流操作 (21)10.1 File类与文件操作 (21)10.1.1 File类的构造方法 (21)10.1.2 文件和目录操作 (21)10.1.3 文件属性查询 (21)10.2 字节流与字符流 (21)10.2.1 字节流 (21)10.2.2 字符流 (21)10.3 缓冲流 (21)10.3.1 缓冲字节流 (21)10.3.2 缓冲字符流 (21)10.4 转换流与对象流 (21)10.4.1 转换流 (22)10.4.2 对象流 (22)第1章 Java简介1.1 Java的发展历程Java编程语言最初由Sun Microsystems公司于1995年发布。
Java代码风格Coding-Style衡量软件质量: 功能性,即软件是否满⾜了客户业务要求; 可⽤性,即衡量⽤户使⽤软件需要付出多⼤的努⼒; 可靠性,即软件是否能够⼀直处在⼀个稳定的状态上满⾜可⽤性; ⾼效性,即衡量软件正常运⾏需要耗费多少物理资源; 可维护性,即衡量对已经完成的软件进⾏调整需要多⼤的努⼒; 可移植性,即衡量软件是否能够⽅便地部署到不同的运⾏环境中;提⾼代码质量需要注意的点: 避免重复代码,减少复制+写成函数⾥⽅便调⽤ 变量名,要容易理解 单元测试,⽤⼀些边界值+null值来测试 ⽤命名常量来代表⼀个特定数字,⽽不是直接嵌⼊ 局部变量尽量⽤途单⼀ 如果能⽤短⼩函数描述,则使⽤⼦函数替代注释本⾝ 保证⼀定的单元测试覆盖率,这个也可以在 CI 上做,低于⼀定覆盖率不让通过 Code Review 静态检测、动态检测 ⽅法参数列表,不宜过长;如果多个相关的参数可以封到⼀个类⾥⾯ 重构函数(写leetcode时训练): (1)、过长 (2)、嵌套层数过深。
(3)、⾃然分块,需要使⽤注释描述该程序块 (4)、判断条件过于复杂 (5)、参数过于复杂 最后:如果产品需求不停的改or上线时间紧迫,天王⽼⼦来了也的写烂代码(太赶了=>没有资格优雅;天天变or复⽤少=>不需要优雅⾼效)常⽤规范综述 优秀的代码:简洁清晰、可维护、可测试、可移植 风格⼀致性原则:尽量风格统⼀命名 少⽤缩写 有集合含义的属性,包含复数形式编码 源⽂件编码格式必须是UTF-8, ASCII ⽔平空格字符(0x20, 即空格)是唯⼀允许出现的空⽩字符;制表符不⽤于缩进。
Java缩写词,也⽤驼峰:supportsIpv6OnIos命名风格⼤驼峰:类、接⼝、注解⼩驼峰:⽅法、局部变量命名全⼤写:静态常量、枚举值注释⽂件头注释:版权信息、⽇期、功能说明⽅法等注释:Javadoc⽤于每⼀个public或protected修饰的元素@param @return @throws 顺序来不⽤的import直接删除,不要注掉// TODO(<author-name>): 补充xx内容// FIXME:修复xx缺陷排版格式避免⽂件过长,净含量不超过2000⾏(⾮空⾮注释) ==》横向拆分:根据职责; ==》纵向拆分:根据层次每⾏不超过⼀个语句每⾏限长120(英⽂)窄字符==60汉字字符(也叫全⾓字符、东亚字符)⾏位、空⾏不能有空格不要⽤C风格数组声明:⽅括号构成类型的⼀部分,是:String[] args,⽽不是String args[]变量和类型浮点数不能为循环因⼦,精度问题会导致 (float) 2000000000 == 2000000050为true浮点数在⼀个范围很⼴的值域上提供了很好的近似,但是它不能产⽣精确的结果。
Java编程指南Java是一种广泛使用的计算机编程语言,它被广泛应用于开发各种类型的应用程序。
无论是大型企业系统还是小型移动应用,Java都可以提供强大和可靠的性能。
然而,要成为一名优秀的Java程序员,并不仅仅需要掌握语言的基本语法和概念,还需要具备一定的编程指南和技巧。
首先,让我们来谈谈代码风格。
良好的代码风格可以使代码更加易读、易于维护,并减少错误的可能性。
在Java中,有一些通用的代码风格规范,例如使用驼峰命名法来命名变量、方法和类名,使用适当的缩进和空格来增加可读性等。
此外,使用有意义的变量和方法名可以使代码更加易于理解,从而提高代码的可维护性。
其次,我们应该遵循面向对象编程的原则。
在Java中,一切都是对象,因此,良好的面向对象设计是非常重要的。
尽量使用封装、继承和多态等概念,使代码具有高内聚和低耦合的特性。
这样可以使我们的代码更加模块化、可扩展和可重用。
在编写Java代码时,我们需要了解异常处理。
Java中的异常处理是一种异常情况的处理机制,它能够使我们的程序更加健壮和容错。
合理地使用try-catch语句块可以处理可能出现的异常,并给出相应的处理方式。
此外,还可以使用throws关键字来抛出异常,使调用者能够处理异常。
除了代码风格、面向对象和异常处理外,还有一些其他的重要指南需要我们遵循。
首先是关于内存管理的指导。
在Java中,我们需要手动分配和释放内存,这可能导致内存泄漏和性能问题。
因此,我们需要合理地使用垃圾回收机制,及时释放不再需要的对象,以避免程序的内存占用过高。
其次,对于Java的标准库和第三方库的使用,我们也需要一些指导。
标准库提供了丰富的类和方法,可以帮助我们处理各种任务。
熟悉并合理使用这些库将使我们的开发更加高效。
此外,第三方库也是我们开发中不可或缺的一部分。
然而,我们应该慎重选择和使用第三方库,以确保其质量和安全性。
最后,让我们来谈谈测试。
在编写Java代码时,测试是至关重要的。
JAVA编程风格建议学会分解问题学会分解问题,不管你是在面向过程还是面向对象。
其实,面向过程和面向对象,对程序员来说没有什么具体的含义。
因为,当你真正分解完问题,自然会知道哪部分是面向过程的,哪部分用面向对象来做简单。
举个例子来说明怎么分解问题。
而不是在问题一产生的时候,就尝试解决它。
现在我们考虑如何编程解决这个问题。
1穷举法。
2人工智能寻道法。
后面的就不是编程的基础技能了,我们这里用穷举法。
穷举法就是我们把所有的可能的情况都考虑过一遍。
看题目。
我们知道每个人有不同的房子(第0间,第1间……) 每个人住不同颜色的房子(白,红,绿,黄,蓝)有不同的国籍(英国,瑞典,丹麦,挪威,德国)不同的饮料,不同的香烟,不同的宠物。
而题目中的情况就是把5个人,各种住不同房子,有不同国籍的情况分布一遍。
而检验这个情况是否合理,就是后面的16个条件的检查。
于是我们现在分2步,1产生所有的情况,2检验情况先补充基础类有了基础数据。
的定义我们就可以开始做第一步了。
列举所有的Case先不急得实现。
我们已经把上述的问题分解到如此。
我们需要的只是完成3个方法,一个可以把所有case统统枚举一遍。
一个验证这个case 是否能通过那16个条件验证。
然后再加入一个输出这个case的情况的方法。
输出case情况我们可以列用类本身的toString所以我们只剩下2个问题要考虑。
其中checkCase已经很明显了,如:剩下一个比较大问题就是。
如何列举出所有Case按排列组合的理论。
仅考虑一个房子是什么颜色的,可能[白,红,绿,黄,蓝][白,红,绿,蓝,黄][白,红,黄,绿,蓝][白,红,黄,蓝,绿][白,红,蓝,绿,黄][白,红,蓝,黄,绿]……等若干种情况,(如果依据排列组合式120种,不过对于用穷举法的我们这个数值是没有必要知道的)。
而这个case有5个维度。
每个维度都有这若干种情况。
那么,应该有若干的5次方个case编码的话,就是5个循环嵌套,每个循环从0到若干。
1. 风格务必保持一贯性(Consis tent)一位同胞顶着我的鼻子问,为什么我们的Java代码缩进格式非得是这样,而不能是他那样,他就是喜欢他自己的这一种,因此他写的代码总是用他自己习惯的风格。
结果在Cod e Review里被大家毙掉,责令修改。
因此他是大大地不服。
就是风格一贯性问题。
其实他的风格,本来也没有什么问题,但在项目里,和其他程序员的程序的风格,显得扃异,那就存在问题了。
比如这个缩进,又比如变量命名方法,不同的类,不同的Met hods里,各自不同,这程序就很难看了。
所以一旦你选择了某种风格,一定要贯彻始终。
如果一个项目里规定了一个风格,即便很不符合你自己的习惯,也要贯彻始终,绝不应该有标新立异。
2. 缩进风格(indent)既然是从缩进说起,就先说说缩进风格;一般来说,象Java这样的类C语言,都采用缩进风格。
而常用的,有四种A.K&R风格这是C程序最早的缩进风格,由C的发明者Ritch ie和他的合作者Ke rnigh an率先使用:if (<cond>) {<body>}其特点,是大括号和i f判断在同一行。
通常,缩进为8个空格或一个t ab 键,但在C++和Java里,也常缩进4个空格。
有人喜欢用两个空格,窃以为不好,不明显。
B. BSD风格又称Allm an Style,源自Unix BSD程序员EricAllman--他为BSD写过很多程序:if (<cond>){<body>}特点:大括号和条件判断分在两行。
C. Whites mith风格这种风格源于White smith C:if (<cond>){<body>}D.GNU风格这种风格仅见于GNUEMACS的源程序中:if (<cond>){<body>}那么在Jav a里用哪种好呢?建议只采用A或B。
Java编程风格与命名规范1.包命名包名按照域名的范围从大到小逐步列出,恰好和Internet上的域名命名规则相反。
由一组以“。
”连接的标识符构成,通常第一个标识符为符合网络域名的两个或者三个英文小写字母。
2.接口命名类的名字必须由大写字母开头而单词中的其他字母均为小写;如果类名称由多个单词组成,则每个单词的首字母均应为大写例如TestPage;如果类名称中包含单词缩写,则这个所写词的每个字母均应大写,如:XMLExample,还有一点命名技巧就是由于类是设计用来代表对象的,所以在命名类时应尽量选择名词。
3.方法名方法的名字的第一个单词应以小写字母作为开头,后面的单词则用大写字母开头。
可以为动词或动词+名词组合。
设置/获取某个值的Method,应该遵循setV/getV规范返回长度的Method,应该命名为length测试某个布尔值的Method,应该命名为isV将对象转换为某个特定类型的Mehod应该命名为toFa.普通变量命名应该采用首字母小写,其他字母首字母大写的方式。
b.final static变量的名字应该都大写,并且指出完整含义。
如果一个常量名称由多个单词组成,则应该用下划线来分割这些单词,如NUM_DAYS_IN_WEEK MAX_VALUc. 如果需要对变量名进行缩写时,一定要注意整个代码中缩写规则的一致性d. 通过在结尾处放置一个量词,就可创建更加统一的变量First(一组变量中的第一个) Last(一组变量中的最后一个) Next(一组变量中的下一个变量) Prev(一组变量中的上一个) Cur(一组变量中的当前变量)e. 无论什么时候,均提倡应用常量取代数字、固定字符串。
也就是说,程序中除0,1以外,尽量不应该出现其他数字。
f. 索引变量:i、j、k等只作为小型循环的循环索引变量。
g. 逻辑变量:避免用flag来命名状态变量,用is来命名逻辑变量。
5.数组总是使用以下方式定义数组:int[] arr = new int[10];禁止使用C语言的是形式:禁止intarr[] = new int[10];数组或者容器推荐命名方式为名词+s的方式,例如:List persons = getPerson(); for(Person person : persons){ dosomeworks; }7.泛型应该尽量简明扼要(最好是一个字母),以利于与普通的class或interface 区分Container中的Element应该用E表示;Map里的key用K表示,value 用V;Type用T表示;异常用X表示如果需要接收多个Type类型的参数,应该用邻接T的大写字母——例如S ——来依次表示,当然也可以用T1, T2这样的方式。
此为英文版,英文好些的,可以看看英文。
除此之外,例子也很详细,直观,一看就懂。
大家看看可以提高自己的编程风格和交流代码。
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.。