gpt4 book ai didi

java - 定义常量的 Sonar 方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:54:31 25 4
gpt4 key购买 nike

我使用 Sonarqube 5.1 并尝试使用“Sonar Way”Java 质量配置文件。工作很简单:我想为缺少的媒体类型定义一个全局字符串常量:

public interface Utf8MediaType {
String APPLICATION_JSON = "application/json;charset=UTF-8";
}

但是,Sonarqube 告诉我这是规则 squid:S1214 中的不良做法 – 常量不应在接口(interface)中定义。长篇大论说要实现这个接口(interface),我不是有意为之,但我让步了,而是创建了一个类:

public class Utf8MediaType {
public static final String APPLICATION_JSON = "application/json;charset=UTF-8";
}

但是,这被认为是规则 squid:S1118 – 实用程序类不应具有公共(public)构造函数 中的主要设计问题。所以它敦促我添加一个私有(private)构造函数。当然,此构造函数必须首先出现,以免违反 squid:S1213 中的约定——接口(interface)声明或类的成员应按预定义的顺序出现。我想在那之后我什至可能会得到 common-java:InsufficientBranchCoverage,因为私有(private)构造函数未包含在测试中。


这些是默认规则,我觉得它们结合起来有点傻。我有更多示例,其中默认设置对我们不起作用(缺少 TestNG 支持)。我该怎么办?你有什么建议?

  • 让步。让它成为一个类,添加一个私有(private)构造函数,在单元测试中使用内省(introspection)。使代码大十倍。对于字符串常量。
  • 创建异常(exception)列表。但是,对每个项目都这样做可能会导致列表很长,甚至会邀请人们为重要的事情添加异常(exception)。
  • 停用规则。现在我希望不要篡改默认配置文件,因为这可能意味着在 Sonarqube 升级方面需要做很多工作。
  • 创建一个配置文件,该配置文件继承默认值并覆盖某些内容。事实证明,当您从配置文件继承时,您无法停用规则。您只能添加额外的规则并更改规则的配置(以降低其严重性)。

最佳答案

Give in. Make it a class, add a private constructor, use introspection in the unit test. Makes the code ten times as big. For a String constant.

这通常是正确的方法。你真的不想创建一个“常量”接口(interface)。需要私有(private)构造函数来确保用户不会无意中扩展或实例化不应实例化的对象。

How to add test coverage to a private constructor?

Create a list of exceptions. But doing this for each project may lead to long lists and invites people to add exceptions even for important stuff.

工作量太大。

Deactivate rules. Now I would prefer not to tamper with the default profiles, because that may mean a lot of work on Sonarqube upgrades.

正如你所说...坏主意。

Create a profile that inherits from the default and overwrites things. It turns out that when you inherit from a profile you cannot deactivate rules. You can only add additional rules and change the configuration of rules (to lower their severity).

如果您将严重性设置为“信息”,它将从技术债务计算中移除。我必须使用 squid:S1213 执行此操作,当我使用 Eclipse 指定的默认顺序进行排序时会引发此问题。

关于java - 定义常量的 Sonar 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30523430/

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