java 代码标准规范 Coding Standards
- 格式:doc
- 大小:115.50 KB
- 文档页数:21
java 代码规范Java代码规范是为了提高代码的可读性、可维护性和可扩展性而制定的一系列约定。
遵循代码规范能够提高团队合作的效率,使代码更易于理解和调试。
1. 命名规范:- 类名和接口名使用大驼峰命名法,即每个单词首字母大写,如`MyClass`;- 方法名和变量名使用小驼峰命名法,即第一个单词首字母小写,其他单词首字母大写,如`myMethod`;- 常量名使用全大写,并用下划线分隔单词,如`MAX_COUNT`;- 缩写词只能用首字母,如`createURL`。
2. 缩进与空格:- 使用4个空格进行缩进,不使用Tab键;- 运算符前后留一个空格,如`a = b + c`;- 每行代码长度不超过80字符。
3. 大括号:- 大括号另起一行,并且与前面的代码保持一个空格的间距;- 例外情况是单行代码块可以省略大括号。
4. 注释规范:- 使用Javadoc格式的注释对类、接口、方法进行文档化,包括描述、参数、返回值等内容;- 对于代码的解释,可以使用单行或多行注释,但要注意不要过度注释。
5. 继承与接口:- 只有当类与接口之间有明确的"is-a"关系时,才使用继承;- 当多个类具有相同的行为时,使用接口进行实现。
6. 异常处理:- 必须捕获异常或者在方法签名中声明抛出异常,不要使用空的catch块;- 在catch块中至少包含对异常的简要说明和处理过程。
7. 方法规范:- 方法应该具有明确的功能,只完成一个任务;- 方法长度不超过40行,尽量保持简短。
8. 避免使用魔术数字:- 将常用的数字定义为常量,以便于代码的理解和维护。
9. 使用合适的数据结构:- 使用集合类或者数组来存储多个相同类型的数据;- 使用枚举类型来表示一组常量。
10. 错误处理与日志:- 合理处理异常,避免出现未捕获的异常;- 使用日志记录程序运行过程中的关键信息。
以上是一些较为常见的Java代码规范,但实际上还有很多方面需要考虑。
java编码规范文档# Java编码规范文档。
一、前言。
小伙伴们!当我们一起在Java的世界里畅游时,要是大家都按照一套约定俗成的编码规范来写代码,那我们的代码就像训练有素的军队一样,整齐又高效。
这份规范就是我们在Java编程旅程中的小指南,让我们的代码既容易理解,又方便维护。
二、命名规范。
# (一)包(package)命名。
1. 包名应该全部小写,用点(.)分隔单词。
就像你的小包裹要摆放得井井有条一样,包名也得规规矩矩。
例如:`com.example.myproject`,这看起来多清爽。
如果写成`Com.Example.MyProject`,那就像穿着奇装异服的士兵混在整齐的队伍里,很不协调。
# (二)类(class)命名。
1. 类名采用大驼峰命名法(UpperCamelCase),每个单词的首字母大写,不要包含下划线或者其他奇怪的符号。
这就好比给每个班级取一个正式又响亮的名字。
比如:`MyFirstClass`,而不是`my_first_class`或者`my first class`。
那些奇怪的写法就像给班级取个让人摸不着头脑的名字,可不好。
# (三)方法(method)命名。
1. 方法名采用小驼峰命名法(lowerCamelCase),第一个单词小写,后面每个单词首字母大写。
这就像给方法这个小助手取个清晰明了的名字,方便我们知道它是干什么的。
例如:`calculateSum`,而不是`Calculate_Sum`或者`CALCULATESUM`。
要是写成后面那种,就像一个小助手穿着奇装异服,你都不知道它是来帮忙做什么的。
# (四)变量(variable)命名。
1. 变量名同样采用小驼峰命名法。
变量就像一个个小盒子,我们得给它们取个能让人一眼就大概知道里面装什么东西的名字。
像`studentName`,你一看就知道这个变量可能是用来存学生名字的。
要是写成`student_name`或者`STUDENTNAME`,就有点让人迷糊啦。
Java编程的标准之JA V A编程规范简介本文提供一整套编写高效可靠的 Java 代码的标准、约定和指南。
它们以安全可靠的软件工程原则为基础,使代码易于理解、维护和增强。
而且,通过遵循这些程序设计标准,你作为一个 Java 软件开发者的生产效率会有显著提高。
经验证明,若从一开始就花时间编写高质量的代码,则在软件开发阶段,对代码的修改要容易很多。
最后,遵循一套通用的程序设计标准将带来更大的一致性,使软件开发团队的效率明显提高。
最根本的原则:运用常识。
当找不到任何规则或指导方针,当规则明显不能适用,当所有的方法都失效的时侯:运用常识并核实这些基本原则。
这条规则比其它所有规则都重要。
常识是必不可少的。
程序设计标准Java 的程序设计标准很重要,原因在于它将提高开发团队各成员的代码的一致性。
一致性的提高会使代码更易理解,这意味着它更易开发和维护。
从而降低了应用程序的总开发成本。
你必须牢记的是:你的 Java 代码在你已离开并开始另一个项目之后,会保留相当长的一端时间。
因此开发过程中一个很重要的目标就是要确保在开发成员或开发团队之间的工作可以顺利交接,不必花很大的力气便能理解已编写的代码,以便继续维护和改进以前的工作。
如果代码难以理解,很有可能被废弃和重写。
命名约定我们将在整个标准中讨论命名约定,所以让我们先讨论几个基本点:1.使用可以准确说明变量/字段/类的完整的英文描述符。
例如,采用类似firstName,grandT otal或CorporateCustomer这样的名字。
虽然象x1,y1或fn这样的名字很简短,输入起来容易,但是我们难以知道它们代表什么、结果是什么含义,因而使代码难以理解、维护和改进。
2.采用该领域的术语。
如果用户称他们的“客户” (clients) 为“顾客”(customers),那么就采用术语Customer来命名这个类,而不用Client。
许多程序开发者会犯的一个错误是,不去使用工业或领域里已经存在着很完美的术语时,却生造出一些普通词汇。
[CodingStyle]官⽅Java编码规范原⽂地址Oracle官⽅Java编码规范(英⽂版)1 介绍(Introduction)1.1 为什么要有编码规范(Why Have Code Conventions)编码规范对于程序员⽽⾔尤为⾸要,有以下⼏个原因:⼀个软件的⽣命周期中,80%的花费在于维护⼏乎没有任何⼀个软件,在其全部⽣命周期中,均由最初的开辟⼈员来维护编码规范可以改良软件的可读性,可以让程序员尽快⽽彻底地懂得新的代码若是你将源码作为产品公布,就须要确任它是否被很好的打包并且清楚⽆误,⼀如你已构建的其它任何产品为了履⾏规范,每个软件开辟⼈员必须⼀致遵守编码规范。
每⼩我。
1.2 版权声明(Acknowledgments)本⽂档反应的是Sun MicroSystems公司,Java说话规范中的编码标准项⽬组。
⾸要供献者包含:Peter King,Patrick Naughton,Mike DeMoney,Jonni Kanerva,Kathy Walrath以及Scott Hommel。
本⽂档现由Scott Hommel维护,有关评论定见请发⾄shommel@2 ⽂件名(File Names)这项⽬组列出了常⽤的⽂件名及厥后缀。
2.1 ⽂件后缀(File Suffixes)Java程序应⽤下列⽂件后缀:⽂件类别⽂件后缀Java源⽂件.javaJava字节码⽂件.class2.2 常⽤⽂件名(Common File Names)常⽤的⽂件名包含:⽂件名⽤处GNUmakefile makefiles的⾸选⽂件名。
我们采取gnumake来创建(build)软件。
README概述特定⽬次下所含内容的⽂件的⾸选⽂件名3 ⽂件组织(File Organization)⼀个⽂件由被空⾏分别⽽成的段落以及标识每个段落的可选注释共同构成。
跨越2000⾏的程序难以浏览,应当尽量避免。
"Java源⽂件典范"供给了⼀个布局公道的Java程序典范。
alibaba java coding guidelines规则关于阿里巴巴Java编码规范规则的详细解析引言在Java开发中,编码规范是非常重要的,它不仅可以提高代码的可读性和可维护性,还有助于团队合作和代码的风格统一。
阿里巴巴作为中国最大的电商企业之一,拥有庞大的Java开发团队,为了统一团队的代码风格,提高代码质量,他们制定了一整套的Java编码规范,即阿里巴巴Java编码规范(下称“规范”)。
本文将以规范中的主题“[alibaba java coding guidelines规则]”为主线,逐条解析规范并给出相应的理解和实践建议。
一、规则一:命名规约1. 【强制】类名使用UpperCamelCase规范,方法名、成员变量名和局部变量名均使用lowerCamelCase规范。
命名规约是代码中最直观的内容之一,良好的命名规约可以提高代码的可读性和可维护性。
在使用UpperCamelCase和lowerCamelCase规范时,可以根据命名对象的特点选择合适的规范。
例如,类名通常代表一种抽象的概念,适合使用UpperCamelCase规范,而方法名、成员变量名和局部变量名通常代表具体的实现细节,适合使用lowerCamelCase规范。
2. 【强制】类名和方法名以功能命名,不以数据结构命名。
命名时应关注方法或类的功能,而不是内部的数据结构。
使用功能命名可以更好地描述代码的用途,并且随着代码的演进,内部的数据结构可以灵活变化而不会影响命名的准确性。
3. 【强制】定义枚举类型时,使用Enum后缀。
为了提高代码的可读性,对于枚举类型的定义,应统一添加Enum后缀。
例如:javapublic enum ColorEnum { ... }4. 【推荐】避免过长或过短的命名。
命名应该尽量精简明了,避免过长或过短的命名。
过长的命名可能会降低代码的可读性,而过短的命名则可能无法准确描述代码的含义。
5. 【推荐】对于常量和静态变量,使用全大写字母加下划线的命名规范。
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 编码规范。
1.代码格式- 代码缩进:使用四个空格。
- 代码行长度:每行不超过80个字符。
- 代码块括号:左大括号放在语句后,右大括号独立一行。
- 空行:在方法或类中的单独任务之间使用空白行来分隔。
- 其他注意事项:避免使用过多的空格,在行末不要有空格,避免使用tab字符。
2.命名规范- 包名:使用小写字母,多个单词使用.分割。
- 类名:使用驼峰命名法,每个单词首字母大写。
- 方法名:使用驼峰命名法,每个单词首字母小写。
- 变量名:使用驼峰命名法,每个单词首字母小写。
- 常量名:所有字母大写,单词之间用_分割。
- 其他注意事项:名称应该避免缩写,可读性要优先。
3.注释- 类、方法和变量都应该进行注释。
- 类和方法的注释应当使用javadoc格式。
- 变量和常量可以使用单行注释或行尾注释。
- 注释要避免使用无意义的话语,应该简明扼要地描述该元素的意义。
Java编码规范对开发人员来说是非常重要的,这能让代码更清晰、可读性更强,并且统一规范有助于团队协作的进行。
了解并遵循Java编码规范,可以帮助开发人员编写出高质量的Java代码,从而提高代码质量,减少bug的出现,提高项目的稳定性。
此外,标准的Java编码规范可以方便代码的查看和维护,便于未来项目的扩展。
因此,遵循Java编码规范是每个Java开发人员的责任和义务。
alibaba java coding guidelines 在vscode中插件使用方法一、什么是Alibaba Java Coding Guidelines?在软件开发领域,编码规范是非常重要的,它可以帮助团队成员编写出高质量、易于维护和易于理解的代码。
Alibaba Java Coding Guidelines是阿里巴巴集团内部制定的Java编码规范,旨在统一团队成员的编码风格,提高代码质量和可读性。
Alibaba Java Coding Guidelines涵盖了代码的命名规范、注释规范、代码风格规范等方面,通过严格遵守这些规范,可以有效地提升Java项目的质量。
二、在VSCode中使用Alibaba Java Coding Guidelines插件方法1. 打开VSCode,点击左侧的Extensions图标,搜索并安装“Alibaba Java Coding Guidelines”插件。
2. 安装完成后,点击VSCode左下角的Setting图标,搜索“java configuration”以找到Java相关的配置项。
3. 找到“java configuration”里关于编码规范的设置,将其设置为“alibaba”,这样就可以启用Alibaba Java Coding Guidelines规范了。
4. 接下来,在编辑Java文件时,插件会自动检测代码是否符合Alibaba Java Coding Guidelines规范,如果有不符合的地方,会有相应的警告或建议显示。
5. 除了实时的检测,插件还可以通过快捷键或右键菜单提供一键修复的功能,帮助开发者快速地调整代码,使其符合规范。
三、个人观点和理解作为一名开发者,我深知编码规范的重要性。
Alibaba Java Coding Guidelines不仅是对编码规范的约定和规范,更是对代码质量和团队协作的重要保障。
在使用Alibaba Java Coding Guidelines插件的过程中,我发现它能够有效地规范开发过程,减少团队成员之间的代码风格差异,提高代码的可读性和可维护性。
java 代码规范Java代码规范是指在Java程序设计中遵循的一些规则和约定,旨在提高代码的可读性、可维护性和可移植性。
遵守代码规范可以帮助团队成员更好地理解和协作开发,提高代码的质量和可靠性。
本文将围绕Java代码规范展开讨论,包括命名规范、代码风格、注释规范、异常处理等方面的内容。
一、命名规范1.包名规范包名应该全小写,连接符可以使用小写字母和下划线,不推荐使用数字。
包名应该能够清晰地表达包所包含的内容,不要使用太长或者太短的包名。
2.类名规范类名应该采用驼峰命名法,首字母大写,类名应该能够清晰地表达类的用途,不要使用太长或者太短的类名。
如果类名由多个单词组成,应该遵循每个单词首字母大写的命名规范。
3.接口名规范接口名应该采用驼峰命名法,首字母大写,接口名应该能够清晰地表达接口的用途,不要使用太长或者太短的接口名。
如果接口名由多个单词组成,应该遵循每个单词首字母大写的命名规范。
4.变量名规范变量名应该采用驼峰命名法,首字母小写,变量名应该能够清晰地表达变量的用途,不要使用太长或者太短的变量名。
如果变量名由多个单词组成,应该遵循每个单词首字母小写的命名规范。
5.常量名规范常量名应该全大写,单词之间使用下划线分隔,常量名应该能够清晰地表达常量的用途,不要使用太长或者太短的常量名。
6.方法名规范方法名应该采用驼峰命名法,首字母小写,方法名应该能够清晰地表达方法的用途,不要使用太长或者太短的方法名。
如果方法名由多个单词组成,应该遵循每个单词首字母小写的命名规范。
二、代码风格1.缩进和空格缩进使用4个空格,不使用tab键。
在操作符前后使用空格,增强代码的可读性。
2.大括号的使用在类定义、方法定义、控制结构等的语句块后面使用大括号,增强代码的可读性。
3.代码行长度每行代码的长度不要超过80个字符,超过80个字符的代码应该使用换行符进行分割。
4.引号的使用字符串常量应该使用双引号,字符常量应该使用单引号。
####Java Coding StandardsVersion 1.1Table of Contents1Introduction 41.1Purpose 41.2Scope 41.3References 42General Concepts 52.1Why are coding standards important? 52.2What Makes a Good Name? 52.3Good Documentation 72.4Internationalization 73Java Source Files 93.1Package Naming 93.2Import Statements 93.3Comments 93.4Class Guidelines and Naming Conventions 103.5Method Guidelines and Naming Conventions 113.5.1The 60 Second Rule 113.5.2Naming Guidelines 113.5.3Visibility 113.6Field (Variable) Guidelines 113.7Code formatting 123.7.1Indentation 123.7.2White Space 123.7.3Line Length 123.7.4Wrapping Lines 133.7.5Control Structure Formatting 144Programming Practices 164.1Access to Instance and Class Variables 164.2Referring to Static Class Variables and Methods 164.3Local Variables 164.3.1Naming Local Variables 174.4Variable Assignments 184.5Multi-function Operators 184.6Ternary Operator 184.7Order of Operations / Parentheses 19 5Code Example 20Java Coding Standards1 IntroductionThis document is to detail the Java coding standards specific to #### Software Inc. This document is amodification of the coding standards from Sun Microsystems Inc. Most of the material herein is taken from the “Java Code Conventions” document published by Sun Microsystems and available at/docs/codeconv/. Where appropriate, modifications have been made and additionalmaterial has been added to cover the entire scope of coding at #### Software Inc.1.1 PurposeThis document is intended to assist developers in the area of code development, such that all codedeveloped by #### Software will look similar. Code developed according to a standard is proven toincrease readability, make code easier to maintain and greatly reduce maintenance costs.1.2 ScopeThe scope of this coding standard is for the #### Project initially. However, it is desirable that anydevelopment in Java by #### Software Inc. would follow these standards.1.3 References1.“Code Conventions for the Java Programming Language”, April 20, 1999, version2.1, Sun MicrosystemsInc. (/docs/codeconv/)2 General Concepts2.1 Why are coding standards important?Coding standards for Java are important because they lead to greater consistency within your code and the code of your teammates. Greater consistency leads to code that is easier to understand, which in turn means it is easier to develop and to maintain. This reduces the overall cost of the applications that you create.You have to remember that your Java code will exist for a long time, long after you have moved on to other projects. An important goal during development is to ensure that you can transition your work to anotherdeveloper, or to another team of developers, so that they can continue to maintain and enhance your work without having to invest an unreasonable effort to understand your code. Code that is difficult to understand runs the risk of being scrapped and rewritten – nobody would be proud of the fact that their code needed to be rewritten. If everyone is doing their own thing then it makes it very difficult to share code betweendevelopers, raising the cost of development and maintenance.No standard is perfect and no standard is applicable to all situations; sometimes you find yourself in asituation where one or more standards do not apply. This leads the prime directive of standards:When you go against a standard, document it.All standards, except for this one, can bebroken. If you do so, you must document why you broke the standard, the potential implications ofbreaking the standard, and any conditions that may/must occur before the standard can be appliedto this situation.The bottom line is that you need to understand each standard, understand when to apply them, and just as importantly when not to apply them.2.2 What Makes a Good Name?We will be discussing naming conventions throughout the standards, so let’s set the stage with a few basics:e full English descriptors that accurately describe the variable/field/class/…For example, usenames like firstName, grandTotal, or CorporateCustomer. Although names like x1, y1, or fnare easy to type because they’re short, they do not provide any indication of what they represent andresult in code that is difficult to understand, maintain, and enhance.e terminology applicable to the domain.If your users refer to their clients as customers, then usethe term Customer for the class, not Client. Many developers will make the mistake of creatinggeneric terms for concepts when perfectly good terms already exist in the industry/domain.e mixed case to make names readable.You should use lower case letters in general, but capitalizethe first letter of class names and interface names, as well as the first letter of any non-initial word.Non-constant names should not contain underscores. Constant values (static final types) shouldbe all uppercase with underscores separating parts of the name. This makes it easy to recognizeconstants where they are used in the source code. Note that this rule applies only to types which areboth static and final; it does not apply to simply static types (whose values can be alteredduring execution).Examples: public class MyClass {private int simpleVariable;private static final int SOME_VALUE = 0;…}e abbreviations sparingly, but if you do so then use them intelligently.This means you shouldchoose them wisely, and you should use them consistently. For example, if you want to use a short form for the word “number,” then choose one of nbr, or num, and use only that one.5.Avoid long names (< 15 characters is a good idea).Although the class namePhysicalOrVirtualProductOrService might seem to be a good class name at the time this name is simply too long and you should consider renaming it to something shorter, perhaps something like Offering. Like all the standards, there are times you might choose to violate this one. For example, class names are often created by code generation tools. When extending or created related classes it might make sense to use similar long names.6.Avoid names that are similar or differ only in case.For example, the variable namespersistentObject and persistentObjects should not be used together, nor shouldanSqlDatabase and anSQLDatabase (singular and plural forms of the same name). This is the motivation for using the “List” postfix on collections – it avoids the singular/plural forms of the name from getting confused (see the next item).e “List” postfix for collections and collection classes. A collection which contains objects ofsome type should have the postfix “List” on the name. For example, a class which is a collection of Customer objects would be CustomerList. Likewise, a reference to a CustomerList object might be named overdueCustomerList. Using the list postfix clearly distinguishes the collection from a singular instance of an item in the collection. For example, it avoids having the object references goodCustomer and goodCustomers in the same code section – this leads to code which has to be very carefully read to be understood correctly.8.Avoid leading or trailing underscores. Avoid underscores altogether except in static final types (see#3 above).9.Avoid type-based (“Hungarian”) Notation. This technique prefixes names with an abbreviated typecode (such as “i” for integer, “f” for float, “str” for String, etc.). Although once very popular in the C/C++ environment, it has proven to be ineffective for a number of reasons:a)It simply makes source code more difficult to read. In extreme cases code becomes almostillegible due to the excessive prefixing required. Hard to read code is hard to enhance andmaintain.b)When such names appear in interfaces (public class properties or via accessor methods) they fixthe interface to a specific data type. If the interface is changed you are faced with either leavingthe name the same and have the prefix not match the type, or changing the name and changing all code that references it. A classic example of this problem exists in the Windows 95 operatingsystem. The type of a message parameter was changed from an unsigned short to an unsignedlong between Windows 3.1 and Windows 95. To maintain source compatibility the parameterna me is still “usParam” but in fact the parameter is an unsigned long (“ul”) , not an unsignedshort (“us”). Now the interface is inconsistent because the notation no longer matches theimplementation.c)With the complex objects of Java (and other OO languages), the prefix notation is not adequate toexpress the datatype anyway, except at the most primitive level. Since objects may be cast up ordown the inheritance tree, or cast to an interface which is implemented by the object, no singleprefix can properly describe the object type.2.3 Good DocumentationWe will also be discussing documentation conventions, so let’s discuss some of the basics first:ments should add to the clarity of your code.The reason why you document your code is tomake it more understandable to you, your coworkers, and to any other developer who comes after you.2.If your program isn’t worth documenting, it probably isn’t worth running.What else needs to besaid? This hits the nail on the head.3.Avoid decoration, i.e. do not use banner-like comments.In the 1960s and 1970s programmers gotinto the habit of drawing boxes, typically with asterisks, around their internal comments. It adds littlevalue to the end product. You want to write clean readable code, not draw pretty boxes. Usingseparator comment lines (a single line of dashes or asterisks) to offset an important comment block canbe useful, but do not take time to create or maintain a full box around the comments.4.Keep comments simple.Some of the best comments are simple, point-form notes. You do not have towrite a book, you just have to provide enough information so that others can understand your code.5.Write the documentation before, or as, you write the code.The best way to document code is towrite the comments before you write the code. This gives you an opportunity to think about how thecode will work before you write it and will ensure that the documentation gets written.Alternatively, you should at least document your code as you write it. Because documentation makesyour code easier to understand you are able to take advantage of this fact while you are developing it.This of it this way: if you are going to invest the time writing documentation you should at least getsomething out of it. If you write a l ong section of code and think “I’ll come back later and put incomments” –don’t. Write the comments as you go; it will help you understand and think about thecode you are writing.Comments written later are usually superficial and lack the insight that existed at the time the code waswritten. Write them while the ideas behind the logic are fresh in your mind.Also, be very careful when cut & paste is used in writing documentation comments. Most inaccuraciesoccur when comments are pasted, but the writer fails to make the necessary changes to the comments.6.Document why something is being done, not just what.Fundamentally, a programmer can alwayslook at a piece of code and figure out what it does. For example, anyone can see from the code belowthat a 5% discount is being given on orders of $1,000 dollars or more. Why is this being done? Is therea business rule that says that large orders get a discount? Is there a limited-time special on large ordersor is it a permanent program? Was the original programmer just being generous? You don’t knowunless it is documented somewhere, either in the source code itself or in an external document.if ( grandTotal >= 1000.00){grandTotal = grandTotal * 0.95;}2.4 InternationalizationJava has some built in support for internationalization via objects called Resource Bundles. The key tomaking any product support internationalization is by not hard-coding strings. Any text that the user maysee or have access to should not be hard-coded, and instead, be routed through a resource bundle. (More will come later here as we gain better understanding on how we plan to use resource bundles).3 Java Source FilesJava source files contain the following information: package statements, import statements, classdeclarations, variables and methods. Optionally, they may contain comments and inner classes.3.1 Package NamingIn Java, package names must be unique throughout all Java code loaded into a virtual machine. JBuilderwill not allow two packages of the same name to loaded into the editor. However, once a package isexported to JAR file the project concept does not exist; so if two packages had the same name in different projects, they could not be exported to the same JAR, or even be loaded into the same JVM.Packages are used in Java to prevent class name collisions between classes created by different developers.It is designed to allow Java code created anywhere in the world, by any company, to be loaded safely into a JVM and combined with any other Java code without concern about duplicate class names. In the JVM at runtime, all class names are fully qualified with the package name. So if there are two classes with thesame name, but in different packages, the JVM will always be able to identify the correct one.In order to prevent package name conflicts with Java code written by developers all over the world, it was necessary to use a world-wide naming system that would guarantee uniqueness of package names. Since there is already such a name system in place (the internet domain name system), Sun decided to use thatnaming system in package names. The Sun standard specifies that Java package names begin with thecompany domain name in reverse order. Package qualifiers beyond the reversed domain name may bearbitrarily defined by the owner of that domain.For example, Java packages written by IBM begin with “com.ibm”, and are followed by a package naming system developed by IBM to keep their internal Java developers from creating conflicting names within the “com.ibm” space. (Roughly, the convention is “com.ibm.<softwaredivision>.<product>.<xxx>”).In keeping with the Sun standard, all Java package names created by #### Software should begin with the qualifiers “com.####”. Subsequent qualifiers should identify t he product or common library name,followed by any qualifiers desired by the product developers. For example:com.####.<product>.<xxx>This identifies a package of Java classes developed by #### Software. It is part of the “i2k” product and “component” common library, and specifically, the DOE component.3.2 Import StatementsImport statements typically immediately follow the package declaration. Although java enables developers to import entire packages, it is recommended that developers import only the specific classes that areneeded. Exceptions to this are some of the most common packages associated with the JDK, such asjava.util, ng, java.awt, and javax.swing.An import statement looks like this:import java.util.*;import com.####.i2k.pse.SomeClass;3.3 CommentsJava has several types of comments: Documentation, C-style, single-line, End end-line. These four aredescribed below.It is recommended that all source files begin with a c-style comment that lists the class name, changeinformation, and copyright notice:/** Classname** Change Information** Copyright Notice*/Documentation comments are what the javadoc tool recognizes and is able to turn into html documentation.Any public or protected class, variable, or method should have documentation style comments associatedwith it. If we do a good job here, producing our API documentation will be easy! For more information on how to write Javadoc comments, visit http://intranet.####.com:5000/~hodgin/javadoc/howto.html (SeeJava Source File Example at the end of this document for an example).When you comment out code, document when and why the code was commented out so you or otherdevelopers will know why it was commented out.3.4 Class Guidelines and Naming ConventionsA Class should represent a single entity. There is no recommended guideline on how long a class should be,however, if a class begins to get very large, it should be closely examined to determine if it should bebroken into multiple classes.Each class should have coded explicit constructors. If no explicit constructor for a class, exists, a default(no Param) constructor is “created” for the class. The constructor will have the same visibility as the classitself. Although this behavior is acceptable at times, there are cases where this could cause problems. Itmay lead to other classes being able to instantiate the class that the developer did not intend, or may allow unintentional avoidance of a singleton paradigm. Whatever the case, it is just good programming practice to explicitly define the constructor(s) of a class.Class names should be nouns, in mixed case, with the first letter of each internal word capitalized. Keep the class names descriptive, yet simple.Inner classes are classes which are defined inside another class. Their purpose should be to serve itscontaining class only and should be private (There may be cases where the inner class should be morevisible). In general, if the inner class serves a class outside the containing class, then it should be brokenout to be a normal class. Inner classes should be defined after the containing class’ declaration and classvariables and just before the constructor(s) of the containing class (See “5 Code Examples” for an example).3.5 Method Guidelines and Naming ConventionsMethods are where the primary functionality of a class may be found. Methods encapsulate a single unit of work in a class. For this reason, they should remain short and to the point. A good rule to use when writing methods that can be easily read and understood using the “60 Second Rule.”3.5.1 The 60 Second RuleAnother programmer should be able to look at your method and be able to fully understand what it does,why it does it, and how it does it in less than 60 seconds. If they cannot, then your code is too difficult tomaintain and should be improved. S ixty seconds, that’s it. A good rule of thumb is that if a memberfunction is more than one screen of source code then it is probably too long. Note that good comments,formatting, and variable naming all contribute to quick understanding of a member function.3.5.2 Naming GuidelinesThe guidelines provided in section 2.2 What Makes a Good Name apply to methods. Beyond thoseguidelines, methods should be verbs describing the action or function they are to perform. Accessormethods, methods which provide outside access to class variables, should begin with get or set (see section4.1 Access to Instance and Class Variables for more detail on this topic). Getter functions which return aboolean value should be prefixed with is (Examples: isVisible(), isEmpty()).3.5.3 VisibilityThe visibility of a class’s member functions should be as restrictive as possible. Much like the principle of data hiding prevents external classes from having data dependencies on the internal class variables, member visibility controls the potential for functional dependencies. It is desirable to reduce the functionaldependency so that how a class performs its functions may be altered without side effects in other classes.By making methods of class A invisible to external classes, call it B, (i.e. private or protected if subclasses need to inherit it) the external class, B, cannot have dependencies on the internal operation of class A.less morevisible Private Protected Default Public visible(Friendly)3.6 Field (Variable) GuidelinesFields may be freely named within the general naming guidelines described in What Makes a Good Namein section 2.2.For example:firstNamezipCodecustomerListorderListAvoid overly long, and overly short field names. Names which are very long (greater than 15-18 characters) make it difficult to format expressions in which the field name is used. Statements which use long fieldnames tend to run off the right side of the source code window or have to be wrapped onto several physical lines of code. In either case the result is less readable source code.Also avoid names which are abbreviated for no particular reason other than to save a few keystrokes. Forexample, using “off” instead of “offset”, “len” instead of “length”, etc. Note that this rule may notapply to variables, which if they are of a limited scope, may be shortened. See in What Makes a GoodName in section 2.2.Again, it is recommended that fields which are collections be post-fixed with “List”.It is also recommended that fields be declared private or protected, and that all outside access to the classvariables be done through accessor methods.3.7 Code formatting3.7.1 IndentationIndentation is used to visually express the nesting (“block”) level of code. It allows the reader toquickly determine the code structure without examining explicit syntax details, such as where thecurly braces match up. Indentation should always be done with TAB characters rather thanspaces. JBuilder allows the user to set the n umber of spaces that a “tab” represents. Therecommended value is 4. Using the tab key to indent rather that spaces insures that users will seecode indented to their liking all the time. For example, if user A sets his tabbing to 2 spaces anduser B sets his to 4 spaces, as long as they both use the tab key to indent, each will see the otherscode indented to their own preference. However, if user A uses the space bar to indent, when userB loads in A’s code, B will see the code indented with only 2 spaces, whereas he prefers four. Thisvalue can be set in JBuilder by clicking “Tools” “Editor Options” from the menu bar. On thedialog that appears, set the “Tab Indent” property to the number of spaces you wish your tabindention to be. Again, the recommended value is 4.3.7.2 White SpaceA few blank lines, called whitespace, added to your Java code can help to make it much morereadable by breaking it up into small, easy-to-digest sections. Use a single blank line to separatelogical groups of code such as control structures, groups of assignment statements, and groups ofvariable declarations.Use 2 blank lines between methods, and between class variable declarations and the methods.3.7.3 Line LengthAvoid lines longer than 80 characters, since they’re not hand led well by many terminals andtools.Note: Examples for use in documentation should have a shorter line length—generally nomore than 70 characters.3.7.4 Wrapping LinesWhen an expression will not fit on a single line, break it according to these general principles: •Break after a comma.•Break before an operator.•Prefer higher-level breaks to lower-level breaks.•Align the new line with the beginning of the expression at the same level on the previous line.•If the above rules lead to confusing code or to code t hat’s squished up against the right margin, just indent 8 spaces instead.Here are some examples of breaking method calls:someMethod(longExpression1, longExpression2, longExpression3,longExpression4, longExpression5);var = someMethod1(longExpression1,someMethod2(longExpression2,longExpression3));Following are two examples of breaking an arithmetic expression. The first is preferred, since the break occurs outside the parenthesized expression, which is at a higher level.longName1 = longName2 * (longName3 + longName4 - longName5)+ 4 * longname6; // PREFERlongName1 = longName2 * (longName3 + longName4- longName5) + 4 * longname6; // AVOIDFollowing are two examples of indenting method declarations. The first is the conventionalcase. The second would shift the second and third lines to the far right if it used conventional indentation, so instead it indents only 8 spaces.//CONVENTIONAL INDENTATIONsomeMethod(int anArg, Object anotherArg, String yetAnotherArg,Object andStillAnother) {...}//INDENT 8 SPACES TO AVOID VERY DEEP INDENTSprivate static synchronized horkingLongMethodName(int anArg,Object anotherArg, String yetAnotherArg,Object andStillAnother) {...}Line wrapping for if statements should be done like this:if ((condition1 && condition2)|| (condition3 && condition4)||! (condition5 && condition6)) {doSomethingAboutIt();}3.7.5 Control Structure Formattingif, if-else, if else-if else StatementsThe 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;}Note:if statements always use braces {}. Avoid the following error-prone form: if (condition) //AVOID! THIS OMITS THE BRACES {}!statement;for StatementsA for statement should have the following form:for (initialization; condition; update) {statements;}while StatementsA while statement should have the following form:while (condition) {statements;}do-while StatementsA do-while statement should have the following form:do {statements;} while (condition);switch StatementsA switch statement should have the following form:.switch (condition) {case ABC:statements;/* falls through */case DEF:statements;break;case XYZ:statements;break;default:statements;break;}Every time a case falls through (doesn’t include a break statement), add a comment where the break statement would normally be. This is shown in the preceding code example with the/* falls through */ comment.Every switch statement should include a default case. The break in the default case is redundant, but it prevents a fall-through error if later another case is added.try-catch StatementsA try-catch statement should have the following form:try {statements;} catch (ExceptionClass e) {statements;}A try-catch statement may also be followed by finall y,which executes regardless of whether or not the try block has completed successfully.try {statements;} catch (ExceptionClass e) {statements;} finally {statements;}4 Programming Practices4.1 Access to Instance and Class VariablesDon’t make any instance or class variable public without good reason. Often, instance variables don’t need to be explicitly set or gotten—often that happens as a side effect of method calls.All access to instance variables from outside the class should be through getter and setter methods. Theformat for these methods is to prefix the variable name with get or set. For example:public class Foo {private int someValue = 0;...public int getSomeValue() {return someValue;}public void setSomeValue(int newValue) {someValue = newValue;}}One example of appropriate public instance variables is the case where the class is essentially a datastructure, with no behavior. In other words, if you would have used a struct instead of a class (if Java supported struct), then it’s appropriate to make the class’s instance variables public.4.2 Referring to Static Class Variables and MethodsAvoid using an object to access a class (static) variable or method. Use a class name instead. For example: classMethod(); //OKAClass.classMethod(); //OKanObject.classMethod(); //AVOID!4.3 Local VariablesA local variable is an object or data item that is defined within the scope of a block, often a memberfunction or an if/then/else code block. (The scope of a variable is the area of code in which the variable can be directly used; each variable’s scope is defined by where the variable is declared and the qualifiers such as public and private). The scope of a local variable (a variable defined in a method, as opposed to a class variable defined in the class header) is the block in which it is defined. The important codingstandards for local variables focus on:•Naming conventions•Documentation conventions•Declarations。