What are the best practices for determining the tasks of Constructor, Initialization and Reset methods

前端 未结 5 1681
长发绾君心
长发绾君心 2021-01-22 08:38

This is a general OOP question although I am designing in Java. I\'m not trying to solve a particular problem, just to think through some design principles.
From my experien

5条回答
  •  野的像风
    2021-01-22 08:54

    Is there a reason init() and reset() need to be different? It's hard to see in this simple example why the "does not instantiate anything" rule is important.

    Beyond that, I think objects should be useful as soon as they're constructed. If there's a reason -- some circular dependency or inheritance issue -- an object has to be "initialized" after construction, I would hide the constructor and the initialization behind a static factory method. (And probably move the initialization code to a separate configurator object for good measure.)

    Otherwise you're counting on callers always to call both the constructor and init(), and that's a non-standard pattern. We have some old, too-useful-to-throw-away code here that does that; it's an abstract dialog class, and what happens is, every time someone extends it, they forget to call constructUI() and then they waste 15 minutes wondering why their new dialog is empty.

提交回复
热议问题