Note of CLEAN CODE chapter 5 - Formatting

Purpose

The functionality you create today has a good chance of in he next release, but he readibility of your code will have a profound effect on all the changes that will ever made.

The coding stype and readability set precedents that continue to affect maintanability and extensibiility long after the original code has been changed beyond recognition

Vertical Rules

Small files are usually easier to understand than large files are.

Newspaper Formatting

The name by itself should be sufficient to tell us whether we are in the right module or not.

A newspaper is compose of many articles, most of which are ver small, and some are a bit larger. Few contain as much text as a page can hold. This makes the newspaper usable.

Vertical Openness Between Concept

You can add some spaces(openness) to make it has a remarkably clear effect on readability of the code

public class Bold extends Parent{
    public static final String regex = "'''.+?'''";
    private static final Pattern pattern = Pattern.compile("'''.+?'''",
        Pattern.MULTILINE
    );
    public Bold(Parent parent, String text){
        super(parent);
        Matcher match = pattern.matcher(text);
        match.find();
        ....
    }
    public String render(){
        StringBuffer html = new StringBuffer("<b>")
        html.append(childHtml())
            .append("<b>");
        return html.toString();
    }
}
public class Bold extends Parent{
    public static final String regex = "'''.+?'''";
    private static final Pattern pattern = Pattern.compile("'''.+?'''",
        Pattern.MULTILINE
    );
 
 
    public Bold(Parent parent, String text){
        super(parent);
        Matcher match = pattern.matcher(text);
        match.find();
        ....
    }
 
 
    public String render(){
        StringBuffer html = new StringBuffer("<b>")
        html.append(childHtml())
            .append("<b>");
        return html.toString();
    }
}

Vertical Density

Openness separates concepts, and density implies close association;

public class report{
    private String className;
    /**
     * The properties of the reporter listener
     */
    private List<Property> properties = new ArrayList<>();
}

The comment is useless, breaking the close association of two instance variable. Just make them Closer to increase the vertical density.

public class report{
    private String className;
    private List<Property> properties = new ArrayList<>();
}

Vertical Distance

Variable Declarations

variable should be declare as colse to their usage as possible

int function(){
+   vector<int> v(100);
    for(int i = 0; i < 100; ++i){
        std::cin >> v[i];
    }
}

Controller variable for loops should usually be declared within the loop statements

    int cnt = 0;
+   for(Test test : tests){
        count += test.getCount();
        ...
        ...
    }


// another example

    for(Test test: suite.getTests()){
+       TestRunner tr = new TestRunner();
        ...
        ...
    }

Instance Variables

They should be declared at the bottom or the top of a block (At least a well-known place). You don’t have to follow the so-called scissors rule, convection. Don’t put them in the middle of a block

Dependent Function

If one function calls another, they should vertically close, giving the program a natural flow, and the caller should be above callees

void a(){
    b();
    c();
    if(page == null){
        d();
    }else{
        e();
    }
}

void b(){}
void c(){}
void d(){}
void e(){}

Conceptual Affinity

Like the overloadded functions or similar functions

void assertTrue(String msg, boolean b){
    if(!b)
        fail(msg);
}

void assertTrue(boolean b){
    assertTrue(null, b);
}

void assertFalse(String msg, boolean b){
    assertTrue(msg, !b);
}

Vertical Ordering

We expect most important concepts to come first, and be expressed with the least amount of polluting detail. Low-level deitals should come last, allowing us to skim the source files to get the gist from first few functions.

Horizontal Formatting

Programmers clearly prefer short lines;(70% lines are less than 60 characters).

We should strive to keep our lines short.
The author follows the rule that never scroll to the right under the circunstance that the screen can contain about 120 words.

Horizontal Openness Between Concept

Assignment operations have two distinct and major elemtns: left side and right side.
White spaces make that separation obvious

int lineSize = line.length()

But author does not put spaces between function names and open parenthesis

determinant(10, 20);

You can use it to show precedent of operations

return b*b - 4*a*c;

return (-b + Math.sqrt(determinant(a, b, c))) / 2*a;

Horizontal Alignment

Lining up all variables names in a set of declarations or the rvalues in a set of assignment statements are not so useful

private     Socket      socket;
private     InputStream input;


this.context =              context;
requestParsingTimeLimit =   1000;

Alinment seems to emphasize the wrong things and leads eyes away from the true intent.
You will focus of the variables names and ignore their types, and you will look down the list of rvalues without seeing the assignment operations.

And if you have a long length class to be aligned, the class should be splitted up

Indentation

With indents spaces and carrige returns, your eyes can rapidly discern the structure of the indented file.
Use it frequently, so you can instantly spot the variables, constructors, accessors and the methods. It takes just a few seconds to realize what does the function do.

Breaking Indentation

For short if or while statements, they might break the rule, the author always goes back and put the indentation back in

if(a == 0){break;}
if(a == 0){
    break;
}

Dummy Scopes

Make sure the semicolon is visible

while(dis.read(buf, 0, readBuffer) != -1);
while(dis.read(buf, 0, readBuffer) != -1)
    ;

Team Rules

The last thing we want to do is add more complexty to the source code by writting it in a jumble of different individual styles.

So make an team agreement and follow them.

  • 13
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值