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

前端 未结 5 1728
长发绾君心
长发绾君心 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:52

    I would design my classes in a way so that an "init" method is not required. I think that all methods of a class, and especially public methods, should guarantee that the object is always left in a "valid" state after they complete successfully and no call to other methods is required.

    The same holds for constructors. When an object is created, it should be considered initialized and ready to be used (this is what constructors are for and there are numerous tricks to achieve this). Otherwise, the only way that you can safely use it is checking if the object has been initialized in the beginning of every other public method.

提交回复
热议问题