Why PMD give me law of demeter violation in this get function?

593 views Asked by At

I am using IntelliJ PMD plugin, and it gives me LOD violation, on the if(keys[i].equals(key)). Keys is an object in the same class within the function.

public Object get(Object key) {
    int n,i;
    for(i=0,n=0;i<keys.length;i++) {
        if(n >= nelems)
            break ;
        if ( keys[i] == null )
            continue;
        if(keys[i].equals(key))
            return values[i] ;
        n++ ;
    }
    return null;
}

You can find the whole code here : https://raw.githubusercontent.com/Sable/abc/master/benchmarks/Jigsaw/src/classes/org/w3c/util/ArrayDictionary.java

1

There are 1 answers

0
Linus Fernandes On

If you don't wish to have this flagged as an error, you can wrap the the indexed field keys[i] as new String(keys[i]) and call the equals function on this new object. This ugly hack will defeat the rule.

However, a better solution , in my opinion, is to filter base classes such as String, Integer, Long etc from this rule. Secondly, immutable classes should also be exempt from this rule. An annotation @Immutable can be used to achieve this. This would have to be implemented by the PMD team.

Another option would be to define the rule by class boundaries rather than object boundaries. If a method returns an object of the same class or a primitive class, that object is not to be counted. If a primitive type, it must be immune from application of the rule.

This method chaining piece of the rule becomes tiresome otherwise.