Flaw: Constructor does Real Work

前端 未结 6 1634
伪装坚强ぢ
伪装坚强ぢ 2020-12-17 04:15

I have a class which represents a set of numbers. The constructor takes three arguments: startValue, endValue and stepSize. The class

6条回答
  •  难免孤独
    2020-12-17 04:50

    It's not a good practice to do "real work" in the constructor: you can initialize class members, but you shouldn't call other methods or do more "heavy lifting" in the constructor.

    If you need to do some initialization which requires a big amount of code running, a good practice will be to do it in an init() method which will be called after the object was constructed.

    The reasoning for not doing heavy lifting inside the constructor is: in case something bad happens, and fails silently, you'll end up having a messed up object and it'll be a nightmare to debug and realize where the issues are coming from.

    In the case you describe above I would only do the assignments in the constructor and then, in two separate methods, I would implement the validations and generate the string-information.

    Implementing it this way also conforms with SRP: "Single Responsibility Principle" which suggests that any method/function should do one thing, and one thing only.

提交回复
热议问题