Formatting這篇是在介紹code內部得命名和寫法風格
介紹如下
Formatting 內容格式
Braces 大括號
if, else, for, do ,while, try都要用{}換行
Nonempty blocks: K & R style 非空白區塊
除了else, catch和','外, 都在 { 前不換行, { 後與 } 後換行
ex:
try {
something();
} catch (ProblemException e) {
recover();
}
Empty blocks: may be concise 空白區塊
內容區塊為空時直接寫{}, 中間不需要空白或換行
除非是有固定格式的if/else-if/else或try/catch/finally
Block indentation: +2 spaces 縮排
兩個空白
One statement per line 每行一個敘述
Column limit: 80 or 100 每行80或100個字
Line-wrapping 單行超過限制就換行
Where to break 哪時斷行
斷在等號 = 前
( 與 , 會留在同行
Indent continuation lines at least +4 spaces 縮排最少4個空白
一個階層是1組空白
Vertical whitespace 垂直空白
不同類型的區塊會使用
Horizontal whitespace 水平空白
用在隔開保留字與區塊, 變數,後
Horizontal alignment: never required 水平對齊(不要求)
用來對齊上下敘述而使用
Grouping parentheses: recommended 用小括號
通常用在運算式中
Specific constructs 特定結構
Enum classes 列舉類別
可和陣列一樣初始話, 其中','要跟著enum constant, 不一定要換行
Variable declarations 變數宣告
一行宣告一個變數, 需要初始值時也寫在同一行
Arrays 陣列
給值時只要為區塊結構就可以, 內文分行不限
使用String[] args, 不用String args[].
因為[]是資料類型而不是變數的內容
Switch statements 敘述區塊
內容空兩格, 並且一定要有default
Annotations 標註
一行一個, Annotation不會因會換行而增加縮排層級
ex:
@Override
@Nullable
public String getNameIfPresent() { ... }
只有一個時可放在第一行
ex:
@Override public int hashCode() { ... }
當後面無參數時, 可以多個放在同一行
ex:
@Partial @Mock DataLoader loader;
Comments 註解
Block comment style 區塊註解
最前面需要有 * 並對齊, 或是用多個//
ex:
/*
* This is // And so /* Or you can
* okay. // is this. * even do this. */
*/
當想要在換行時自動格式化則選用/* ... */
Modifiers 修飾字
按照java定的順序
public protected private abstract static final transient volatile synchronized native strictfp
Numeric Literals 數值
最後面加上大寫避免混淆
ex: 3000L 而不是 3000l
1. 官網 https://google.github.io/styleguide/javaguide.html#s4-formatting
留言列表