2016-06-17 10 views
1

に、私は同じことを書いている2つのスタイル見ればVS:-ベストプラクティス次/望ましい/より正確である1リターン早期Rubyコード

def find_nest(animal) 
    if animal.bird? 
    GPS.find_nest(animal.do_crazy_stuff) 
    end 
end 

def find_nest(animal) 
    return unless animal.bird? 
    GPS.find_nest(animal.do_crazy_stuff) 
end 

を?それとも問題じゃない?無効なデータをアサートすることができたときにRuby style guideを1として

+0

animal.bird場合、私は 'GPS.find_nest(animal.do_crazy_stuff)を記述します' – Stefan

+0

を私はいつも質問のためにひどい例を思い付く@Stefan? :P –

+0

@Stefan:値が重要な式の場合は、修飾子の条件が混乱することがわかります。最初の式が長すぎない場合(またはそれ以外の場合は修飾子を視界から外す)のみ、 "ステートメント"でそれらを使用してください。 –

答えて

7

は、ガード句を好みます。ガード節 は、できるだけ早く となるように機能の先頭にある条件文です。

# bad 
def compute_thing(thing) 
    if thing[:foo] 
    update_with_bar(thing) 
    if thing[:foo][:bar] 
     partial_compute(thing) 
    else 
     re_compute(thing) 
    end 
    end 
end 

# good 
def compute_thing(thing) 
    return unless thing[:foo] 
    update_with_bar(thing[:foo]) 
    return re_compute(thing) unless thing[:foo][:bar] 
    partial_compute(thing) 
end 
1

それは、明らかに個人的な好みの問題です。しかし、私は早期復帰を好む。コードが「フラット」になって読みやすくなり、チェックの数も増えます。たとえば、次のように

def create_terms_of_service_notification 
    return if Rails.env.test? 
    return if current_user.accepted_tos? 
    # imagine 5 more checks here. 
    # Now imagine them as a mess of nested ifs. 

    # create the notification 
    end 
0

この:}

def find_nest(animal) 
    GPS.find_nest(animal.do_crazy_stuff) if animal.bird? 
end 
関連する問題