Back

重构:对于复杂的if-else的手法

发布时间: 2015-09-15 09:05:00

基本是几个:

1. 在逻辑上简化

2. 使用guard statement ( 守护语句,  xxx if ooo )

3. 使用case 表意更明确。

4. 对于  if ... else ... end , 使用  三元表达式:     true ?  state1 : state2  

下面是个例子: (有三层 if-else )

    def show
      if current_user_can_view_page?
        if should_skip_to_first_child?
          redirect_to refinery.url_for(first_live_child.url)
        elsif page.link_url.present?
          redirect_to page.link_url
        else
          if requested_friendly_id != page.friendly_id
            redirect_to refinery.url_for(page.url), :status => 301 
          else
            render_with_templates?
          end 
        end 
      else
        error_404
      end 
    end 

第一步, 简化最外层的分支。 因为 else 中的内容只有一行。

if ..
else
   error_404    
end 
改成:

error_404 unles ...
if ... end 

#  经历了各种步骤之后,看起来应该是:

      error_404 and return unless current_user_can_view_page?
      redirect_to refinery.url_for(first_live_child.url) and return if should_skip_to_first_child?
      redirect_to page.link_url and return if page.link_url.present?
      requested_friendly_id != page.friendly_id ?
        redirect_to refinery.url_for(page.url), :status => 301   :   
        render_with_templates?

Back