微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/ruby/270644.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐