为什么 switch 语句上有奇怪的缩进?

为什么在 switch 语句中缺少“ case”关键字的缩进被认为是好的风格?

在几乎每个 IDE 中,“ case”关键字的缩进似乎都不是默认的格式选项:

switch (i){
case 0:
break;
case 1:
break;
}

而我发现这种格式更直观:

switch (i){
case 0:
break;
case 1:
break;
}

这背后有什么逻辑,让我不明白吗?

29554 次浏览

The 1999 official Oracle Code Conventions for the Java TM Programming Language (section 7.8) recommends a switch style where case statements are not indented relative to the switch statement as a whole.

This is a subjective choice, but Sun decided it is better if everyone stick to one style, and picked this.

The cases are logically labels. Many people put labels at the same indentation level as the block they are in. In my opinion, that way it's easier to read through the text.

I compare it with a timeline you can scroll through. You have markers on the time line itself, not indented into the content. You can then quickly point out where labels/markers are, without moving your eye away from the base-line.

There are different indentation styles to choose from. AFAIK, none is considered better style than the others as long as you consistently use an indentation style at all. For me, indenting case labels is more readable, same goes for private, protected and public labels in classes, however, my IDE won't do the indentation my way. My code isn't as readable as I'd like it to be this way. Oh well...

Maybe it is to keep the same indentation level as its logical equivalent expressed in if statments? That is:

switch(i){
case 0:
//do something 1
case 1:
//do something 2
}

Would look similar to its logical equivalent:

if(i==0){
//do something 1
}else if(i==1){
//do something 2
}

In 4 words: no blocks, no indentation.

Cases are not opening a block. In C or C++ you can even put variables declarations (but the initializers are not called, except for static variables, that's a pitfall) at the beginning of the switch block. You can do many weird things with switch, like Duff's device.

Hence, as cases are just labels, indenting them does not seem that intuitive, and not indenting is the style chosen by most styles.

FWIW, another option is using two half-indents:

switch (i) {
case 1:
...
case n:
...
}