Coding: Invariant checking on dependency injected components
I’ve written a couple of times previously about invariant checking in constructors and I had an interesting discussion with some colleagues recently around doing this type of defensive programming when the object in question has its dependencies injected by a container.
Quite often we would see code similar to this in a controller:
public class SomeController
{
public SomeController(Dependency1 valueOne, Dependency2 valueTwo)
{
AssertThat.isNotNull(valueOne);
AssertThat.isNotNull(valueTwo);
// and so on
}
}
Where 'SomeController' would have 'Dependency1' and 'Dependency2' set up in a Spring configuration file in this example.
I can’t really see much benefit in this type of pre condition checking although Raph pointed out that if we got the configuration for this bean wrong then having these assertions would allow us to get quicker feedback.
While that is true it seems to me that we would maybe achieve quicker feedback by a few seconds in return for the clutter that we end up creating in our code. We have to read those assertions every time we come to this class.
I would prefer to have some specific tests for the dependency injection container if we’re interested in getting quick feedback in that area.
That seems to be a cleaner solution than having these types of checks in production code or am I missing something?
About the author
I'm currently working on short form content at ClickHouse. I publish short 5 minute videos showing how to solve data problems on YouTube @LearnDataWithMark. I previously worked on graph analytics at Neo4j, where I also co-authored the O'Reilly Graph Algorithms Book with Amy Hodler.