Each article in the Practice category focuses on a bad development practice detected by Kalistick’s Cockpit.
Calling a derivable internal method (not final in Java, or virtual in C#) from the class constructor is a risky practice. If the method is overloaded, inconsistencies or even errors may arise.
The intrinsic reasons for these errors are closely related to the object instantiation processes in the C# and Java languages, particularly when executing parent constructors before initializing the fields in the child class.
Example:
MyWindow.java
public class MyWindow
{
public MyWindow()
{
/* ... */
buildUI();
}
public void buildUI()
{
/* ... */
}
}
MyExtendedWindow.java
public class MyExtendedWindow extends MyWindow
{
private MyComponent component;
public MyExtendedWindow()
{
this.component = new MyComponent();
}
public void buildUI()
{
super.buildUI();
component.setWidth(800);
}
}
The buildUI method in the MyWindow class is derivable and called in the constructor for the MyWindow class.
The MyExtendedWindow class extends MyWindow and overloads the buildUI method in order to add processing to these fields.
When instantiating an object in the MyExtendedWindow class, the order of execution will be as follows:
- Initialize the fields in the
MyWindowclass (declaration). - Execute the constructor for the
MyWindowclass. - Execute the
buildUImethod in theMyExtendedWindowclass (overload). - Initialize the fields in the
MyExtendedWindowclass (declaration). - Execute the constructor for the
MyExtendedWindowclass.
The instantiation will result in a nullity exception (in 3) since the setWidth method in MyComponent is called before the component object is initialized, which will be in 5. Here, the error is obvious. In other circumstances, the symptoms might not be as obvious, making the diagnostic much more time consuming!
Possible corrections:
- Declare the non-derivable or private
buildUImethod at theMyWindowlevel so that it can no longer be overloaded. - Remove the
buildUImethod from theMyWindowconstructor and explicitly call it after the constructor.
No related posts.
