diff --git a/python/ql/src/Classes/InitCallsSubclass/InitCallsSubclassMethod.qhelp b/python/ql/src/Classes/InitCallsSubclass/InitCallsSubclassMethod.qhelp index 81e16aacd26..55788736b54 100644 --- a/python/ql/src/Classes/InitCallsSubclass/InitCallsSubclassMethod.qhelp +++ b/python/ql/src/Classes/InitCallsSubclass/InitCallsSubclassMethod.qhelp @@ -6,8 +6,9 @@

When initializing an instance of the class in the class' __init__ 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. +in a potentially unexpected state. Fields that would be initialized after the call, including potentially in the subclass' __init__ method, +will not be initialized. This may lead to runtime errors, as well as make the code more difficult to maintain, as future changes may not +be aware of which fields would not be initialized.

@@ -16,14 +17,19 @@ more difficult to maintain.

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' __init__ method. -

-If calling an overridden method is required, consider marking it as an internal method (by using an _ prefix) to -discourage external users of the library from overriding it and observing partially initialized state. +

+

+If the overridden method does not depend on the instance self, and only on its class, consider making it a @classmethod or @staticmethod instead. +

+

+If calling an overridden method is absolutely required, consider marking it as an internal method (by using an _ prefix) to +discourage external users of the library from overriding it and observing partially initialized state, and ensure that the fact it is called during initialization +is mentioned in the documentation.

-

In the following case, the `__init__` method of `Super` calls the `set_up` method that is overriden by `Sub`. +

In the following case, the __init__ method of Super calls the set_up method that is overridden by Sub. This results in `Sun.set_up` being called with a partially initialized instance of `Super` which may be unexpected.

In the following case, the initialization methods are separate between the superclass and the subclass.

@@ -35,7 +41,7 @@ This results in `Sun.set_up` being called with a partially initialized instance
  • CERT Secure Coding: Rule MET05-J. Reference discusses Java but is applicable to object oriented programming in many languages.
  • StackOverflow: Overridable method calls in constructors.
  • - +
  • Python documentation: @classmethod.