Nice programing

Java 스위치 케이스 : 중괄호가 있거나 없는가?

nicepro 2020. 10. 7. 08:18
반응형

Java 스위치 케이스 : 중괄호가 있거나 없는가?


중괄호가있는 다음 두 스 니펫을 고려하십시오.

switch (var) {
  case FOO: {
    x = x + 1;
    break;
  }

  case BAR: {
    y = y + 1;
    break;
  }
}

중괄호 없음 :

switch (var) {
  case FOO:
    x = x + 1;
    break;

  case BAR:
    y = y + 1;
    break;
}

중괄호가있는 스 니펫에서 각 케이스를 중괄호로 묶어 새 범위가 생성된다는 것을 알고 있습니다. 그러나 각 케이스에 새 범위가 필요하지 않은 경우 (즉, 변수 이름이 재사용되지 않음) 케이스와 함께 중괄호를 사용하면 성능이 저하됩니까?


케이스에 중괄호를 사용하면 성능이 저하됩니까?

없음.

중괄호는 컴파일러가 변수, 조건, 함수 선언 등의 범위를 파악하는 데 도움이됩니다. 코드가 실행 파일로 컴파일되면 런타임 성능에 영향을주지 않습니다.


실행 관점에서 성능 저하가 없습니다.

파싱 ​​할 것이 더 많기 때문에 컴파일 관점에서 약간의 성능 저하가 있지만 실제로 우려되는 사람이 있다면 코드를 한 줄에 모두 작성해야합니다. :-)

그리고 이제 우리 게시물의 의견 부분에 대해 ... 저는 항상 {및}를 입력했습니다. 유지 관리에 대한 패널티가 있기 때문에 나중에 입력해야 할 가능성이 높고이를 두는 것이 고통 스러울 수 있습니다. 나중에 ...하지만 그것은 103 % 개인 선호도입니다.


우리가 알고 있듯이 스위치 케이스에 대한 중괄호가 필요하지 않습니다. 중괄호 케이스를 사용하면 케이스 범위에 대해 혼동을 일으킬 수 있습니다.

여는 중괄호는 일반적으로 함수의 시작, 루프의 시작, 클래스 선언의 시작 또는 배열 초기화의 시작 등과 같은 의미있는 것과 관련이 있습니다 ... 우리는 케이스가 브레이크를 만났을 때 스위치 블록을 벗어나는 것을 알고 있습니다. 성명서. 따라서 중괄호를 사용하는 것은 무지한 독자에게 케이스에 대한 다른 범위의 아이디어를 암시하는 것처럼 보입니다. 따라서 프로그래밍 가독성을 높이기 위해 중괄호를 사용하지 않는 것이 좋습니다.

즉, 내가 뭔가를 가질 때,

switch(i)
{
  case 1 :
  {
     //do something
  }
  System.out.println("Hello from 1");

  case 2: 
  ....
}

"Hello from 1"이 인쇄됩니다. 그러나 중괄호를 사용하면 대소 문자가 '}'로 끝나는 무지한 독자를 암시 할 수 있으며 루프, 메서드 등의 경우 중괄호가 일반적으로 무엇을 의미하는지 이미 알고 있습니다.

Like we have jump-to-label statements in 'C' the control just shifts to case and continues it's execution. So, with that understanding it's just a BAD practice to use curly braces when writing cases for switch.

Technically speaking you can surround any block of your code with an additional pair of curly braces when used with valid syntax. Using braces in switch looks so bad at least to me as it seems to give a different feel like I have said above.

My suggestion : Just avoid using surrounding braces for switch cases.


With braces.

There are so many things that can go wrong with switch statements I try to avoid them where I can, i.e.

  1. Forgetting breaks and thus having case fall-throughs
  2. Forgetting a default case and thus not catching an un-catered for condition
  3. Accidentally reusing variables between case statements, or worse yet, affecting a variable which IS sharing a variable between case statements.

Using braces is one way to prevent both intentional and accidental sharing of variables between case statements


This question is probably going to be closed as "argumentative" (BRACE WAR!) but what the heck. I actually like the braces after the cases. To me it makes the ugly switch syntax look more like the rest of the language constructs. (There is no penalty for using braces in this "case")


You say the braces can be omitted because no variables names are being reused. By reusing variable names, I assume you mean declaring a new variable of the same type.

The braces are actually most useful to ensure you don't end up reusing the same variable in different cases by mistake. They don't declare any variables today, but someone will add them tomorrow and without the braces the code is error-prone.


I wouldn't use braces for switch cases.

  • The switch statement looks baroque enough already without braces.

  • Switch cases should be very short. When you need to declare variables it is a sign that you are doing it wrong.

Now off to maintaining some legacy C code which sports switch cases of 500+ lines ...


I've never thought about it before. Never needed the braces in a case clause so can't really see why you would need them. Personally I don't go for the "It'll be easier to maintain" idea, that's just rubbish, it'll be easier to maintain if the code makes sense and is documented.

No braces ... less syntax is more

참고URL : https://stackoverflow.com/questions/633497/java-switch-cases-with-or-without-braces

반응형