Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

This rule is closely related to MET04-J. Ensure that constructors do not call overridable methods.

Noncompliant Code Example

This noncompliant code example shows two classes, BadClone and Sub. The class BadClone calls an overridable method doSomething(). The overridden method sets the value of the cookies; the overriding method sets the values of the domain names. The doSomething() method of the subclass Sub is erroneously executed twice at runtime because of polymorphism. The first invocation comes from BadClone.clone(), and the other comes from Sub.clone(). Consequently, the cookies never get their values initialized, while their domains are initialized twice.

...

If an overridable method is invoked on a shallow copy of the object, the original object is also modified.

Compliant Solution

This compliant solution declares both the doSomething() and the deepCopy() methods final, preventing overriding of these methods.

...

Alternative solutions that prevent invocation of overloaded methods include declaring these methods private, declaring the class final, or eliminating the method calls by congregating the code.

Risk Assessment

Calling overridable methods on the clone under construction can expose class internals to malicious code or violate class invariants by exposing the clone to trusted code in a partially initialized state, affording the opportunity to corrupt the state of the clone, the object being cloned, or both.

Rule

Severity

Likelihood

Remediation Cost

Priority

Level

MET07-J

medium

probable

low

P12

L1

Automated Detection

Automated detection appears to be straightforward.

Related Vulnerabilities

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

Other Languages

This rule appears in the C++ Secure Coding Standard as ARR40-CPP. Use a valid ordering rule.

Bibliography

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="24537493a2fc75cf-51b5b6a9-450e4dc3-8ced94b8-a1153cc4e38aa93581b7b04f"><ac:plain-text-body><![CDATA[

[[Bloch 2008

AA. Bibliography#Bloch 08]]

Item 11: Override clone judiciously

]]></ac:plain-text-body></ac:structured-macro>

<ac:structured-macro ac:name="unmigrated-wiki-markup" ac:schema-version="1" ac:macro-id="ca7f34f4a9e4abaf-e72799f9-4af84734-9545aa4d-d508269e8c19e158ccf9c53c"><ac:plain-text-body><![CDATA[

[[Gong 2003

AA. Bibliography#Gong 03]]

 

]]></ac:plain-text-body></ac:structured-macro>

...