gpt4 book ai didi

ruby - 重构圈复杂度

转载 作者:太空宇宙 更新时间:2023-11-03 17:29:48 24 4
gpt4 key购买 nike

我有一段圈复杂度很高的代码:

def status_icon_name
return 'icons/new.png' if mailgun_id.blank?
return 'icons/hourglass.png' if mailgun_id.present? && log.blank?

return 'icons/accept.png' if log['event'] == 'delivered'
return 'icons/exclamation.png' if log['severity'].present? && log['severity'] == 'permanent'
return 'icons/time.png' if log['event'] == 'accepted'
return 'icons/error.png' if log['severity'] == 'temporary'
return 'icons/question.gif'
end

我如何重构它以消除圈复杂度?

我已阅读这篇博文 Cyclomatic complexity refactoring tips for javascript developers想出了这样的东西,但我觉得不对:

def status_icon_name
lookup = [
{
condition: mailgun_id.blank?,
icon_name: 'icons/new.png'
},
{
condition: mailgun_id.present? && log.blank?,
icon_name: 'icons/hourglass.png'
},
{
condition: log.present? && log['event'] == 'delivered',
icon_name: 'icons/accept.png'
},
{
condition: log.present? && log['severity'].present? && log['severity'] == 'permanent',
icon_name: 'icons/exclamation.png'
},
{
condition: log.present? && log['event'] == 'accepted',
icon_name: 'icons/time.png'
},
{
condition: log.present? && log['severity'] == 'temporary',
icon_name: 'icons/error.png'
},
{
condition: true,
icon_name: 'icons/question.gif'
}
]

lookup.find { |x| x[:condition] }[:icon_name]
end

最佳答案

在运行时构建这样的查找表会适得其反,您正在生成这个巨大的结构并评估所有这些条件,而不管它们的有效性。

也就是说,当你写:

lookup = [
{
condition: mailgun_id.blank?,
icon_name: 'icons/new.png'
}
]

这会立即得到评估并简化为:

lookup = [
{
condition: true,
icon_name: 'icons/new.png'
}
]

如果你想要延迟执行,你需要使用一个Proc:

LOOKUP = [
{
condition: Proc.new { mailgun_id.blank? },
icon_name: 'icons/new.png'
}
]

然后你会像这样执行:

LOOKUP.find { |x| instance_eval(&x[:condition]) }[:icon_name]

这样您就可以将查找表作为常量存储在类的顶部,并且只需定义一次,而不是每次方法调用一次。

关于ruby - 重构圈复杂度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45290202/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com