I always think that a method should always ensure that its dependencies are not null (unless they inject nullability in the constructor and constructor).
For example, if I have a method
public void SendMessage(IEmailSender emailSender, contactList list)
{
if(emailSender == null)
{
throw new ArgumentNullException("Failed to send
message.",MethodBase.GetCurrentMethod().GetParameters[0].Name);
}
if(list == null)
{
throw new ArgumentNullException("Failed to send
message.",MethodBase.GetCurrentMethod().GetParameters[1].Name);
}
// rest of code goes here
}
Am I missing something?
For example, instead of
if(log != null)
log. Write("My log message");
You can instead create an ILogger interface that contains the Write method, and create two classes that implement this interface: NullLogger and FileLogger. NullLogger will implement the Write method Provide an empty body.
In my opinion, this is different from the explicit precondition verification you have in the example
I am reading today Uncle Bob’s book on exception handling, and what I can recall from handling null values is that methods should not handle null values, because it will mess up the code. I am a bit confused.
I always think that a method should always ensure Its dependencies are not null (unless they inject nullability in the constructor and the constructor).
For example, if I have a method
public void SendMessage(IEmailSender emailSender, contactList list)
{
if(emailSender == null)
{
throw new ArgumentNullException("Failed to send
message." ,MethodBase.GetCurrentMethod().GetParameters[0].Name);
}
if(list == null)
{
throw new ArgumentNullException("Failed to send
message.",MethodBase.GetCurrentMethod().GetParameters[1].Name );
}
// rest of code goes here
}
Am I missing something?
I haven’t read this book yet, but I can only imagine Uncle Bob who advocates using the Null Object Pattern in preference to explicit null reference handling.
For example, instead of
if(log != null)
log.Write("My log message");
You can instead create an ILogger interface that contains the Write method, and create two classes that implement this interface: NullLogger and FileLogger. NullLogger will provide an empty body for the implementation of the Write method.
In my opinion, this is different from your explicit precondition verification in your example