Boolean types

前端 未结 10 2019
时光说笑
时光说笑 2021-01-22 11:54

During code review I discovered many places of our C# code that looks like this:

if(IsValid()) {
     return true;
}
else {
     return false;
}
<
相关标签:
10条回答
  • 2021-01-22 12:21

    First case is easier when you are debugging. When you step through your source, it is easier to find out what the return value is without opening up immediate window or run IsValid(); just to see the return value.

    For the first and second case, developer might not be aware that s/he can simply do

    return IsValid();

    Lastly, a developer might be forced to use first or second syntax due to company policies.

    0 讨论(0)
  • 2021-01-22 12:22

    The reasons for the first two examples are entirely human:

    • ignorance
    • lack of intellectual involvement with one's code
    • code was refactored, but only half-way

    There's no reason not to (I know it's a double negative) go with return IsValid();

    0 讨论(0)
  • 2021-01-22 12:23

    If you're absent-minded, it's easy to refactor some code from this:

    private bool ConsiderTheOstrich()
    {
        /* do ostrich things */
    
        if(someCondition && unpredictableThing == 5)
            return true;
        else
        {
            // log something
            return false;
        }
    }
    

    To this:

    private void IsValid() { return (someCondition && unpredictableThing == 5); }
    
    /* ... */
    
    private void ConsiderTheOstrich()
    {
        /* do ostrich things */
    
        if(IsValid())
            return true;
        else
            return false; // ostrichlogger logs it for us now
    }
    

    Without noticing the extra opportunity for brevity.

    0 讨论(0)
  • 2021-01-22 12:28

    Yes, of course return IsValid(); would be most optimal if the only code you have is as above.

    I guess what comes into play though is what else is your function doing? The rest of the code might shed more light on why a developer would put an if statement around IsValid().

    After all, if it's just returning IsValid() then why isn't the calling code just checking IsValid() directly rather than having this wrapper method.

    0 讨论(0)
  • 2021-01-22 12:30

    I would also just say "return IsValid();" I think you're 100% correct in doing so

    0 讨论(0)
  • 2021-01-22 12:33

    return IsValid(); is the way to go. less code, more concise - choice of champions

    0 讨论(0)
提交回复
热议问题