Putting Constructors in __init__ is Asking For Trouble

| Comments

One thing I’ve learned when using dependency injection is that initializing one or more class instances in the constructor of another is a sure sign you haven’t separated your interests well.

Miko Hevery has summarized this far better than I’ve ever been able to in his post about how to think about the “new” operator.

In this case, what’s true for Javer is equally true for Python. Many is the time I’ve gotten up the will to write tests for some legacy code, cracked open the module, seen the five or more objects created in init, closed the file up, and quickly walked away.

Invoking constructors for other objects in your constructor is not only bad for testing; it’s bad for maintainability. By putting them in there, you proclaim to the universe “THIS is the type I want to use here, forever and ever, until the sun burns out and the sky falls down. Amen”.

I don’t know too many people willing to commit to something to that degree. Maybe the Pope would.

blog comments powered by Disqus