Currently I am finishing reading the book Dependency Injection in .NET from Mark Seemann. The really good thing about this book is, that it assigns names to DI patterns as well as anti-patterns. My own reflection on the topics covered in the book brought up a simple (maybe provoking) thesis:
Occurrences of the new operator most likely have a smell.
Everytime I “new” up an instance I create a very strong dependency upon a concrete implementation. Although this is common knowledge and nothing special in itself, it is practiced day by day – producing tightly coupled code. This is why I consider occurrences of the new operator a code smell.
Dependency injection is a well established technique that helps producing loosely coupled code. Since DI and IoC are (imho) advanced concepts, differently skilled developers (which you almost always find in a team) may or may not be familiar with those concepts. So what I was looking for is a rule-of-thumb that supports the ultimate goal of getting a team of developers with very different skills write loosely coupled code (and maybe not even recognizing it at first).
I am almost sure I found this rule, because it is so damn simple:
Do not use the new operator.
The best thing about this rule is that I can make my static code analysis recognize and find it. Having set up a CI server performing static code analysis for me, the only work left is analyzing the findings.
I can then discuss the findings in peer reviews, refine my rules when using the “new” operator is indeed a good thing and start collecting statistical data on problem “hot spots” which I can use to find and develop skill improvement strategies (e.g. trainings).
But one of the most important advantages I see when applying this in practice is the boost in communication on a fundamental quality criterium of software systems that often enough decides on project success – a loosely coupled modular design.
In conclusion I can say that the rule itself is indeed very restrictive, since there are several situations where using the new operator is perfectly legal, but starting off with this simple rule will all by itself motivate group discussion and contribute to a common understanding. And that’s what I had in mind.
I would really appreciate when you leave a comment and describe your perspective. Do you consider occurrences of the new operator a smell as well or do you totally disagree with me? I am really interested in your opinion!