0

I have a class A in external library. this class A has 27 fields in one level. we use this class to generate json format. and the json tree is very straight.

{
 "field1":"value",
 "field2":"value",
...}

I would need to add one more field, field27 on the same level. so I created class B extends A and added one more field and it's working fine. However, Sonar scan raised major issue saying that too many parameters in constructor which I have to fix.

public class B extends A {
  private String field27;
  public B(String field1,...field26, field27){
   super(field1,...field26);
   this.field27 = field27;
}

I cannot create B like below as it generates json in different structure.

public class B {
 private A a;
 private String field27;
 public B(A a, String field27){
  this.a = a;
  this.field27 = field27;
 }
}

{
  A:{
   "field1":"value",
    "field2","value",
     ... 
   },
   "field27":"value"
}

Class A is very simple class and doesn't provide any other constructor with subset of parameters. I've tried

public class B extends A {
 private String field27;
 public B(Class a, String field27){
  super(a.getField1(),...);
  this.field27 = field27
 }
}

but found that this class A does not have expected getFieldX() for all columns... so now option I have is

public class B extends A {
 private String field27;
public B(A a, ZonedDateTime field2, Level field3, String field27){
 super(a.getField1(),field2, field3, a.getField4(), a.getField26());
 this.field27 = field27;
 }
}

this code serves what is needed but code is confusing as I pass A and then subset of A as parameters. Is there any other better approach to solve this problem?

Thanks!

Julia
  • 133
  • 11

1 Answers1

0

If "A" has an Interface you can try to have "B" code to that instead of mucking with A.

Code scanners and code scanning configs are opinionated, but unlike the laws of physics, you can and should be allowed to "break" the rules if you feel you're in a space where the rule doesn't apply.

That said, given that A is clearly just a large value object with a large constructor, it may be a better use of your time learning how to tell Sonar to ignore the file specifically (i.e. with an annotation or something) so you can go back to what worked for you and was simple.

Or if you just want to try something fancy, maybe Lombok @Delegate? I used that once and it was kind of nifty, but a bit rigid in how it worked for my needs. Might work for you.

https://projectlombok.org/features/experimental/Delegate

Atmas
  • 2,389
  • 5
  • 13