Should a Perl constructor return an undef or a “invalid” object?

后端 未结 4 1728
南旧
南旧 2021-02-14 10:06

Question:

What is considered to be \"Best practice\" - and why - of handling errors in a constructor?.

\"Best Practice\" can b

4条回答
  •  执念已碎
    2021-02-14 10:44

    I prefer:

    1. Do as little initialization as possible in the constructor.
    2. croak with an informative message when something goes wrong.
    3. Use appropriate initialization methods to provide per object error messages etc

    In addition, returning undef (instead of croaking) is fine in case the users of the class may not care why exactly the failure occurred, only if they got a valid object or not.

    I despise easy to forget is_valid methods or adding extra checks to ensure methods are not called when the internal state of the object is not well defined.

    I say these from a very subjective perspective without making any statements about best practices.

提交回复
热议问题