0

我的一门课有以下功能

def intraday_time_series(opts)

  ### Guard block ###

  valid_resource = opts[:resource] && [:calories, :steps, :distance, :floors, :elevation].include?(opts[:resource])
  valid_date = opts[:date]
  valid_detail_level = opts[:detailLevel] && %w(1min 15min).include?(opts[:detailLevel])

  raise FitgemOauth2::InvalidArgumentError,
        'Must specify resource to fetch intraday time series data for.'\
        ' One of (:calories, :steps, :distance, :floors, or :elevation) is required.' unless valid_resource

  raise FitgemOauth2::InvalidArgumentError, 'Must specify the date to fetch intraday time series data for.' unless valid_date

  raise FitgemOauth2::InvalidArgumentError,
        'Must specify the data resolution to fetch intraday time series data for.'\
        ' One of (\"1d\" or \"15min\") is required.' unless valid_detail_level

  ### actual logic ###
  resource = opts.delete(:resource)
  date = format_date(opts.delete(:date))
  detail_level = opts.delete(:detailLevel)
  time_window_specified = opts[:startTime] || opts[:endTime]
  resource_path = "user/#{@user_id}/activities/"

  if time_window_specified
    start_time = format_time(opts.delete(:startTime))
    end_time = format_time(opts.delete(:endTime))
    resource_path += "#{resource}/date/#{date}/1d/#{detail_level}/time/#{start_time}/#{end_time}.json"
  else
    resource_path += "#{resource}/date/#{date}/1d/#{detail_level}.json"
  end
  get_call(resource_path)
end

该函数有一个保护块,用于检查参数的任何问题(保护块),如果没有发现错误,它会处理这些参数。

现在,当我rubocop用来分析我的代码时,由于防护块,它报告了很高的循环复杂度。我可以降低复杂性的一种方法是定义另一个函数guard_for_intraday_time_series并将所有保护块移到那里。不过,我认为它不是一个合适的解决方案,因为它会为我的项目中的每个函数使用一个保护块填充我的代码。

什么是降低这种复杂性的适当方法,或者它只是不可避免的?

4

1 回答 1

2

您有许多使代码复杂的中间局部变量。

我会这样重构它:

def intraday_time_series(resource: nil, date: nil,
    detailLevel: nil, startTime: nil, endTime: nil)
  unless %i[calories steps distance floors elevation].include?(resource)
    raise FitgemOauth2::InvalidArgumentError,
      "Must specify resource to fetch intraday time series data for."\
      " One of (:calories, :steps, :distance, :floors, or :elevation) is required."
  end
  unless date
    raise FitgemOauth2::InvalidArgumentError,
      "Must specify the date to fetch intraday time series data for."
  end
  unless %w(1min 15min).include?(detailLevel)
    raise FitgemOauth2::InvalidArgumentError,
      "Must specify the data resolution to fetch intraday time series data for."\
      " One of (\"1d\" or \"15min\") is required."
  end
  resource_path = [
    "user", @user_id,
    "activities", resource,
    "date", format_date(date),
    "1d", detailLevel
  ].join("/")
  if startTime || endTime
    resource_path =
    [resource_path, "time", format_time(startTime), format_time(endTime)].join("/")
  end
  get_call("#{resource_path}.json")
end
于 2016-04-02T09:16:25.007 回答