title: What design pattern to use for validating data and creating an object
body: <p>I often come across situations where a I want to create an instance of an object by passing it some given data or maybe another object but the data or object needs to be valid or in the right state. I am always a bit unclear on the 'correct' way of doing this. Here is my example:</p>
  
  <p>Given this class:</p>
  
  <pre><code>class BusinessObject()
  {
      const Threshold = 10;
  
      public BusinessObject(SetOfData&lt;SomeType&gt; setofdata)
      {
          // an example of some validation
          if (setofdata.count &gt; Threshold)
          {
              // performance some business logic
              // set properties
          }
      }
  }
  </code></pre>
  
  <p>It is possible to run into some problems if you do this:</p>
  
  <pre><code>var setofdata = new SetOfData&lt;SomeType&gt;();
  
  // if data is not valid then the object will be created incorrectly
  var businessObject = new BusinessObject(setofdata);
  </code></pre>
  
  <p>So my solutions have always been either:</p>
  
  <pre><code>class BusinessObjectBuilder()
  {
      public BusinessObject Build(SetOfData&lt;SomeType&gt; setofdata)
      {
          // an example of some validation
          if (setofdata.count &gt; Threshold)
              return new BusinessObject(setofdata);
          }
          else
          {
              return null;
          }
      }
  }
  </code></pre>
  
  <p>Or make the constructor private and add a static factory method:</p>
  
  <pre><code>class BusinessObject()
  {
      const Threshold = 10;
  
      public static Create(SetOfData&lt;SomeType&gt; setofdata)
      {
          if (setofdata.count &gt; Threshold)
          {
              return new BusinessObject(setofdata);
          }
          else
          {
              return null;
          }
      }
  
      private BusinessObject(SetOfData&lt;SomeType&gt; setofdata)
      {
          // performance some business logic
          // set properties
      }
  }
  </code></pre>
  
  <p>ideally I would not like to throw an exception if the data is invalid as there might be multiple business objects being created in one process and I don't want the whole process to fail if one validation fails and catching and suppressing exceptions is not good.</p>
  
  <p>Also all examples I read of the Abstract Factory or Factory method involve passing in some type or enum and a correct object being built and returned. They never seem to cover this scenario.</p>
  
  <p>So what are the conventions in this scenario? Any advice would be greatly appreciated.</p>