-
Notifications
You must be signed in to change notification settings - Fork 2k
Expand file tree
/
Copy pathInitCallsSubclassMethod.qhelp
More file actions
42 lines (34 loc) · 2.08 KB
/
InitCallsSubclassMethod.qhelp
File metadata and controls
42 lines (34 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE qhelp PUBLIC
"-//Semmle//qhelp//EN"
"qhelp.dtd">
<qhelp>
<overview>
<p>
When initializing an instance of the class in the class' <code>__init__</code> method, calls tha are made using the instance may receive an instance of the class that is not
yet fully initialized. When a method called in an initializer is overridden in a subclass, the subclass method receives the instance
in a potentially unexpected state, which may lead to runtime errors from accessing uninitialized fields, and generally makes the code
more difficult to maintain.
</p>
</overview>
<recommendation>
<p>If possible, refactor the initializer method such that initialization is complete before calling any overridden methods.
For helper methods used as part of initialization, avoid overriding them, and instead call any additional logic required
in the subclass' <code>__init__</code> method.
</p><p>
If calling an overridden method is required, consider marking it as an internal method (by using an <code>_</code> prefix) to
discourage external users of the library from overriding it and observing partially initialized state.
</p>
</recommendation>
<example>
<p>In the following case, the `__init__` method of `Super` calls the `set_up` method that is overriden by `Sub`.
This results in `Sun.set_up` being called with a partially initialized instance of `Super` which may be unexpected. </p>
<sample src="examples/InitCallsSubclassMethodBad.py" />
<p>In the following case, the initialization methods are separate between the superclass and the subclass.</p>
<sample src="examples/InitCallsSubclassMethodGood.py" />
</example>
<references>
<li>CERT Secure Coding: <a href="https://www.securecoding.cert.org/confluence/display/java/MET05-J.+Ensure+that+constructors+do+not+call+overridable+methods">
Rule MET05-J</a>. Reference discusses Java but is applicable to object oriented programming in many languages.</li>
<li>StackOverflow: <a href="https://stackoverflow.com/questions/3404301/whats-wrong-with-overridable-method-calls-in-constructors">Overridable method calls in constructors</a>.</li>
</references>
</qhelp>