1
\$\begingroup\$

In my Repository class:

public class DeliveryRepository : IDeliveryRepository
{
    private readonly List<Delivery> deliveries = new List<Delivery>();

    public Delivery Add(Delivery item)
    {
        if (item == null)
        {
            throw new ArgumentNullException("item");
        }
        deliveries.Add(item);
        return item;
    }
}

...I could implement my Add() method this way:

public Delivery Add(Delivery item)
{
    Contract.Requires(item != null);
    deliveries.Add(item);
    return item;
}

...or this way instead:

public Delivery Add(Delivery item)
{
    Contract.Requires<ArgumentNullException>(item != null, "item");
    deliveries.Add(item);
    return item;
}

Which of the three is best? Does it matter? Just a matter of style/preference?

Are they 2 of one, a pair of the other, and a couple of the third?

\$\endgroup\$
  • 2
    \$\begingroup\$ I think it's preference and also what decisions your programming team has made in regards to the tools available. I personally like the second one, 3rd then first one however I've also never used the Contract features of .NET either (only read about them) \$\endgroup\$ – dreza Oct 11 '13 at 19:48
1
\$\begingroup\$

If you are addressing Code Contracts specifically then you should adopt a programming style that reinforces exception handling policy in release build, i.e. whether you require argument validation at runtime and whether Code Contracts will be part of release build or not.

I suggest taking a look at this diagram (copied from Code Contracts user documentation) and consult it with your team. enter image description here

\$\endgroup\$
0
\$\begingroup\$
  • It is really up to you, whichever preference you have. Otherwise the first two are the most commonly used examples. The first example checks to see if the "item" is null and if it is, then do something....., while the second one does the opposite. If the "item" is not null then do something..... This are common programming techniques used and applied to many coding problems.

  • However you decide to solve the problem, should be well thought and should get the job done. In some cases; when you are attempting to solve a problem, the 1st example might be appealing. While in some other scenarios, the 2nd example might be appealing. So again it might depend on the problem you have to solve.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.