Best Practice on IF/ELSE Statement Order

前端 未结 10 2225
陌清茗
陌清茗 2020-12-16 14:48

Which is a better practice? (I\'m coding in .Net if that makes a difference)

IF condition = true THEN
   ...true action--even if rare...
ELSE
   ...action
E         


        
10条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-16 15:30

    If the most common case isn't the simplest to express, you might have an opportunity for re-factoring

    One useful re-factoring I've found:

    if (a.getFoo() == 1 && a.getBar() == 2) 
    

    can be re-factored to

    if (a.isFooBar()) 
    

    In come cases something nasty like this,

    if (!(fooSet.contains(a.getValidFoo()))) 
    

    could be

    if (a.hasInvalidFoo(fooSet)) 
    

    This can make option 1 also be option 2 by simplifying the evaluation of the most common condition.

提交回复
热议问题