56星座屋
当前位置: 首页 星座百科

sonar指导手册(代码检查扫描常见的问题汇总)

时间:2023-06-15 作者: 小编 阅读量: 1 栏目名: 星座百科

接下来我们就一起去研究一下吧!sonar指导手册阿里巴巴开发规范及sonar相信很多人都用过,今天主要汇总一下,用sonar扫描出来的一些代码问题。在开发中,经常一顿猛如虎的操作下来,代码是码完了,单元测试貌似也测了,代码的覆盖率好像也都覆盖了,结果符合预期,貌似可以提测了。这时有点方,好吧先不提测了,先看看sonar扫了些什么出来。

sonar指导手册?阿里巴巴开发规范及sonar相信很多人都用过,今天主要汇总一下,用sonar扫描出来的一些代码问题,今天小编就来聊一聊关于sonar指导手册?接下来我们就一起去研究一下吧!

sonar指导手册

阿里巴巴开发规范及sonar相信很多人都用过,今天主要汇总一下,用sonar扫描出来的一些代码问题。

在开发中,经常一顿猛如虎的操作下来,代码是码完了,单元测试貌似也测了,代码的覆盖率好像也都覆盖了,结果符合预期,貌似可以提测了。刚发提测邮件,领导说,Dot你去review一下代码,看有没有问题,sonar扫描一下看哪些不符合规范。这时有点方,好吧先不提测了,先看看sonar扫了些什么出来。

好在,这个工具很好用,虽然很讨要的扫出来很多不规范的写法及用法,但是也相应的给出答案及正确做法

Move the contents of this initializer to a standard constructor or to field initializers

将这段内容移到初始化构造里或者字段初始化里

错误示范:

class MyClass {private static final Map<String, String> MY_MAP = new HashMap<String, String>() {// Noncompliant - HashMap should be extended only to add behavior, not for initialization{put("a", "b");}};}

正确示范:

class MyClass {private static final Map<String, String> MY_MAP = new HashMap<String, String>();static {MY_MAP.put("a", "b");}}

或者是用google的guava相关工具包

class MyClass {// Compliantprivate static final Map<String, String> MY_MAP = ImmutableMap.of("a", "b");}

Call "Optional#isPresent()" before accessing the value

这个看起来就很简单了,就是在使用这个value之前呢先得用Optional.isPresent()检查一下这个值是否为空

错误示范:

Optional<String> value = this.getOptionalValue();// ...String stringValue = value.get(); // Noncompliant

正确示范:

Optional<String> value = this.getOptionalValue();// ...if (value.isPresent()) {String stringValue = value.get();}

或者:

Optional<String> value = this.getOptionalValue();// ...String stringValue = value.orElse("default");

Invoke method(s) only conditionally

这个肯定是日子用的有问题咯,看看错误示范

logger.log(Level.DEBUG, "Something went wrong: "message); logger.fine("An exception occurred with message: "message);LOG.error("Unable to open file "csvPath, e);

正确示范:

logger.log(Level.SEVERE, "Something went wrong: {0} ", message); logger.fine("An exception occurred with message: {}", message);logger.log(Level.SEVERE, () -> "Something went wrong: "message);LOG.error("Unable to open file {0}", csvPath, e);if (LOG.isDebugEnabled() {LOG.debug("Unable to open file "csvPath, e);}

String contains no format specifiers

这个肯定是字符串格式化有问题或者不规范,比如

} catch (Exception er) {logger.error("save error info failed", er.getLocalizedMessage());}

String.format("First {0} and then {1}", "foo", "bar");String.format("Display %3$d and then %d", 1, 2, 3);String.format("Too many arguments %d and %d", 1, 2, 3);String.format("First Line\n");String.format("Is myObject null ? %b", myObject);String.format("value is "value);String s = String.format("string without arguments");MessageFormat.format("Result '{0}'.", value);MessageFormat.format("Result {0}.", value, value);MessageFormat.format("Result {0}.", myObject.toString());

正确示范:

String.format("First %s and then %s", "foo", "bar");String.format("Display %2$d and then %d", 1, 3);String.format("Too many arguments %d %d", 1, 2);String.format("First Line%n");String.format("Is myObject null ? %b", myObject == null);String.format("value is %d", value);String s = "string without arguments";MessageFormat.format("Result {0}.", value);MessageFormat.format("Result '{0}' = {0}", value);MessageFormat.format("Result {0}.", myObject);

Refactor this method to reduce its Cognitive Complexity from 32 to the 15 allowed

方法的复杂度过高,其实就是if太多了,方法的方法体太大了

减少if的判断,真的是业务比较复杂,将方法拆解,然后在规划出不满足条件的,直接return剩下的逻辑就都是满足的业务场景

Remove this unused "xxxx" private field

移除未使用的私有变量

No need to call "toString()" method as formatting and string conversion is done by the Formatter.

例如:

logger.info("地址余额信息:{}", addressBalanceMap.toString());

这里不需要调用tostring方法,应该调用自己需要看到的string format

This block of commented-out lines of code should be remoted

不用的代码块应该移除掉

Add a private consturctor to hide the implicit public one

添加一个私有构造函数来替代隐藏默认的共有的构造函数

错误示范:

class StringUtils { // Noncompliantpublic static String concatenate(String s1, String s2) {return s1s2;}}

正确示范:

class StringUtils { // Compliantprivate StringUtils() {throw new IllegalStateException("Utility class");}public static String concatenate(String s1, String s2) {return s1s2;}}

Change the visbility of this constructor to "protected"

这个一般是针对抽象类的,修改这个隐藏的默认的构造函数访问权限为protected

错误示范:

public abstract class AbstractClass1 {public AbstractClass1 () { // Noncompliant, has public modifier// do something here}}

正确示范:

public abstract class AbstractClass2 {protected AbstractClass2 () {// do something here}}

Change this condition so that it does not always evaluate to "false"

修改条件,不能使用条件未执行的代码,例如:

a = false;if (a) { // NoncompliantdoSomething(); //这块永远都不会执行// never executed}if (!a || b) { // Noncompliant; "!a" is always "true", "b" is never evaluateddoSomething();} else {doSomethingElse();//这块永远都不会执行// never executed}

Define and throw a dedicated exception instead of using a generic one

不应该抛出一个笼统的异常,应该定义一个自己的异常

错误示范:

public void foo(String bar) throws Throwable { // Noncompliantthrow new RuntimeException("My Message"); // Noncompliant}

正确示范:

public void foo(String bar) {throw new MyOwnRuntimeException("My Message");}

Add at least one assetion to this test case.

单元测试应该包含断言内容

错误示范:

@Testpublic void testDoSomething() { // NoncompliantMyClass myClass = new MyClass();myClass.doSomething();}

正确示范:

@Testpublic void testDoSomething() {MyClass myClass = new MyClass();assertNull(myClass.doSomething()); // JUnit assertionassertThat(myClass.doSomething()).isNull(); // Fest assertion}

Move constants defined in this interfaces to another class or enum.

接口中不应该定义一些常亮信息

例如:

interface Status { // Noncompliantint OPEN = 1;int CLOSED = 2;}

正确示范:

public enum Status { // CompliantOPEN,CLOSED;}

或者:

public final class Status { // Compliantpublic static final int OPEN = 1;public static final int CLOSED = 2;}

Add a nested comment explaining why this method is empty,thow an UnsupoorttedOperationException or complete the implementation

为什么会有个空方法,要么添加一些注释说明要么抛出UnsupportedOperationException

错误示范:

public void doSomething() {}、public void doSomethingElse() {}

正确示范:

@Overridepublic void doSomething() {// Do nothing because of X and Y.}@Overridepublic void doSomethingElse() {throw new UnsupportedOperationException();}

Extract this nested try block into a separeate method.

try代码块不应该有嵌套

Return an empty collection instead null

返回一个空集合代替返回null

错误示范:

public static List<Result> getResults() {return null; // Noncompliant}public static Result[] getResults() {return null; // Noncompliant}

正确示范:

public static List<Result> getResults() {return Collections.emptyList(); // Compliant}public static Result[] getResults() {return new Result[0];}

Either log this exception and handler it,or rethrow it with some contextual information

log应该记录或重新抛出但不能同时记录跟抛出,说的有点绕,什么意思呢,大概看下错误实例代码就知道了

catch (SQLException e) {...LOGGER.log(Level.ERROR, contextInfo, e);throw new MySQLException(contextInfo, e);}

正确实例:

catch (SQLException e) {...throw new MySQLException(contextInfo, e);}

或者:

catch (SQLException e) {...LOGGER.log(Level.ERROR, contextInfo, e);// handle exception...}

Either re-interrupt this method or rethrow the "InterruptedException"

不能忽略InterrupttedException这个异常

错误示范:

public void run () {try {while (true) {// do stuff}}catch (InterruptedException e) { // Noncompliant; logging is not enoughLOGGER.log(Level.WARN, "Interrupted!", e);}}

正确示范:

public void run () {try {while (true) {// do stuff}}catch (InterruptedException e) {LOGGER.log(Level.WARN, "Interrupted!", e);// Restore interrupted state...Thread.currentThread().interrupt();}}

Use "BigDecimal.valueOf" instead

用BigDecimal.valueOf替代

错误示范:

double d = 1.1;BigDecimal bd1 = new BigDecimal(d); // Noncompliant; see comment aboveBigDecimal bd2 = new BigDecimal(1.1); // Noncompliant; same result

正确示范:

double d = 1.1;BigDecimal bd1 = BigDecimal.valueOf(d);BigDecimal bd2 = new BigDecimal("1.1");

Replace this "Map.get()" and condition with a call to "Map.computeIfAbsent()"

map.get 带条件的方法应该使用compuleIfAbsent,有就get没有就put

错误示范:

V value = map.get(key);if (value == null) { // Noncompliantvalue = V.createFor(key);if (value != null) {map.put(key, value);}}return value;

正确示范:

return map.computeIfAbsent(key, k -> V.createFor(k));

Add the missing @deprecated Javadoc tag

添加废弃注释时应该添加java注释,注释写清楚,让其他人知道什么情况废弃,废弃原因是什么

错误示范:

class MyClass {@Deprecatedpublic void foo1() {}/*** @deprecated*/public void foo2() { // Noncompliant}}

正确示范:

class MyClass {/*** @deprecated (when, why, refactoring advice...)*/@Deprecatedpublic void foo1() {}/*** Java >= 9* @deprecated (when, why, refactoring advice...)*/@Deprecated(since="5.1")public void foo2() {}/*** Java >= 9* @deprecated (when, why, refactoring advice...)*/@Deprecated(since="4.2", forRemoval=true)public void foo3() {}}

以上都是项目中扫描出来的不规范的代码,根据实际情况进行修改,标示出来的都是优先级比较高的,下次汇总会汇总一些优先级中等级别的出来以便记录

    推荐阅读
  • 形成酸雨的主要气体是什么(形成酸雨的主要气体)

    以下内容大家不妨参考一二希望能帮到您!形成酸雨的主要气体是什么酸雨是指PH小于5.6的雨雪或其他形式的降水,形成的主要气体有二氧化硫、三氧化硫、硫化氢、二氧化氮。酸雨主要是人为的向大气中排放大量酸性物质所造成的。酸雨又分硝酸型酸雨和硫酸型酸雨。

  • 木棉花的花语是什么(木棉花的意义)

    接下来我们就一起去了解一下吧!珍惜眼前的幸福,珍惜身边的人给他们快乐与幸福。它的花期通常在3月或者4月份,在这一段时间盛开,而传说中四月的第十一天,是木棉花盛开的日子,所以4月11被定为木棉花的日子。

  • 炒凉皮不碎技巧(炒凉皮不碎有什么技巧)

    以下内容大家不妨参考一二希望能帮到您!炒凉皮不碎技巧炒凉皮不碎技巧:就是在做凉皮时不能炒太久,变软会失去筋度。胡萝卜切丝,蒜薹切段,葱切花,猪肉切丝,大蒜拍扁。成品凉皮一张张卷起切粗条,抖散备用。生抽,白糖,盐,鸡精,醋,胡椒粉调成汁备用。热锅倒适量食用油烧热加入大蒜,肉丝翻炒至金黄,加入胡萝卜丝和蒜薹炒熟,凉皮翻炒均匀后随即淋入调好的汁儿翻炒均匀。

  • 近几年灭绝的鱼(瞭望在长江源寻鱼)

    长江被誉为我国淡水渔业的摇篮、鱼类基因的宝库。据青海省渔业部门统计,长江流域青海段分布有土著鱼类21种。因此,严格意义上长江源的关键鱼类指的是裂腹鱼中的小头裸裂尻鱼。2019年,李伟带领团队参加长江源科考时,将小头裸裂尻鱼列为长江源鱼类研究的代表对象。2019年4月,科考小组五个人,两台车,开始了沿河寻觅之旅。“全球平均气温上升已是科学界的共识,位于青藏高原的长江源是全球气候变化的敏感区。”科考发现,江源地区

  • 鹧鸪在什么时候季节鸣叫(鹧鸪的孵化期有多长)

    鹧鸪在什么时候季节鸣叫鹧鸪一般会在繁殖季节鸣叫,繁殖期为3-6月,3-4月间开始求偶交配。求偶期间鸣叫更为频繁,常在山岩、树桩、灌木或乔木枝上鸣叫,尤以黎明和黄昏时更甚,往往是一鸟先鸣叫,其他雄鸟一起跟随,此起彼伏。鹧鸪的孵化期在21天左右,雏鸟出壳后不久即可跟随亲鸟活动。鹧鸪的繁殖期为每年的3-6月,3-4月间开始求偶交配,每窝产卵3-6枚,多时可达8枚,卵为椭圆形或梨形,颜色为淡皮黄色至黄褐色。

  • 秋天的诗词(这些都是关于秋天的诗句)

    迢迢新秋夕,亭亭月将圆《戊申岁六月中遇火》,今天小编就来说说关于秋天的诗词?《戊申岁六月中遇火》自古逢秋悲寂寥,我言秋日胜春朝。《秋词》是处红衰翠减,苒苒物华休。惟有长江水,无语东流。宋·柳永《八声甘州》落时西风时候,人共青山都瘦。《昭君怨》雨色秋来寒,风严清江爽。《酬裴侍御对雨感时见赠》秋声万户竹,寒色五陵松。唐·李颀《望秦川》秋色无远近,出门尽寒山。宋·苏轼《九日次韵王巩》

  • 广州有几种车牌(广州车牌你有吗)

    在广州的普通上班族,有房贷还想拥有一辆车,已经不容易了。但有车想让个广州牌,那更是难上加难,再加之限行,参与摇号,竞价的人是越来越多,那中标的机会更是渺茫了!截止日期是8日24时止。9月拟配置的中小客车增量指标共16313个,是这样分配的:1.以摇号方式向单位和个人配置节能车增量指标7285个,其中,单位指标100个,个人指标7185个。

  • qq注销账号有哪几个步骤(QQ将开注销帐号功能)

    1999年2月10日,一个名为OICQ、只有几百K的软件正式上线。当时,腾讯方面表示,这是QQ团队对帐号注销功能的灰度测试。网友截图出于安全考虑,也有网友表示支持有人说,QQ不推出注销服务有自己的考虑,这是为了防止用户QQ密码被他人知道后恶意注销,给用户带来无法挽回的损失。腾讯2018年第三季度财报显示,QQ智能终端月活跃账户同比增长6.9%至6.979亿。

  • 高跟鞋不合脚怎么办(穿高跟鞋不合脚怎么办)

    4、合理利用袜子,如果不喜欢垫各种鞋垫的朋友,可以穿一双船袜,再穿高跟鞋,那样既不影响穿着效果,也不影响美观,也是比较简单和实用的方法。

  • 年四旺名字打分104分 年四旺事迹

    文章目录:一、年四旺相关名字打分113二、年四旺相关名字评分115三、年四旺相关名字推荐四、年四旺相关名字大全五、其他人还看了一、年四旺相关名字打分113年灯石志明年橘纪红兵武尊道后书法孔多塞年贷款孙敬媛年立秋里蓝业珍冯景华年见朱诗词林于思冯桂年粤日林格孟昭毅年家薛邑马布鱼鲁初雪苏沫沫卜庆中年上年掌柜秦源达刘登龙严学锋国韵酒年线高成江裘梦年维泗红沙日年周王克斌王翔千毛淑红龙威信李万和年神范小慧王大