I have a line of code looking like this:
String someString = "something";
if (Foo.SOME_CONSTANT_STRING.equals(someString))
which results in a violation: "Potential violation of Law of Demeter (static property access)"
What is the suggested approach here?
(Edit: I changed the code example)
The problem with accessing static variables is that you are enforcing an external state to the class that is hard to test. You should access it via a class variable such as:
private final Foo SOME_CONSTANT = Foo.SOME_CONSTANT_STRING;
public void doSomething(){
String someString = "something";
if (SOME_CONSTANT.equals(someString)){
doTheWave();
}
}
this, with a getter for SOME_CONSTANT, allows to test the "initial state" of the function more precisely.
You should write
if ("hello".equals(Foo.SOME_CONSTANT_STRING))
because as far as PMD can know, Hello is for sure non null when Foo.SOME_CONSTANT_STRING might not be.
Also, check out Wikipedia's page on Law of Demeter for a better understanding of it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With