Get rid of ugly if statements

后端 未结 25 2190
借酒劲吻你
借酒劲吻你 2020-12-02 05:59

I have this ugly code:

if ( v > 10 ) size = 6;
if ( v > 22 ) size = 5;
if ( v > 51 ) size = 4;
if ( v > 68 ) size = 3;
if ( v > 117 ) size = 2         


        
25条回答
  •  情话喂你
    2020-12-02 06:29

    The original code seems fine to me, but if you don't mind multiple returns you might prefer a more tabular approach:

    if ( v > 145 ) return 1;
    if ( v > 117 ) return 2;
    if ( v >  68 ) return 3;
    if ( v >  51 ) return 4;
    if ( v >  22 ) return 5;
    if ( v >  10 ) return 6;
    return ...;     // The <= 10 case isn't handled in the original code snippet. 
    

    See the multiple return or not discussion in org.life.java's answer.

提交回复
热议问题