Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Law of Demeter: Static property access

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)

like image 809
Alix Avatar asked Dec 06 '25 03:12

Alix


2 Answers

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.

like image 70
bunyaCloven Avatar answered Dec 10 '25 20:12

bunyaCloven


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.

like image 38
Seb - SonarSource Team Avatar answered Dec 10 '25 21:12

Seb - SonarSource Team



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!