Vikot106's Blog.

笔记:代码风格统一记录

字数统计: 598阅读时长: 3 min
2018/12/08 Share

最后一次更新时间:2019-3-21

Google C++编写规范

snap

K&R风格

​ 代码风格最早出现的,也较为传统的是K&R风格。所谓K&R即指《The C Programming Language》一书的作者Kernighan和Ritchie二人,这是世界上第一本介绍C语言的书,而K&R风格即指他们在该书中书写代码所使用的风格。K&R风格在处理大括号时,使用了一种较为紧凑的格式,将左括号留在前一行的末尾,尽可能地压缩了空间。

驼峰命名法

​ 骆驼式命名法就是当变量名或函数名是由一个或多个单词连结在一起,而构成的唯一识别字时**,第一个单词以小写字母开始;从第二个单**词开始以后的每个单词**的首字母都采用大写字母,**例如:myFirstName、myLastName。

代码示例

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
/*
* This is a sample file.
*/

public class ThisIsASampleClass extends C1 implements I1, I2, I3, I4, I5 {
private int f1 = 1;
private String field2 = "";

public void foo1(int i1, int i2, int i3, int i4, int i5, int i6, int i7) {
}

public static void longerMethod() throws Exception1, Exception2, Exception3 {
// todo something
int i = 0;
int[] a = new int[]{1, 2, 0x0052, 0x0053, 0x0054};
int[] empty = new int[]{};
int var1 = 1;
int var2 = 2;
foo1(0x0051, 0x0052, 0x0053, 0x0054, 0x0055, 0x0056, 0x0057);
int x = (3 + 4 + 5 + 6) * (7 + 8 + 9 + 10) * (11 + 12 + 13 + 14 + 0xFFFFFFFF);
String s1, s2, s3;
s1 = s2 = s3 = "012345678901456";
assert i + j + k + l + n + m <= 2 : "assert description";
int y = 2 > 3 ? 7 + 8 + 9 : 11 + 12 + 13;
super.getFoo().foo().getBar().bar();

label:
if (2 < 3) {
return;
} else if (2 > 3) return;
else return;
for (int i = 0; i < 0xFFFFFF; i += 2)
System.out.println(i);
while (x < 50000) x++;
do x++; while (x < 10000);
switch (a) {
case 0:
case 1:
doCase0();
break;
case 2:
case 3:
return;
default:
doDefault();
}
try (MyResource r1 = getResource(); MyResource r2 = null) {
doSomething();
} catch (Exception e) {
processException(e);
} finally {
processFinally();
}
do {
x--;
} while (x > 10);
try (MyResource r1 = getResource();
MyResource r2 = null) {
doSomething();
}
Runnable r = () -> {
};
}

public static void test()
throws Exception {
foo.foo().bar("arg1",
"arg2");
new Object() {
};
}

class TestInnerClass {
}

interface TestInnerInterface {
}
}

enum Breed {
Dalmatian(), Labrador(), Dachshund()
}

@Annotation1
@Annotation2
@Annotation3(param1 = "value1", param2 = "value2")
@Annotation4
class Foo {
@Annotation1
@Annotation3(param1 = "value1", param2 = "value2")
public static void foo() {
}

@Annotation1
@Annotation3(param1 = "value1", param2 = "value2")
public static int myFoo;

public void method(@Annotation1 @Annotation3(param1 = "value1", param2 = "value2") final int param) {
@Annotation1 @Annotation3(param1 = "value1", param2 = "value2") final int localVariable;
}
}
CATALOG
  1. 1. Google C++编写规范
  2. 2. K&R风格
  3. 3. 驼峰命名法
  4. 4. 代码示例