1

I have this DTO class:

class DTO{
    private String a;

    public DTO(String a){
        this.a = a;
    }
}

I am JSON serializing this class using Gson and sending it over to other application.

I don't need getters for this class. For this class sonar is showing following issue:

"Remove this unused "a" private field."

Should I ignore this sonar issue or there is another ideal way to change my code to eliminate this sonar error?

vatsal mevada
  • 4,408
  • 7
  • 33
  • 62
  • 1
    Refer https://stackoverflow.com/questions/12135939/how-to-make-sonar-ignore-some-classes-for-codecoverage-metric to exclude some code coverage – Bhavesh Oct 27 '17 at 09:34

2 Answers2

1

The issue raised by SonarQube is a false positive in this example. Your best course of action is to mark it as such on SonarQube.

If your DTO files follow a consistent naming pattern, then it could also be interesting to configure SonarQube to ignore this issue in those files by default. For more details see the Ignore Issues on Multiple Criteria section in the documentation.

janos
  • 115,756
  • 24
  • 210
  • 226
0

In order to prevent SonarQube false positives for your DTOs you could use AutoValue as a library to create DTOs:

@AutoValue
@AutoGson(autoValueClass = AutoValue_DTO.class)
public abstract class DTO
{
    public abstract String getA();
}

with AutoGson defined as:

@Retention(RetentionPolicy.RUNTIME)
@Target(ElementType.TYPE)
public @interface AutoGson
{
    Class autoValueClass();
}

and a Gson type adapter defined as:

public class AutoValueTypeAdapterFactory implements TypeAdapterFactory
{
    @SuppressWarnings("unchecked")
    @Override
    public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type)
    {
        Class<? super T> rawType = type.getRawType();

        AutoGson annotation = rawType.getAnnotation(AutoGson.class);
        if (annotation == null)
        {
            return null;
        }

        return (TypeAdapter<T>) gson.getAdapter(annotation.autoValueClass());
    }
}

which is used by Gson as:

Gson gson = new GsonBuilder().registerTypeAdapterFactory(new AutoValueTypeAdapterFactory())