首页 > 其他分享 >[软件测试] sonar 常见问题及修复思路

[软件测试] sonar 常见问题及修复思路

时间:2022-12-06 09:22:05浏览次数:79  
标签:常见问题 return 修复 orElseThrow null localAddress sonar localHostname 软件测试

1 sonar 常见问题及修复思路

1.1 空指针

  • 问题描述

A "NullPointerException" could be thrown; "localAddress" is nullable here.

问题代码[样例]

// 本地(服务器本机)信息
InetSocketAddress localAddress = null;
localAddress = request.getLocalAddress();
String localHostname = null;
localHostname = localAddress.getHostName();
if(StringUtils.isEmpty(localHostname)){
    localHostname = "";
}
if(localAddress != null){
    log.debug(String.format("[4] request-local-host-info: <host:%s, port:%s>", localHostname, localAddress.getPort()));// <host:0:0:0:0:0:0:0:1, port:18100>
}
  • 修复思路

先判断或者先实例化,再访问里面的属性或者成员。

修复代码[样例]

// 本地(服务器本机)信息
InetSocketAddress localAddress = null;
String localHostname = null;
localAddress = request.getLocalAddress();
if(!ObjectUtils.isEmpty(localAddress)){
    localHostname = localAddress.getHostName();
    log.debug(String.format("[4] request-local-host-info: <host:%s, port:%s>", localHostname, localAddress.getPort()));// <host:0:0:0:0:0:0:0:1, port:18100>
}
if(StringUtils.isEmpty(localHostname)){
    localHostname = "";
}

1.2 Optional...orElseThrow()

  • 问题描述

The return value of orElseThrow must be used.

问题代码[样例]

Optional.ofNullable(object).orElseThrow(() -> {
	return new BusinessException("AuthRequestParametersValidator Oject is null!");
});
  • 修复思路

我假设这是一个警告(不使用orElseThrow()返回的值不应该是一个错误)。如果您希望消除该警告,请使用isPresent()代替:

if (!itemList.stream().filter(i->orderItemId.equals(i.getId())).findAny().isPresent()) {
    throw new BadRequestException("12345","Item Not Found");
}
 
// 或只是避免使用Optional s,而是使用anyMatch()代替:  
if (!itemList.stream().anyMatch(i->orderItemId.equals(i.getId()))) {
    throw new BadRequestException("12345","Item Not Found");
}

修复代码[样例]

if(!Optional.ofNullable(object).isPresent()){
    throw new BusinessException("AuthRequestParametersValidator Oject is null!");
}

X 参考文献

标签:常见问题,return,修复,orElseThrow,null,localAddress,sonar,localHostname,软件测试
From: https://www.cnblogs.com/johnnyzen/p/16954252.html

相关文章