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?
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.
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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With