Confusing If Statement?

前端 未结 13 913
-上瘾入骨i
-上瘾入骨i 2020-12-20 13:03

I always use If statement (In C#) as (1. Alternative);

if (IsSuccessed == true)
{
   //
}

I know that there is no need to write \"== true\"

13条回答
  •  悲哀的现实
    2020-12-20 13:29

    If the name of the boolean value makes it perfectly clear what it is, then I'd always opt for version 2. However, sometimes you're stuck with a particularly obtuse variable name that you can't change, at least, can't change right now... Refactoring is all well and good, but I try and avoid refactoring too heavily when making functional changes to the code as well.

    For example:

    if (!NoDropDownInHeader == true)
    {
      // Activates when there *is* a dropdown in the header)
    }
    

    I've actually seen this particular example in production code and simplified it down to:

    if (NoDropDownInHeader == false)
    {
     // Activates when there *is* a dropdown in the header
    }
    

    And I personally think that both examples are more readable (although arguably the first example may be on par with this one for difficulty of mental parsing) than:

    if (!NoDropDownInHeader)
    {
     // Activates when there *is* a dropdown in the header
    }
    

    Note: Yes, I know the variable is badly named, but changing it in the multitude of places that it was present was outside the scope of the change I was making due to the number of places if would affect.

提交回复
热议问题