How much code should one put in a constructor?

前端 未结 9 2202
一整个雨季
一整个雨季 2020-12-15 05:34

I was thinking how much code one should put in constructors in Java? I mean, very often you make helper methods, which you invoke in a constructor, but sometimes there are s

9条回答
  •  感情败类
    2020-12-15 06:14

    My customary practice is that if all the constructor has to do is set some fields on an object, it can be arbitrarily long. If it gets too long, it means that the class design is broken anyway, or data need to be packaged in some more complex structures.

    If, on the other hand, the input data need some more complex processing before initializing the class fields, I tend to give the constructor the processed data and move the processing to a static factory method.

提交回复
热议问题