SonarQube complains about using ResponseEntity with a wildcard

荒凉一梦 提交于 2019-12-11 07:37:19

问题


I use SpringBoot for REST web services development and SonarQube for static analysis.

I have a few endpoints in my application that look the following way:

@PostMapping
ResponseEntity<?> addSomething(@RequestBody Some object) {
    // some code there
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

SonarQube complains about using ResponseEntity with a wildcard, reporting me a Critical issue "Generic wildcard types should not be used in return parameters".

I wonder if I should disable this verification in SonarQube or come up with something different for return type for these cases.

What do you think about it?


回答1:


Finally I've removed <?> from return value, so the code looks like the following now:

@PostMapping
ResponseEntity addSomething(@RequestBody Some object) {
    // some code there
    return new ResponseEntity<>(HttpStatus.NO_CONTENT);
}

SonarQube doesn't complain anymore and code seems a little bit simpler now.




回答2:


So actually i find the rule pretty self describing:

Using a wildcard as a return type implicitly means that the return value should be considered read-only, but without any way to enforce this contract.

Let's take the example of method returning a "List". Is it possible on this list to add a Dog, a Cat, ... we simply don't know. The consumer of a method should not have to deal with such disruptive questions.

https://sonarcloud.io/organizations/default/rules#rule_key=squid%3AS1452

So Actually in your case, you do not want any kind of Class in there, you specifically want an Serializable-object - for obvious reasons: it should be serialized later on

So instead of using ? it would be more suitable in your case to use Serializable. This is always case dependent, but normally you definitly expect some kind of common interface or base class as a return value. Hence that, the follow up developer, definitly knows what he can expect, and what kind of functionality he definitly can use.



来源:https://stackoverflow.com/questions/44974384/sonarqube-complains-about-using-responseentity-with-a-wildcard

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!