I’m using constructor injection for the first time and wish to write my code defensively.
Therefore if I have a class with a constructor and a save method as below:
public SomeConstructor(string name, Object someObject)
{
_name= name;
_someObject= someObject;
}
public void Save()
{
// Does a database save
}
But then need to create another related method in this Class that doesn’t need the _someObject so I create an overloaded chained constructor as:
public SomeConstructor(string name) : this(name, null)
{
}
How can I successfully stop someone instantiating the class with this second constructor with 1 parameter and using the Save() which has someObject as null?
I’m not using an injection tool.
Above is a simple example and in it, you are correct I could just throw an exception for a null just as I would if a property was not set.
What I wanted to avoid was a series of validation checks at the start of each method.
Use the friction you are experiencing as a warning system. It’s really telling you that you’re likely moving towards low cohesion and violation of the Single Responsibility Principle.
If this is the case, refactor the class into two separate classes.