Using NOT operator in IF conditions

后端 未结 7 1906
遇见更好的自我
遇见更好的自我 2020-12-15 16:10

Is it really a good practice to avoid using NOT operator in IF conditions in order to make your code better readable? I heard the if (doSomething()) is better t

7条回答
  •  再見小時候
    2020-12-15 17:05

    In general, ! is a perfectly good and readable boolean logic operator. No reason not to use it unless you're simplifying by removing double negatives or applying Morgan's law.

    !(!A) = A
    

    or

    !(!A | !B) = A & B
    

    As a rule of thumb, keep the signature of your boolean return methods mnemonic and in line with convention. The problem with the scenario that @hvgotcodes proposes is that of course a.b and c.d.e are not very friendly examples to begin with. Suppose you have a Flight and a Seat class for a flight booking application. Then the condition for booking a flight could perfectly be something like

    if(flight.isActive() && !seat.isTaken())
    {
        //book the seat
    }
    

    This perfectly readable and understandable code. You could re-define your boolean logic for the Seat class and rephrase the condition to this, though.

    if(flight.isActive() && seat.isVacant())
    {
        //book the seat
    }
    

    Thus removing the ! operator if it really bothers you, but you'll see that it all depends on what your boolean methods mean.

提交回复
热议问题