Sonarqube 报告控制器操作的重复代码块

Sonarqube reporting duplicate code block on controller actions

我正在使用 SonarQube 分析我的 .NET Core 应用程序,它现在报告以下两个控制器操作的重复块:从查询字符串中获取的三个参数和 ParametersHelper.ProcessAndSanitizeSee2InputParams 的调用,如图所示。

静态方法调用清理每个参数 - 空值检查、修整和自定义逻辑 - 并将它们分组到字典中。

关于如何重构这些操作以避免触发 SonarQube 的重复代码检测的任何提示?

// comments omitted
[HttpGet("{seasonKey}")]
[ProducesResponseType(typeof(See2Season), 200)]
public async Task<IActionResult> GetSeasonByKeyAsync(
    string seasonKey,
    [FromQuery(Name = "provider")] string providers,
    [FromQuery(Name = "lang")] string languages,
    [FromQuery(Name = "priority")] string priority)
{
    var sanitizedSee2Params = ParametersHelper.ProcessAndSanitizeSee2InputParams(
        this._logger,
        true,
        new KeyValuePair<string, string>(InputParameterNames.PROVIDERS, providers),
        new KeyValuePair<string, string>(InputParameterNames.LANGUAGE, languages),
        new KeyValuePair<string, string>(InputParameterNames.PRIORITY, priority));

    var result = await this._seasonManager.GetSeasonByKeyAsync(
        seasonKey,
        sanitizedSee2Params).ConfigureAwait(false); 

    return this.Ok(result);
}

// comments omitted
[HttpGet("{seasonKey}/children")]
[ProducesResponseType(typeof(IEnumerable<See2Content>), 200)]
public async Task<IActionResult> GetSeasonChildrenByKeyAsync(
    string seasonKey,
    [FromQuery(Name = "overrideDefaultDirection")] bool overrideDefaultDirection,
    [FromQuery(Name = "provider")] string providers,
    [FromQuery(Name = "lang")] string languages,
    [FromQuery(Name = "priority")] string priority)
{
    var sanitizedSee2Params = ParametersHelper.ProcessAndSanitizeSee2InputParams(
        this._logger,
        true,
        new KeyValuePair<string, string>(InputParameterNames.PROVIDERS, providers),
        new KeyValuePair<string, string>(InputParameterNames.LANGUAGE, languages),
        new KeyValuePair<string, string>(InputParameterNames.PRIORITY, priority));

    var result = await this._seasonManager.GetSeasonChildrenByKeyAsync(
        seasonKey,
        overrideDefaultDirection,
        sanitizedSee2Params).ConfigureAwait(false);

    return this.Ok(result);
}

您无需删除整个重复即可解决此重复问题(克隆)。删除/减少由第一个克隆的行 96-101 引起的重复应该足够了。您可以考虑将该逻辑提取到一个单独的方法中。像这样:

private SanitizedInputParams sanitizeSeasonParams(string providers, string languages, string priority) {
  return ParametersHelper.ProcessAndSanitizeSee2InputParams(
    this._logger,
    true,
    new KeyValuePair<string, string>(InputParameterNames.PROVIDERS, providers),
    new KeyValuePair<string, string>(InputParameterNames.LANGUAGE, languages),
    new KeyValuePair<string, string>(InputParameterNames.PRIORITY, priority));
}

因此,克隆长度减少,因此 SonarQube 可能不会再报告此问题(取决于配置的最小克隆长度)。 或者,您可以考虑增加最小克隆长度以专注于更长、更相关的克隆。另见:https://docs.sonarqube.org/display/SONARQUBE45/Duplications