Java代码可理解性/可读性及编码规范

目录

0、写在前面

本文是软件构造系列文章Chapter4的总结,主要关注代码的可理解性/可读性,以及编码规范。

1、可理解性的标准(alias:可读性)
1.1、Code quality measurement:WTFs/min


(一群人在屋子里做code review, 传来WTF……)

1.2、Metrics
WTFs/minute让评论代码的人有更少的疑问和抱怨
Length of names标识符(类名、变量名、方法名等)的长度(度量方式:所有标识符的平均长度)
Name Uniqueness Ratio(UNIQ)命名独特性比例
Complexity and LoC代码复杂度和代码行数
Comment density(MCOMM%)注释的密度(百分比)
1.3、How to do in writing understable code?

Many many considerations:
– Naming conventions (consisting naming scheme) 命名规范
– Limit line length and file length 代码行的最大长度、文件的最大LoC
– Enough necessary comments 注释
– Code format such as Consistent Indentation, White space before and after names and operators, Code alignment, Separating blocks of code with space lines between them, etc 代码的布局:缩进、空行、对其、分块、等
– Avoid deep nesting (simple structural complexity) 避免多层嵌套—增加复杂度
– File and folder organization 文件和包的组织

经验:代码的可读性/可理解性很多时候比效率/性能更重要,不可读不可理解代码可能蕴含更多的错误。
先写出可读易懂的代码,再去逐渐调优!

2、代码中的注释文档
2.1、Four places of use commentary

①Title comments(Documentation Comments)
介绍类的定义,重要的方法,宏定义(macro definitions),版权声明(copy right)

/**
* The Example class provides ...
*/
public class Example { ...

②Introductory comments
阐述类、方法、模块的目的

/**
* purpose and usage of  a class
* 
* @param parameter
* @return  result
* @throws exception
*/

③Block comments

/*
* Here is a block comment.
*/

④Single-Line / Trailing / End-Of-Line comments

if (a == 2) {
return TRUE; /* special case */
} else {
return isPrime(a); /* works only for odd a */
2.2、Special comments for design

– Specifications: pre-condition and post-condition (Lecture 2-2)
Rep Invariants (RI) (Lecture 2-3)
Abstract Function (AF) (Lecture 2-3)
Safety from Rep Exposure (Lecture 2-3)
Testing Strategy (Lecture 7-5)
– How to ensure thread-safe (Lecture 10-1)

3、伪代码(Pseudo-code)

用伪代码表达某个模块/算法的内部处理逻辑/流程

3.1、Six Basic Computer Operations
  1. Receive information from outside(从外部获取信息): ReadGet
  2. Put out information to outside(打印外部信息): PrintWriteOutputDisplay, etc
  3. Perform arithmetic/computation(算法、计算): ComputeCalculate
  4. Assign value to a variable or memory location(赋值): SetSaveStore
  5. Compare and select alternate actions(比较、选择): If-Then-Else
  6. Repeat a group of actions(循环):ForWhileDo/Until
4、编码规范
4.1、– Naming

Use Intention-Revealing Names(名字意图明确)
Example:
methodsAreNamedWithCamelCaseLikeThis(方法名小写字母开头)
variablesAreAlsoCamelCase(变量名小写字母开头)
CONSTANTS_ARE_IN_ALL_CAPS_WITH_UNDERSCORES(常量全都大写,以下横线分割)
ClassesAreCapitalized(类名以大写字母开头,大写字母分割)
packages.are.lowercase.and.separated.by.dots(包名小写,”.”分割)

4.2、– Vertical formatting by blank lines(使用空白行垂直格式化)

①Length Limits(长度限制)
 Limit the Number of Java Statements per Line to 1
– Multiple statement can hide code to the casual observer
– Makes stepping through code difficult
– Long lines cannot be handled well by many terminals and tools.
 Limit the Length of Methods(方法的长度限制:大约30行)
– A method should be about a “page of code”
– Around 30 lines of code
 Limit the Length of SourceFiles: in Java, file size is closelyrelated to class size.(每个源文件:通常200行,上限500行,文件越小越容易理解)
– Typically 200 lines long, with an upper limit of 500
– Small files are easier to understand

②Use Blank Lines to Organize Code(使用空白行组织代码)
– Single blank lines(单空格行)
• Between local variable declarations and the first code in a method(局部变量的声明和一个方法的第一行代码之间)
• Before a block comment(注释块之前)
• Between logical sections of code to improve readability(代码逻辑行之间)
– Double blank lines(双空格行)
• Between methods(方法之间)
• Between class and interface definitions(类和接口的定义)
• Between any other sections of a source file(源文件的每一节)

4.3、– Horizontal Formatting: White Spacing, Indentation, Line Wrapping(使用空格、缩进水平格式化)

The old Hollerith limit of 80 is a bit arbitrary(每行宽为80个字母)

 Use horizontal white space(使用空格)
– Before and after the assignment operators(在操作符号的前后使用空格)
– Between the function names and the opening parenthesis(方法名和”{“之间使用空格)

 Code must be indented according to its nesting level(缩进)
– The body of a function must be indented with respect to its header(方法本身和方法头要具有相对缩进)
– the body of a for, while, or switch statement must be indented with respect to its first line, and similarly for if statements and other nested structures. (for、while、switch主体要有相对缩进)

 Wrapping Lines(换行)
– 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.(将新行与上一行中相同级别的表达式的开头对齐)

4.4、– File/Package organization(包文件的组织)

①引用的库函数的顺序
 Orders:
– 1. Standard packages (java.io, java.util, etc.)(标准库函数、包)
– 2.Third party packages such as com.ibm.xml.parser(第三方包)
– 3. Your own packages(自己定义的包)
 Within each group order the packages in alphabetic order(上述每一部分的顺序按字母表顺序排列)

②每个类内部顺序
Ordering of Class Parts
 1. Javadoc comments(java文档注释)
 2. Class declaration statement(类声明语句)
 3. Class-wide comments(类内部注释)
 4. Class static variable declarations (public, protected, package,private)(类静态变量声明)
 5. Class instance variable declarations (public, protected, package,private)(类实例变量声明)
 6. Methods declarations(方法声明)
– Constructors first(首先是构造函数)
– Functional or alphabetical ordering(剩下的方法按功能或字母排序)

③包结构顺序
Create a package of classes and interfaces
project / src / com / mycompany / myproject / MyClass.java

4.5、– Automatic Code Formatting in IDE

IDE自动代码格式化(eg. Eclipse格式化快捷键 是 Ctrl + Shift + F,绝大多数IDE的格式化快捷键都与”F”有关)

4.6、– Following a standard coding styles/conventions

遵循标准代码风格 eg. Oracle’s Java code convertions(收购了sun公司) 或者 Google’s Java style guide

4.7、– Using CheckStyle

使用CheckStyle

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值