rspec/rules/S1699/java/rule.adoc
2023-06-09 11:07:55 +02:00

48 lines
1.4 KiB
Plaintext

== Why is this an issue?
Calling an overridable method from a constructor could result in failures or strange behaviors when instantiating a subclass which overrides the method.
For example:
* The subclass class constructor starts by contract by calling the parent class constructor.
* The parent class constructor calls the method, which has been overridden in the child class.
* If the behavior of the child class method depends on fields that are initialized in the child class constructor, unexpected behavior (like a `NullPointerException`) can result, because the fields aren't initialized yet.
=== Noncompliant code example
[source,text]
----
public class Parent {
public Parent () {
doSomething(); // Noncompliant
}
public void doSomething () { // not final; can be overridden
...
}
}
public class Child extends Parent {
private String foo;
public Child(String foo) {
super(); // leads to call doSomething() in Parent constructor which triggers a NullPointerException as foo has not yet been initialized
this.foo = foo;
}
public void doSomething () {
System.out.println(this.foo.length());
}
}
----
== Resources
* https://wiki.sei.cmu.edu/confluence/x/8zZGBQ[CERT, MET05-J.] - Ensure that constructors do not call overridable methods
* https://wiki.sei.cmu.edu/confluence/x/6ns-BQ[CERT, OOP50-CPP.] - Do not invoke virtual functions from constructors or destructors
include::../rspecator.adoc[]