Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why the strange indentation on switch statements?

Tags:

java

c

syntax

Why is the imho missing indentation of the "case" - keywords in a switch statement considered good style?

No indentation of the "case" keyword seems to be the default formatting option in about every IDE:

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

while I find this format more intuitive:

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

Is there some logic behind this, that eludes me?

like image 358
fasseg Avatar asked Dec 22 '10 12:12

fasseg


People also ask

Why you should not use switch statements?

Last but not least, because a switch statement requires us to modify a lot of classes, it violates the Open-Closed Principle from the SOLID principles. To conclude, switch statement are bad because they are error-prone and they are not maintainable.

Are switch statements evil?

Switch case is not a bad syntax, but its usage in some cases categorizes it under code smell. It is considered a smell, if it is being used in OOPS. Thus, Switch case should be used very carefully.

Why break is optional in switch statement?

A break statement is optional. If we omit the break, execution will continue on into the next case. It is sometimes desirable to have multiple cases without break statements between them.

Does indentation affect code?

Indentation refers to the spaces at the beginning of a code line. Where in other programming languages the indentation in code is for readability only, the indentation in Python is very important. Python uses indentation to indicate a block of code.


2 Answers

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.

like image 117
Johannes Schaub - litb Avatar answered Oct 05 '22 23:10

Johannes Schaub - litb


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.

like image 40
kriss Avatar answered Oct 06 '22 01:10

kriss