Search code examples
javasonarqubepmdcode-duplication

Avoid duplicate code in POJO Class


Let's say we have 3 classes: A, B and C. Each class has the others in parameter. Like this: EDIT:

 +-----+  +-----+  +-----+
 |  A  |  |  B  |  |  C  |
 -------  -------  -------
 | X x |  | X x |  | Z z |
 | Z z |  | Y Y |  | Y y |
 -------  -------  -------

Getters and setters will be duplicated. So, is it a bad practice and should we avoid this ? Or does this should not be took as duplication code by code analyzers (eg. PMB) ?

I have thought about "strategy pattern", but I think it's maybe too much, just for getters and setters ...

EDIT : My first question is maybe not really clear. The question is if we have two classes (not linked) with a common attribut and exactly the same getter/setter. Sonar or PMD should consider these methods as duplicated code or not ? And if not, will it be fixed ?


Solution

  • As already noted, first consider whether you really need the duplication. Maybe they should be in a common object that gets passed around. Maybe they aren't needed.

    Now lets assume they really are needed. Which can be the case of course. PMD's copy paste detector lets you set the minimum number of lines before it counts as a duplicate. Since a getter/setter is only three lines each (or 6 for both), you could set the threshold just above there.