Pre-check
- [x] I am sure that all the content I provide is in English.
Search before asking
- [x] I had searched in the issues and found no similar feature requirement.
Apache Dubbo Component
Java SDK (apache/dubbo)
Descriptions
Key Reasons to Avoid Method Calls in Constructors
- Incomplete Object Initialization: When a constructor calls other methods, those methods may execute before the object is fully initialized, leading to potential NullPointerExceptions or inconsistent states.
- Inheritance Issues: If the called method is overridden by a subclass, the subclass version will execute before the subclass constructor completes, violating the expected initialization order.
- Reduced Code Clarity: Constructors should focus solely on initialization. Adding method calls makes the code harder to understand and maintain.
- Testing Difficulties: Methods called during construction make unit testing more complex, as you can't test the constructor independently from those methods.
Better Alternatives Instead of calling methods in constructors:
- Initialize fields directly
- Use factory methods
- Implement lazy initialization
- Apply the Initialization-on-demand holder idiom for singletons
Example of Problematic Code
public abstract class AAA {
public AAA() {
initialize();
}
protected void initialize();
}
public class BBB extends AAA {
private final Object myFinal = new Object();
public BBB() {
super();
}
@Override
public void initialize() {
new Thread(() -> {
// The assertion might fail because myFinal isn't initialized during running BBB construction.
Assertions.assertNotNull(myFinal);
}).start();
}
}
Help Wanted Keeping constructors simple and focused on field initialization to create more maintainable and reliable code that properly follows object-oriented principles.
Related issues
Are you willing to submit a pull request to fix on your own?
- [ ] Yes I am willing to submit a pull request on my own!
Code of Conduct
- [x] I agree to follow this project's Code of Conduct
Comment From: wcy666103
I'm working on it.