如果使用依赖注入,那么构造函数有很多参数是完全正常的。
sonarlint是否有可能没有显示太多参数"使用注射的构造函数的代码气味警告?
答案 0 :(得分:1)
就我而言,Spring服务需要大量其他服务才能完成其工作。因此,规则squid:S00107
被解雇,并在SonarCube中给了我一个错误。我发现this article提议使用Lombok来解决该问题,如下所示:
之前:
@Component
public class EventService {
private final String param1;
private final String param2;
private final String param3;
private final String param4;
private final String param5;
private final String param6;
private final String param7;
private final String param8;
private final String param9;
public EventService(String param1, String param2, String param3, String param4, String param5, String param6, String param7, String param8, String param9) {
this.param1 = param1;
this.param2 = param2;
this.param3 = param3;
this.param4 = param4;
this.param5 = param5;
this.param6 = param6;
this.param7 = param7;
this.param8 = param8;
this.param9 = param9;
}
...
之后:
@Component
@RequiredArgsConstructor
public class EventService {
private final String param1;
private final String param2;
private final String param3;
private final String param4;
private final String param5;
private final String param6;
private final String param7;
private final String param8;
private final String param9;
...
答案 1 :(得分:0)
正如其他张贴者所指出的那样,方法或构造函数的过多参数表明,某种程度上违反了关注点分离原则。最好采用以下解决方案:
这避免了参数的混淆,即“ x,y或z是第一个参数?”
如果所有尝试均失败,则在要忽略的方法/构造函数的顶部注释@SuppressWarnings("squid:S00107")
。这只能是最后的资源。