Boolean types

前端 未结 10 2030
时光说笑
时光说笑 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: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.

提交回复
热议问题