Let's say I have a method public void Foo(string bar) that the caller should not call with a null value of bar. Let's say I also have a method, call it private void FooImpl(string bar), that does the actual work of Foo. It's, of course, FooImpl that really requires non-nullness of bar, even though Foo is the public interface. And lets say I want to enforce this non-nullness using the .NET 4.0 code contracts.
Where do I put the contract?
If I do this:
public void Foo(string bar)
{
this.FooImpl(bar);
}
private void FooImpl(string bar);
{
Contract.Requires<ArgumentNullException>(bar != null);
// Something that requires non-nullness, e.g.:
bar.Contains("test");
}
then the static checker complains that Foo is calling FooImpl with a possibly-null value, and suggests I add the non-null contract to Foo. OK, so I guess I can't delegate my contract-checking/exception-throwing to the implementation methods.
But if I try to put it in the public interface, i.e.:
public void Foo(string bar)
{
Contract.Requires<ArgumentNullException>(bar != null);
this.FooImpl(bar);
}
private void FooImpl(string bar);
{
bar.Contains("test");
}
then the static checker complains that FooImpl is calling Contains on a possibly-null value---even though the only place from which FooImpl is ever called in the code is from Foo, which itself ensures that it will never call FooImpl with a null value.
So, do I need to include the same contract twice? Or should I just ignore the static checker? I know it's kind of a source of busywork and shouldn't be relied upon, but I would hope that it had some way of handling this basic, and presumably common, scenario.