开发者

What is the preferred way to indent cases in a switch? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. Closed 9 years ago.

As I was writing another switch in Eclipse, I once again came across a rather weird (to me, at least) default indentation, which is applied to 'switch' statements:

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

I tend to prefer another way:

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

Which way is more readable and eye-pleasing for you? I'm still not hundred percent determined what's best for me, so I'd like to stick to what's best for other people who would read my code.

BTW, you're free to close开发者_如何学JAVA this question if this is too subjective. :)


According to the "official" Java Code Conventions, it's the first variant (no additional indentation for case).


I prefer the second way as well. But it is more important to stay consistent within a particular application and/or within a particular team than it is to indent one way or the other.


I tend to indent all control structure bodies a single (4space) tab like so:

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

I consider the switch to be the outer control structure and the case directives part of the body(even though they are part of the control structure).

I would then further tab indent each case like so:

switch (i) 
{
    case 1:
        do_something();
    case n:
        do_something_else();
}

I find this to be the most readable format for the switch case construct.

As jkohlhepp has mentioned conformity to the code style conventions of the project you are working on is the most important thing, if you are working on a project that has none, it is worth developing some.


The first is the standard switch case indentation.

switch (i) {

case 1:
    .... // Here you can write more code in a row than using the second way
    break;
case n:
    ....
    break;
default:
    ....
    break;
}

Notice the new inserted line between switch (i) and case 1:


I use second way:

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


The first method makes logical sense (to me), however I also prefer the second method. I think most of us are conditioned to expect that code inside braces will be indented.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜