开发者

Is it a good practice to call methods from constructors?

Is it a good practice to call methods from constructor开发者_如何学Pythons?


I assume you are talking about other private/public functions of the class which is being initialized.

Like anywhere else, I would say decomposing large complicated behavior into sub functions is good practice.

The obvious complication would be calling functions which rely on as-yet un-initialized content of the object.

Since the constructor and the other functions are in the class have the same visibility (from a code maintainability point of view) I don't think it is unreasonable to say that it is ok to leverage other functions but necessary for the programmer to ensure that such circular dependencies are avoided (like virtual functions).


I sometimes put an init() call in the constructor of my objects if I have lots of other overloaded versions of the constructor that need to initialize the class in the same way. It's DRY.


Not if those methods are virtual. Anyway, just be sure that if your constructor fails (or one of the methods it calls fails) that your constructor does a "catch" to perform a Dispose() on any IDisposables it allocated.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜