Reputation: 6592
Assume we have an interface as follows with the contract class
[ContractClassFor(typeof(Custom))]
public abstract class CustomContract : Custom
{
public string GetPerson(int i)
{
Contract.Requires(i > 0);
Contract.Ensures(!String.IsNullOrEmpty(Contract.Result<string>()));
return default(string);
}
public string Name { get; set; }
}
[ContractClass(typeof(CustomContract))]
public interface Custom
{
string GetPerson(int i);
string Name { get; set; }
}
Implementation is like
public class CustomProcessor: Custom
{
public CustomProcessor(ISomeinterface obj, string logname)
{
if(null == obj) throw new ArgumentNullException(...);
...
}
public GetPerson(int I)
{
...
}
}
Does it make sense to replace the throw new ArgumentNullException
in constructor with Contract.Requires(obj != null).
Contracts are supposed to be defined by an interface and since constructor is a part of implementation and not an interface I am leaned towards the current approach. Is that a good practice ?
Upvotes: 2
Views: 508
Reputation: 21244
To get the most out of code contracts, yes, it makes sense to replace the ArgumentNullException
throws with Contract.Requires
.
This is perfectly all right given the fact that you're using an interface and a contract class. There is simply no other place to validate the constructor parameters other than in the constructor itself.
If you use the ArgumentNullException
approach then you'll miss out on code contract's static checking and other goodies.
Upvotes: 1