AdSense

網頁

2019/4/18

Java 縮排(Indentation)該用Tab 2格空白 還是 4格空白?

Java程式縮排該用Tab,2格空白還是4格空白?

Java程式縮排建議用4格空白(white space)。

請參考Code Conventions for the Java TM Programming Language - Revised April 20, 1999 - 4 - Indentation

Four spaces should be used as the unit of indentation. The exact construction of the indentation (spaces vs. tabs) is unspecified. Tabs must be set exactly every 8 spaces (not 4).


OpenJDK Java Style Guidelines規定用4格空白,不要用tab。

Indentation level is four spaces.

Only space characters may be used for indentation. No tabs.


不過Google的Java Style Guild - Block indentation: +2 spaces卻是2格空白。

Each time a new block or block-like construct is opened, the indent increases by two spaces. When the block ends, the indent returns to the previous indent level. The indent level applies to both code and comments throughout the block.


所以看來2格或4格都可以。我之前也都是用2格,但最近又覺得4格縮排比較明顯。總之只要和團隊成員統一風格就好,或是用IDE如Eclipse的Code Fomatter整理來保持一致。

通常用2格的人多是說用4格很快就讓程式太長(太深),例如幾個if else或for迴圈block程式碼就會縮到很右邊。

2格縮排

if (...) {
  if (...) {
    for(...) {
      if (...) {
        
      }
    }
  }
} 

4格縮排

if (...) {
    if (...) {
        for(...) {
            if (...) {
            
            }
        }
    }
} 

但我的想法是如果程式碼縮到很右邊代表程式可能需要重構,而不是用較少的兩格縮排來解決,因為程式碼太長意味著這段程式碼有三個以上的巢狀if else或for迴圈,程式很難讀得懂。

不過本篇僅討論Java的縮排,如果是寫JavaScript的話我依舊會遵照2格縮排的慣例。


沒有留言:

AdSense