【问题标题】:What is meant by 'Assignment Branch Condition Size too high' and how to fix it?“分配分支条件大小太高”是什么意思以及如何解决?
【发布时间】:2015-09-05 02:49:01
【问题描述】:

在我的 Rails 应用程序中,我使用Rubocop 来检查问题。今天它给了我这样的错误:Assignment Branch Condition size for show is too high。这是我的代码:

def show
  @category = Category.friendly.find(params[:id])
  @categories = Category.all
  @search = @category.products.approved.order(updated_at: :desc).ransack(params[:q])
  @products = @search.result.page(params[:page]).per(50)
  rate
end

这是什么意思,我该如何解决?

【问题讨论】:

  • 一个简短的搜索发现this。这是rubocop 的正式表达方式“你的方法做得太多了”。
  • 渲染中是否使用了所有定义的变量?

标签: ruby-on-rails ruby code-metrics rubocop


【解决方案1】:

分配分支条件 (ABC) 大小是对方法大小的度量。它本质上是通过计算 Assignments、Branches 和 Conditional statements 的数量来确定的。 (more detail..)

要降低 ABC 分数,您可以将其中一些作业移到 before_action 调用中:

before_action :fetch_current_category, only: [:show,:edit,:update] 
before_action :fetch_categories, only: [:show,:edit,:update] 
before_action :fetch_search_results, only: [:show,:edit,:update] #or whatever

def show
  rate
end

private

def fetch_current_category
  @category = Category.friendly.find(params[:id])
end

def fetch_categories
  @categories = Category.all
end

def fetch_search_results
  @search = category.products.approved.order(updated_at: :desc).ransack(params[:q])
  @products = @search.result.page(params[:page]).per(50)
end

【讨论】:

  • 非常感谢。现在代码看起来很可读,但它不会使文件变大吗?更多代码?好吃吗?
  • 如果您在其他操作中需要这些变量,请减少代码。
  • 我在这个方法上得到了同样的结果: # 将球画到这个设备上下文中 def draw(dc) dc.setForeground(color) dc.fillArc(x, y, w, h, 0, 64 * 90) dc.fillArc(x, y, w, h, 64 * 90, 64 * 180) dc.fillArc(x, y, w, h, 64 * 180, 64 * 270) dc.fillArc(x, y, w, h, 64 * 270, 64 * 360) end 我这里好像不能保留代码块布局!!!这里发生了什么?这里根本没有赋值,没有分支,也没有条件!!!!
  • 您在乘以数字的地方隐含了赋值。我会把它们移到常量中,这样你就不会在这些调用中重新评估相同的算术。我不确定这是否会解决您的 linter 的反馈,但它肯定会稍微清理一下。 :)
  • 您可以将它们全部分配在一行中,例如:RQ,RH,RT,RW=[90,180,270,360].map { |i| i * 64 }
猜你喜欢
  • 1970-01-01
  • 2020-05-22
  • 1970-01-01
  • 2016-04-13
  • 2016-09-05
  • 1970-01-01
  • 2010-11-22
  • 2020-04-22
  • 2019-10-17
相关资源
最近更新 更多