programing

더 명확한 형식 : if (! value) 또는 if (flag == value)?

nasanasas 2021. 1. 5. 08:09
반응형

더 명확한 형식 : if (! value) 또는 if (flag == value)?


이 질문이 주관적인 질문이라는 것을 이해하고 마감해야하는지 사과드립니다.하지만 한 형식에 대한 일반적인 선호도가 다른 형식보다 더 많은지 궁금 할 정도로 자주 나오는 것 같습니다.

분명히 가장 좋은 대답은 "코드를 리팩토링하여 거짓을 테스트 할 필요가 없습니다"이지만 때로는 그렇게 할 수있는 쉬운 방법이 없으며 "else"분기는 단순히 처리를 계속하는 것입니다. 따라서 선호되는 표준 인 "거짓이 아닌 경우"구조가 있어야하는 경우 :

not 연산자

if (!value)

또는 거짓 테스트

if (value == false)

if (!value)따라 가기 쉽고 빠릅니다. 당신이 말했듯이 주관적입니다. 일관성이있는 한 이것이 중요합니다.

편집하다

추가해야 할 또 다른 요점-true / false 키워드를 생략하면 코더가 더 나은 이름의 변수를 사용하도록 강제해야합니다. 부울 변수는 항상 다음과 같은 의미 또는 상태 목적을 나타내야합니다.

if (MyWallet.IsEmpty)

위의 내용을 사용 == false하거나 == true중복되므로 이유가 없습니다 . 위의 내용은 사람이 즉시 읽을 수 있습니다.

해독하는 것보다 훨씬 낫습니다.

if (MyWallet.EmptyStatus == true) 또는 이와 같은 우스꽝스러운 것.


나는 개인적으로 좋아한다

if ((value == false) == true) ...

이것은 문장 value is false이 실제로 부울 true로 평가되고 있는지 확인하는 것 입니다 ...

그리고 분명히 두 가지 가능성을 모두 덮으면 더 명확 해집니다.

if ((value == false) == true && (value == false) != false)

<grin/>

명확성을 위해 진정한 열성가이고 논란의 여지가없는 가독성을 요구하는 분들에게는

if (((value == false) == true && (value == false) != false) == true)


if (!value)

이것은 내 생각에 항상 더 명확합니다.

if (value == false)

나는이 말을하기 싫다. 왜냐하면 그것은 다소 비열하게 들리기 때문이다. 그러나 이것은 일반적으로 코드를 작성하는 사람이 부울 값의 사용을 정말로 이해하지 못한다는 것을 보여준다. if 문에서 부울이 무엇인지 다시 검증 할 필요가 없습니다. 중복됩니다.

(개인적으로도 그 사람 value이 좀 더 의미있는 이름 대신 변수 이름을 지정하면 짜증이납니다 . 게시 한 내용이 가짜 코드 일 뿐이라는 느낌이 들어서 리뷰에 분명히 표시 할 것입니다.)

수정 (아래 댓글에 대한 응답으로) :

사소 해 보일 수 있지만 종종 훨씬 더 큰 것의 표시입니다. 사실, var == true 등을 사용하는 대부분의 사람들은 이해하지 못합니다. 사실 일뿐입니다. 나는 그들의 어리 석음을 말하는 것이 아니다. 단지 그들이 복습하고 배워야 할 무언가가있을 것이라고 단지 프로그래머가되어서는 안된다. 문제는 논리가 훨씬 더 복잡해지면 이와 같은 개념을 이해하지 못하면 훨씬 더 큰 문제가 발생할 수 있다는 것입니다. 어떤 사람들은 "스타일이야"라고 말합니다. 괜찮아. 이 경우 진짜 질문은 "이렇게하면 나에게 어떻게 유익한가? 나 또는 다른 사람들이 그것으로부터 무엇을 얻습니까?"입니다. 그 질문에 확실하게 답할 수 없다면 "이게 좋은 생각 인 이유는 무엇입니까?"라고 자문 해보십시오.


나는 결코 사용 하지 않을if(value == true) 것이므로 일관성을 위해서도 사용하지 않을 것 if(value != false)입니다.


if(!value) 특히 부울 변수의 이름을 올바르게 지정하는 경우 더 명확하고 "우아함"

  • isWhatever
  • hasWhatever
  • 기타

같은 것

if (Page.IsPostback == true)

나에게 중복 된 것 같다


반대 의견 (종류)

컴파일 관점에서 보면 동일한 IL을 얻을 수 있으므로 가독성 관점에서만 중요합니다.

이러한 관점에서 볼 때 if(value == false)평범한 독자에게 더 분명하고!를 놓칠 가능성이 적습니다. bool 전에.

솔직히 두 가지 접근 방식을 모두 사용하며 대부분의 경우 변수 이름에 따라 다릅니다. "뱅"대신 "not"이라고 말하는 것이 여전히 괜찮다면, 나는 뱅 표기법을 사용할 것입니다.

예 :

if(!gotValue) {}
//if (I've) not gotValue

//but

if(checkValue == false){}
//If (I've) not checkValue doesn't quite work here grammatically.

Not valueVB로 코딩 할 때 사용 하지만 value == falseC #으로 코딩 할 때 사용하는 경향이 있습니다 . 가끔 변수 이름 (예 :! legal)에서 느낌표가 손실 될 수 있습니다. 내가 노련한 베테랑이기 때문 인지도 모르겠다.


일반적으로 if (! value) 값이 부울이라는 것을 알 때 선호합니다. 그러나 여러 번 문자열 또는 숫자 일 수 있습니다.

The number zero would evaluate to false in conditionals in a lot of languages (not all, though); however, the string "0" would evaluate to true. This is a problem particularly in JavaScript, particularly if you receive JSON strings from the server, particularly if the server is written in PHP (because most PHP developers are careless enough to just take values from the DB and call json_encode on them, not knowing that the DB yields strings and not having a clue that all those zeros and ones that they use as boolean fields will be encoded as strings on the other end, thus all treated as true in conditionals).

Rant over. 제 제안 : 특히 귀하의 언어가 "매우 동적 인"유형 (예 : JavaScript, PHP, Perl) 인 경우 명시 적으로 작성하십시오.


나는 그것이 모든 주관적이라고 생각하지 않습니다. 나는 그것이 더 긴 형태로 권장되는 것을 본 적이 없습니다 . 실제로 내가 읽은 모든 책과 코딩 가이드와 "좋은 프로그래머가되는 방법"하우투는 그것을 권장하지 않습니다.

다음과 같은 범주에 속합니다.

if (value) {
  return true;
} else {
  return false;
}

OTOH, 여기에 주어진 모든 대답은 내 첫 번째 진술이 사실이 아닌 것과 같습니다.


if(!value)관련된 변수의 이름에 따라 "진정한"케이스가 영어 의미론에 따라 훨씬 더 의미가 있기 때문에 사용을 선호 합니다.

이 MSDN 기사 의 예 중 하나를 고려 하십시오 .

if(pane.IsChecked)

영어로 "창이 선택되어있는 경우"로 읽습니다.

However, if(pane.IsChecked == true) reads in English as "If whether the pane is checked is true". That statement that is far less clear in English than it should be.

One of the reasons why we don't write C# code in binary is human readability. If you're given the choice between code that flows well when you read it and code that doesn't, side with the one that is more readable. I don't think adding the "== true" makes this example more readable, and MSDN doesn't think so either.

Granted, this is a rather small example to worry about. But as some of the other answers have indicated, not applying this way of thinking to larger-scale cases can hurt readability.


I favour the if (!value) style at least for evaluating variables or common properties like Page.IsPostback and the like. For anything more complex I tend to parenthesise the expression like thus:

if (!(SomeType.SomeProperty.CallingAMethod(input).GetSomething.BooleanProperty))

Just to draw a little more attention to it.

All in all, it's an argument for Perl-style unless and until keywords.


Whatever one you prefer. Pick one and stick to it.


If the condition is just a check of a single value, then !value is quicker.

However, when the condition contains multiple value checks, I find it much easier to read value == false. Somehow it is easier to parse multiple checks for equality than multiple negations of values.


I am sorry to say, the second just looks stupid to me.

I'd add an extra level, if someone prefers it:

if( (value==false) == true )

:)


I actually many of forms possible.

This is not actually how it is written to standards, but this is how I see it:

//if foo is(or exists)
if(foo)

//if foo is true
if(foo == true)

//if foo doesn’t exist
if(!foo)

if foo is false
if(foo == false)

Hence I don’t see == false is redundant.


I prefer the second option, the if (value == false) one. I gladly use if (~value) or if (not value) in languages that support it, but that ! just merges waaaaay too easily either with the variable name or opening braces or | or || operators... at least in my opinion.

Also, two things:

  1. I never do if (value == true), and I'm aware I'm inconsistent. And although consistency is very important in my opinion, that pesky ! is simply worse.
  2. I think it's really a matter of personal taste, just like the brace-on-a-newline debate. I would never criticize a teammate for silly little things like that, and I have a hard time understanding the people who will.

Whatever condition an if block should evaluate in order to execute must evaluate to true.

Hence, when value is false, the reason why if (!value) allows an if block to execute is because the ! operator essentially flips the false value of value to true, thus making the resultant condition within the parentheses evaluate into a true one that an if block needs in order to execute.

if (value), if (!value), if (flag == value), if (value == true), if (value == false), depending on what's to be achieved, are valid code. E.g. if (value == true) is very useful when value is a nullable boolean, because if (value) will give a syntax error, and if (value.Value == true) will throw exception if you didn't ensure that value is not null before the if block is executed.


I use if (value == false) The ! in if (!value) is so small I sometimes miss it.

ReferenceURL : https://stackoverflow.com/questions/2977365/which-is-clearer-form-ifvalue-or-ifflag-value

반응형