developer tip

'if'문에는 항상 'else'절이 있어야합니까?

copycodes 2020. 12. 2. 21:29
반응형

'if'문에는 항상 'else'절이 있어야합니까?


이것은 종교적인 주장 일 수 있지만, 모든 IF 문이 ELSE 절을 포함해야하는지 여부에 대한 논의가 여기에 있습니다. 심지어 ELSE 절에 '의도적으로 비워 두었다'는 주석 만 포함되어 있더라도 말입니다.

양측에 대한 주장을 들었습니다. 'For'캠프-조건에 ELSE 절이 필요한지 여부를 코드가 실제로 다루 었는지 확인합니다. 'Against'캠프-코드를 읽기가 더 어렵고 노이즈가 너무 많이 추가됨

양측 모두를 만족시킬 수있는 답변으로이 논쟁을 해결해야하므로 다른 관점에 관심이 있습니다.

도와 주셔서 감사합니다.

BTW : StackOverflow에서 이에 대한 답변을 검색했지만 찾을 수 없었습니다. 하나가 있으면 링크를 포함하고 닫으십시오. 감사.


쓸모없는 타이핑처럼 보입니다 ... 그리고 혼란의 원인이 될 수 있습니다. 필요하지 않다면 넣지 마세요!


아니요. else측면에서 코드를 실행할 필요가 없다면 else절이 필요하지 않습니다 .


여기의 응답을 통해 아무도 사용하지 않은 다른 사람이 필요하다고 느끼지 않는다는 것이 분명합니다. 나는 그런 것을 듣거나 읽은 적이 없습니다. 더 중요한 문제는 이것이 If Then이 사용되는 방식이라고 굳게 믿는 동료 / 개발자를 상대하는 것입니다.

이 시나리오에서는 당신이 선임자가 아닌 것처럼 들리므로 단순히 그렇게하겠다고 선언 할 수는 없습니다. 개발에 관한 책 (블로그는 포함되지 않음)에서 그러한 프로세스가 제안 된 위치를 보여줄 "다른 빈"당사자에게 요청하는 것이 좋습니다. 더 좋은 것은 개발에 관한 3 권의 책입니다. 나는 1982 년부터 프로그래밍 언어에 걸쳐 프로그래밍 책을 읽었으며 그러한 제안을 본 적이 없습니다.

이런 식으로 당신은 그들이 개인적으로 받아 들일 수있는 그들이 틀렸다고 말하는 것이 아닙니다. 대신 그러한 입장을 기꺼이 받아들이지 만 몇 가지 문서를보고 싶습니다. 증거를 찾을 책임이 그들에게 있습니다. 그들은 그것을 찾거나 지금까지 쓰여진 모든 프로그래밍 책이 옳지 만 틀렸다고 주장 할 수 있습니다.

행운을 빕니다.


황금률 : 코드를 더 명확하고 이해하기 쉽게 만들면 입력하고, 그렇지 않으면 제외합니다. 숙련 된 프로그래머는 사례별로 이러한 판단을 내릴 수 있습니다.


Algol 파생 언어에 대해 이야기하고 있습니까?

Lisp에서는 그렇습니다. 모든 IF에는 else 절이 있어야합니다. 그렇지 않으면 WHEN을 사용해야합니다.


당신이 말했듯이, 이것은 스타일의 문제일지도 모르지만, "모든 if 블록이 하나를 가져야 만한다"는 이유로 내 코드에 빈 else 블록을 넣는 것을 꿈꾸지 않을 것입니다. 제 생각에는 코드에 문자를 더 추가하고 코드 검토 중에 시간을 할애 할 하나의 포인트 ( 매우 적은 가치) 만 추가합니다.


else악취가 필요합니다 . 필요할 때 사용하십시오. 모든 프로그래머는 구조와 누락의 의미를 이해합니다 else. 코드를 반향하는 무의미한 주석과 같습니다. 평범한 IMO입니다.


저는 "early if"문을 다음과 같이 중첩 된 중괄호 (또는 Python의 들여 쓰기) 수준을 줄이는 수단으로 사용하는 경향이 있습니다.

if (inParam == null) {
  return;
}

if (inParam.Value < 0) {
  throw new ArgumentException(...,...);
}
// Else ... from here on my if statements are simpler since I got here.

물론 .Net 4.0에는 이제 코드 계약이 있습니다. 그러나 대부분의 언어에는 아직이 기능이 없으므로 "early ifs"(더 나은 용어가 부족한 경우)는 많은 else 절과 중첩 된 if를 제거하기 때문에 정확합니다. 고급 언어로 else 절을 ​​사용하는 것은 유익하지 않다고 생각합니다. 심지어 어셈블리에서도 마찬가지입니다! 아이디어는 당신이 확인하고 점프하지 않았다면 조건이 거짓이고 우리는 계속할 수 있다는 것입니다. 나에게 논리적으로 이해됩니다 ...

편집 : 이 기사를 확인하여 else절이 많은 도움이되지 않는 이유를 확인하십시오 : http://www.codinghorror.com/blog/2006/01/flattening-arrow-code.html


"코드가 조건에 ELSE 절이 필요한지 여부를 실제로 해결했는지 확인합니다."

이것은 모든 메서드에서 catch 절을 요구하는 것보다 더 사실이 아닙니다. 가능한 모든 예외가 제대로 처리되었는지 확인합니다.


아니요. 가드 조건이 좋은 예입니다. 나머지 메소드 로직을 else 절에 중첩시킬 수 있지만 정말 빨리 추악해질 수 있습니다.


SQL Server 2000, 2005 이상.

IF 1 = 1
BEGIN
    PRINT 'doing something productive'
END
ELSE
BEGIN
    --Just sitting here
END


Msg 102, Level 15, State 1, Line 8
Incorrect syntax near 'END'.

의미있는 진술이 있어야합니다. 즉, 더미 할당 또는 클라이언트에 데이터 반환을 의미합니다. WAITFOR DELAY를 사용할 수 있다고 생각합니다 ...


if (thereIsSomeThingToDoInTheElse)
{
    putAnElseClause();
}
else
{
    // intentionally left blank
}

Haskell의 if는 항상 삼항입니다. 그래서 다른 것은 필수입니다.


Having an "else" with just an empty line of a code comment can usually mean the developer thought-through the condition and has a better idea of what execution path is actually taken at a given time. All recent compilers will remove the "else" and the comment, so you are not slowing software execution.

Unless I am reading the other responses incorrectly, it looks like most folks are objecting to the time it takes to declare their thoughts in the code and would rather just do it.


If your code is complex enough that this becomes an issue, you should probably be rethinking your approach to the problem. Break what you're doing down into smaller simpler functions where it should be unbelievably obvious what the if statements are doing.

If you can't break it down into smaller functions, or you find yourself nesting more than one if statement inside another, Using if statements for your conditional logic are probably not a good fit. Consider switches, lookup tables (if the only difference between your conditions is the value of some constant), or decision tables instead.

If you've already done all this, then you are quibbling over something so unbelievably trivial it's hardly worth your time to argue it.


One of the few possible situations where this might be a good idea is where you have several nested if statements, but fewer else clauses. The language will specify which if the else matches, but this may not always be clear to the reader. Of course, where you put content in curly brackets, nesting will be obvious, so there's no ambiguity. This make this a bit of an artificial case, but still possibly worth mentioning. Also, if your code is this complicated, there's probably a clearer way of writing it.


there are a lot of "words" telling you the way to programming such as DRY

in this case i'd use YAGNI.. you aint gonna need it..

so following this you shouldn't write the else.

anyhow in my opinion it makes it harder to read and understand the code.. the more you write the harder to understand the code is

edit: here are the links you requested: http://en.wikipedia.org/wiki/YAGNI http://en.wikipedia.org/wiki/Don%27t_repeat_yourself


There are situations where using an optional syntax element when not required can improve readability or prevent future errors. A typical case are the brackets around one-sentence conditionals:

Doing

if(foo){
    bar
}

instead of

if(foo)
    bar

could eventually prevent

if(foo)
    bar
    dot

I can't really think of any language I know where omitting an unnecessary else can lead to potential errors :-?

참고URL : https://stackoverflow.com/questions/1780384/should-if-statement-always-have-an-else-clause

반응형