http://misko.hevery.com/code-reviewers-guide/flaw-constructor-does-real-work/
This blog post talks about why having a constructor do too much work is a bad programming practice. When a constructor instantiates and initializes its collaborators, the result is often inflexible and can shut off the ability to inject test collaborators. The author gives a few reasons why this is a flaw:
- It violates the Single Responsibility Principle – Mixing collaborator construction with initialization suggests that there is only one way to configure the class. Having object graph creation take place in the constructor violates the Single Responsibility Principle
- Testing directly is difficult – If a constructor does a lot of work, you will have to do that work when creating the objects while testing
- Subclassing and overriding to test are still flawed – When you use subclassing you will fail to test the method that you override
- It forces collaborators on you – You don’t always want to create all an object’s collaborators when you test it
Signs that a constructor is doing too much work:
- new keyword in the constructor
- Static method calls in a constructor
- Object not fully initialized after the constructor finishes
- Conditional or looping logic in a constructor
- Complex object graph creation in a constructor rather than using a factory or builder
- Using a initialization block
Fixing the Flaw:
To fix this flaw you should remember to pass collaborators into your constructor rather than create them there. The responsibility for object graph creation and initialization should be moved into another object such as a builder, factory, or provider. These collaborators can then be passed into the constructor.
Overall, the phrase “work in the constructor” means doing anything that makes instantiating your object difficult or introducing test-double objects difficult.
I thought that this blog did a very thorough job of explaining why doing work in a constructor is a flaw that should be avoided. It did a good job explaining why it is a flaw, recognizing when it is happening, and explaining various methods to fix it. There are also a lot of code examples that demonstrate the problem more concretely and show how it can be fixed. After reading this blog I now have a better understanding of what should and should not be included in a constructor. This blog also introduced me to some new object-oriented programming concepts that are too specific to be covered in the classroom. Overall I thought this blog was very informative and I expect to use what I have learned in future programming projects.
From the blog CS@Worcester – Computer Science Blog by rydercsblog and used with permission of the author. All other rights reserved by the author.