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

在我的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的好书,他在解释如何,何时以及为何重构你的代码时非常惊人.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...