加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby – 为什么一个包含太多行的方法是一件坏事?

发布时间:2020-12-16 19:19:05 所属栏目:百科 来源:网络整理
导读:在我的rails应用程序中,我有一个这样的方法: def cart if user_signed_in? @user = current_user if @user.cart.present? @cart = @user.cart else @cart = false end else cart_id = session[:cart_id] if cart_id.present? @cart = Cart.find(cart_id.to_
在我的rails应用程序中,我有一个这样的方法:
def cart
    if user_signed_in?
        @user = current_user
        if @user.cart.present?
            @cart = @user.cart
        else
            @cart = false
        end
    else
        cart_id = session[:cart_id]

        if cart_id.present?
            @cart = Cart.find(cart_id.to_i)
        else
            @cart = false
        end
    end
end

Rubocop标记了这个方法,因为Method有太多行.为什么写一个行太多的方法不好?如果我们必须做很多工作怎么办?我怎样才能重新考虑这一点并编写好的代码?

解决方法

一种方法是你可以使用 ternary operator重构它,但代价是可读性.
def cart
  if user_signed_in?
    @user = current_user
    @cart = @user.cart.present? ? @user.cart : false
  else
    cart_id = session[:cart_id]
    @cart = cart_id.present? ? Cart.find(cart_id.to_i) : false
  end
end

其次,如果你被迫编写一个很长的方法,这意味着你的面向对象设计有问题.也许,您需要为额外功能设计一个新类,或者您需要通过编写多个方法将功能拆分到同一个类中,这些方法在组合时可以完成单个long方法的工作.

Why is it bad to write a method with too many lines?

就像一篇带有大段落的文章难以阅读一样,同样使用较长方法的程序难以阅读,并且不太可能重复使用.您划分代码的块越多,代码的模块化,可重用性和可理解性就越高.

What if we have to do a lot of work in it?

如果你必须做很多工作;这肯定意味着你以一种不好的方式设计你的课程.也许,您需要设计一个新类来处理此功能,或者您需要将此方法拆分为较小的块.

How can I re-factor this and write good code?

为此,我强烈推荐给你一本名为:Refactoring by Martin Fowler的好书,他在解释如何,何时以及为何重构你的代码时非常惊人.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读