Nice programing

Java에서 중괄호를 생략해도 괜찮습니까?

nicepro 2020. 10. 20. 08:11
반응형

Java에서 중괄호를 생략해도 괜찮습니까?


나는 이것을 찾았지만 답을 찾을 수 없었고, 어떤 이유로 든 교수에게 물어보기에는 너무 부끄러웠다. 수백명의 사람들이 당신을 응시하는 그 느낌 때문에 ...

어쨌든 내 질문은 대괄호를 갖는 것의 중요성이 무엇입니까? 생략해도 괜찮습니까? 예:

for (int i = 0; i < size; i++)  {
   a += b;
}

vs

for (int i = 0; i < size; i++)
   a += b;

둘 다 작동한다는 것을 알고 있지만 대괄호를 생략하면 (가시성 때문에 많이하는 경향이 있음) 아무것도 변경되지 않습니까? 내가 말했듯이 작동한다는 것을 알고 수십 번 테스트했지만 이제 일부 유니 할당이 커지고 있으며 어떤 이유로 장기적으로 이것이 내 문제가 될 것이라는 비합리적인 두려움이 있습니다. 그것을 두려워 할 이유가 있습니까?


코드의 유지 관리 가능성을 제외하고아무것도 변경하지 않습니다 . 다음과 같은 코드를 보았습니다.

for (int i = 0; i < size; i++)
   a += b;
   System.out.println("foo");

이는 다음을 의미합니다.

for (int i = 0; i < size; i++)
   a += b;
System.out.println("foo");

...하지만 어떤 것이 었어 했습니까?

for (int i = 0; i < size; i++) {
   a += b;
   System.out.println("foo");
}

개인적으로 코드를 읽거나 수정할 때 혼동 가능성을 줄이기 위해 항상 대괄호를 포함합니다.

내가 일한 모든 회사의 코딩 규칙은 이것이 필요했습니다. 다른 회사가 다른 규칙을 가지고 있지 않다는 것은 아닙니다 ...

그리고 그것이 결코 차이를 만들지 않을 것이라고 생각하는 경우를 대비하여 : 위의 코드와 거의 동일한 버그를 한 번 수정해야했습니다. 발견하기가 매우 어려웠습니다 ... (확실히 이것은 몇 년 전, 단위 테스트를 시작하기 전이었습니다. 의심 할 여지없이 진단을 더 쉽게 만들었습니다).


중괄호를 사용하면 코드를보다 쉽게 ​​유지 관리하고 이해할 수 있습니다. 따라서 기본적으로 이를 고려해야합니다 .

코드를 더 간결하게 만들기 위해 가드 절중괄호를 사용 하지 않는 경우가 있습니다. 이에 대한 내 요구 사항은 또는 같은 점프if이 뒤에 오는 문이라는 입니다. 또한 관용구에주의를 끌기 위해 같은 줄에 두었습니다.returnthrow

if (!isActive()) return;

루프 내부의 코드에도 적용됩니다.

for (...) {
  if (shouldSkip()) continue;
  ...
}

그리고 메서드 본문의 맨 위에있을 필요는없는 메서드에서 다른 점프 조건으로.

일부 언어 (예 : Perl 또는 Ruby)에는 중괄호가 적용되지 않는 일종의 조건문이 있습니다.

return if (!isActive());
// or, more interestingly
return unless (isActive());

방금 설명한 것과 동일 하다고 생각 하지만 언어에 의해 명시 적으로 지원됩니다.


다른 점이 없다. 두 번째 버전의 주요 문제점은 다음과 같이 작성하게 될 수 있다는 것입니다.

for (...) 
  do_something();
  do_something_else();

해당 메서드를 업데이트 할 때 do_something_else()루프 내부에서 호출 된다고 생각합니다 . (그리고 머리를 긁는 디버그 세션으로 이어집니다.)

중괄호 버전에없는 두 번째 문제가 있으며 발견하기가 더 어려울 수 있습니다.

for (int i=0; i<3; i++);
  System.out.println("Why on earth does this print just once?");

따라서 합당한 이유가없는 한 중괄호를 유지하십시오. 몇 번만 더 입력하면됩니다.


자동 서식을 사용하는 경우에도 중괄호를 푸는 것이 좋다고 생각합니다. 들여 쓰기가 항상 정확하기 때문에 그런 식으로 오류를 쉽게 발견 할 수 있기 때문입니다.

전체 언어가 그 아이디어를 기반으로하고 꽤 인기가 있기 때문에 중괄호를 빼는 것은 나쁘고, 이상하거나 읽을 수 없다고 말하는 것은 잘못된 것입니다.

하지만 포맷터를 사용하지 않으면 위험 할 수 있습니다.


대부분의 경우 지금까지 언급 한 답변이 정확합니다. 그러나 사물의 보안 관점에서 볼 때 몇 가지 단점이 있습니다. 결제 팀에서 일해온 보안은 그러한 결정을 내리는 훨씬 더 강력한 요소입니다. 다음 코드가 있다고 가정 해 보겠습니다.

if( "Prod".equals(stage) )
  callBankFunction ( creditCardInput )
else
  callMockBankFunction ( creditCardInput )

이제 내부 문제로 인해이 코드가 작동하지 않는다고 가정 해 보겠습니다. 입력을 확인하고 싶습니다. 따라서 다음과 같이 변경합니다.

if( "Prod".equals(stage) )
  callBankFunction ( creditCardInput )
else
  callMockBankFunction ( creditCardInput )
  Logger.log( creditCardInput )

문제를 수정하고이 코드를 배포한다고 가정 해 보겠습니다 (그리고 리뷰어가 'Prod'조건에 포함되지 않기 때문에 문제가되지 않는다고 생각합니다). 마술처럼 생산 로그는 이제 로그를 볼 수있는 모든 직원이 볼 수있는 고객 신용 카드 정보를 인쇄합니다. 하나님은 그들 중 누군가가 (악의적 인 의도로)이 데이터를 보유하는 것을 금지합니다.

Thus not giving a brace and a little careless coding can often lead to breach of secure information. It is also classified as a vulnerability in JAVA by CERT - Software Engineering Institure, CMU.


If you have a single statement you can omit the brackets, for more that one statements brackets is necessary for declaring a block of code.

When you use brackets you are declaring a block of code :

{

//Block of code
}

The brackets should be used also with only one statement when you are in a situation of nested statement for improve readability, so for example :

for( ; ; )
  if(a == b) 
    doSomething()

it is more readable written with brackets also if not necessary :

for( ; ; ) {
  if(a == b) {
    doSomething()
   }
}

If you use brackets your code is more readable. And if you need to add some operator in same block you can avoid possible errors


Using the brackets future proofs the code against later modifications. I've seen cases where brackets were omitted and someone later added some code and didn't put the brackets in at that time. The result was that the code they added didn't go inside the section they thought it did. So I think the answer is that its good practice in light of future changes to the code. I've seen software groups adopt that as a standard, i.e. always requiring brackets even with single line blocks for that reason.


More support for the "always braces" group from me. If you omit braces for single-statement loops/branches, put the statement on the same line as the control-statement,

if (condition) doSomething();
for(int i = 0; i < arr.length; ++i) arr[i] += b;

that way it's harder to forget inserting braces when the body is expanded. Still, use curlies anyway.


Result wise , it is the same thing.

Only two things to consider.

- Code Maintainability
- Loosely coupled code. (may execute something else. because you haven't specified the scope for the loop. )

Note: In my observation, if it is loop with in a loop. Inner Loop without braces is also safe. Result will not vary.


If you have only one statement inside the loop it is same.

For example see the following code:

for(int i=0;i<4;i++)
            System.out.println("shiva");

we have only one statement in above code. so no issue

for(int i=0;i<4;i++)
            System.out.println("shiva");
            System.out.println("End");

Here we are having two statements but only first statement comes into inside the loop but not the second statement.

If you have multiple statements under single loop you must use braces.


If you remove braces, it will only read the first line of instruction. Any additional lines will not be read. If you have more than 1 line of instruction to be executed pls use curly brace - or else exception will be thrown.


using redundant braces to claim that code is more maintainable raises the following question: if the guys writing, wondering about and further maintaining the code have issues like the ones described before (indentation related or readability related) perhaps they should not program at all...


it should be a reflex to reformat the code as well... that is of course for professional programmers in professional teams


It's probably best to use the curly braces everywhere for the simple fact that debugging this would be an extreme nuisance. But other wise, one line of code doesn't necessarily need the bracket. Hope this helps!


Nowadays, it is very easy to re-indent codes to find out which block of codes is in which if or for/while. If you insist that re-indenting is hard to do, then brackets placed at wrong indentation can confuse you equally badly.

for(int i = 0; i < 100; i++) { if(i < 10) {
    doSomething();
} else { for(int j = 0; j < 5; j++) {
        doSomethingElse();
    }
}}

If you do this everywhere, your brain is going to break down in no time. Even with brackets, you are depending on indentation to visually find the start and end of code blocks.

If indentation is important, then you should already write your code in correct indentation, so other people don't need to re-indent your codes to read correctly.

If you want to argue that the previous example is too fake/deliberate, and that the brackets are there to capture careless indentation problem (especially when you copy/paste codes), then consider this:

for(int i = 0; i < 100; i++) {
    if(i < 10) {
    doSomething();
}
else {
    for(int j = 0; j < 5; j++) {
        doSomethingElse();
    }
}

Yes, it looks less serious than the previous example, but you can still get confused by such indentation.

IMHO, it is the responsibility of the person writing the code to check through the code and make sure things are indented correctly before they proceed to do other things.

참고URL : https://stackoverflow.com/questions/8020228/is-it-ok-if-i-omit-curly-braces-in-java

반응형