I have a method which calls an Action<string>
public Action<string> DisplayError;
public void MyMethod()
{
DisplayError("ERROR");
}
In this method I want to call DisplayError however I can see that if DisplayError is null it will thrown an exception.
I can run a test that proves that it will throw an exception.
So I know I want to add a if (DisplayError != null) to my code but I feel this design is wrong somehow. Maybe the test should be different?
Rather than making Action a public field, make it a property or pass it into the method. You can then do the null checking at that point. I also doubt that you need to retrieve it after setting it, so either:
Or:
The first of these shouldn’t require any code changes from your consumers.
Of course, if you’re just working with a team who are using your code, you shouldn’t need to null-check at all. Just find out who’s using your code wrong and have a friendly chat to work out where the misunderstanding is. Defensive programming is not a good substitute for a team whose members trust each other, and null-checking is not as effective as having a clearly defined, easy-to-use interface.
You’ll need 2 tests:
My class: