In object-oriented programming, inappropriately accessing static members of a base class via derived types is considered a code smell.
Static members are associated with the class itself, not with any specific instance of the class or its children classes. Accessing through the
wrong type suggests a misunderstanding of the ownership and role of this member. This can make the maintenance of the code more complicated.
Therefore, the access should be done directly through the base class to maintain clarity and avoid potential misunderstandings.
Noncompliant code example
class Parent {
public static int counter;
}
class Child extends Parent {
public Child() {
Child.counter++; // Noncompliant
}
}
Compliant solution
class Parent {
public static int counter;
}
class Child extends Parent {
public Child() {
Parent.counter++;
}
}