Skip to content
This repository has been archived by the owner on Oct 14, 2019. It is now read-only.

Argument checking

sergun edited this page Aug 7, 2012 · 1 revision

CheckNull

Before

public class Person
{
  private Work _workInfo;

  public Person(Work workInfo)
  {
    if (workInfo == null)
    {
        throw new ArgumentNullException("workInfo");
    }

    _workInfo = workInfo;
  }
}

After

public class Person
{
  private Work _workInfo;

  public Person(Work workInfo)
  {
     _workInfo = workInfo.CheckNull("workInfo");
  }
}

--

Before

public class Person
{
  private Work _workInfo;

  public Person(Work workInfo)
  {
    if (workInfo == null)
    {
        throw new CustomException("Incorrect data");
    }
    _workInfo = workInfo;
  }
}

After

public class Person
{
  private Work _workInfo;

  public Person(Work workInfo)
  {
    _workInfo = workInfo.CheckNull(() => new CustomException("Incorrect data"));
  }
}

CheckNullWithDefault

Before

public class Person
{
  private Work _workInfo;
  public Person(Work workInfo)
  {
    if (workInfo != null)
    {
        _workInfo = workInfo;
    }
    else
    {
        _workInfo = new Work();
    }
  }
}

After

public class Person
{
  private Work _workInfo;
  public Person(Work workInfo)
  {
    _workInfo = workInfo.CheckNullWithDefault(new Work());
  }
}

Check

Before

public class Person
{
  private Work _workInfo;

  public Person(Work workInfo)
  {
    if (workInfo != null)
    {
      if (workInfo.Count > 5)
      {
        _workInfo = workInfo;
      }
      else
      {
        throw new IndexOutOfRangeException();
      }
    }
    else
    {
        throw new ArgumentNullException("workInfo");
    }
  }
}

After

public class Person
{
  private Work _workInfo;

  public Person(Work workInfo)
  {
     _workInfo = workInfo.CheckNull("workInfo").Check(s=>s.Count>5, s=>new IndexOutOfRangeException());
  }
}

CheckWithDefault

Before

public class Person
{
  private Work _workInfo;

  public Person(Work workInfo)
  {
    if (workInfo != null)
    {
      if (workInfo.Count > 5)
      {
        _workInfo = workInfo;
      }
      else
      {
        _workInfo = new Work(10);
      }
    }
    else
    {
        throw new ArgumentNullException("workInfo");
    }
  }
}

After

public class Person
{
  private Work _workInfo;

  public Person(Work workInfo)
  {
     _workInfo = workInfo.CheckNull("workInfo").CheckWithDefault(s => s.Count>5, new Work(10));
  }
}
Clone this wiki locally