Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Style of switch statements with curly brackets #15

Open
shawnkoh opened this issue Aug 23, 2019 · 1 comment
Open

Style of switch statements with curly brackets #15

shawnkoh opened this issue Aug 23, 2019 · 1 comment

Comments

@shawnkoh
Copy link

Hi Prof,
I understand from the style guide that switch statements should look like this.

String test = "abc";
switch (test) {
case "abc":
    # doStuff
    break;
case "bcd":
    # doOtherStuff
    break;
default:
    throw new Exception();
}

May I know what the style should be when the switch statement uses scopes in their cases.
Should it be like this?

String test = "abc";
switch (test) {
case "abc": {
    # doStuff
    break;
}
case "bcd": {
    # doOtherStuff
    break;
}
default: {
    throw new Exception();
}
}

The rationale for having curly brackets in switch statements is to provide a scope for the case's variables.
Consider this scenario:
It will fail to compile because the variable foo is being declared twice.

switch (test) {
case "abc":
    String foo = "bar";
    break;
case "bcd":
    String foo = "baz";
    break;
}
@damithc
Copy link
Collaborator

damithc commented Aug 23, 2019

May I know what the style should be when the switch statement uses scopes in their cases.
Should it be like this?

String test = "abc";
switch (test) {
case "abc": {
    # doStuff
    break;
}
case "bcd": {
    # doOtherStuff
    break;
}
default: {
    throw new Exception();
}
}

Yes, I supposed so, if one follows the current coding standard. Yes, it does look ugly. It's rare to use braces within a switch statement. In the rare case braces are used, one can deviate from the standard with an explanation for the deviation.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants