I was looking through the Orchard CMS Project source code and I noticed that some of their constructors never verify that the required parameter is not null. At first, I thought this was odd. I asked my self, "Considering that you're saying this dependency is required, wouldn't you want to check that you actually have one?" Realizing that the project uses Castle Windsor as an IoC container, I later then thought, "Well, the container would have thrown the exception when it tried to find the dependency for the object that had the requirement." So my question stands, should I still check when I know that an IoC container will check for me?
Or is the double check good because I'm, in a sense, adhering to a reverse encapsulation principle stating: "I don't know how I'm getting this dependency, but I really need one!"
What is it? Inversion of Control (IoC) means to create instances of dependencies first and latter instance of a class (optionally injecting them through constructor), instead of creating an instance of the class first and then the class instance creating instances of dependencies.
I've been led to follow the practice of checking every visible parameter for NULL regardless of how it's been designed to be instantiated. There's always a chance that someone will choose a different IoC container that enforces a more loose type delegation policy or some junior developer finds your code and hopes it'll work the way they want.
Either way, better safe than sorry. In this case better spend a couple seconds guarding the code then hours when someone decides to use it as unintended.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With