title: Data Validation in a Constructor?
body: <p>I a beginner to OO-programming, and this question is about handling data validation in a particular design. I have read <a href="https://stackoverflow.com/questions/1158410/how-to-handle-incorrect-values-in-a-constructor">this thread</a> about a similar problem, and I like the second solution, which recommends re-designing the constructor interface such that invalid values are impossible, but i wonder whether this idea is also applicable to my case. So I have outlined my thoughts below and would like to know if people agree with my ideas.</p>
  
  <p>I have a <code>Die</code> class, which is constructed by passing a vector of probabilities. All the probabilities must be non-negative, and must add up to 1.0.</p>
  
  <pre><code>class Die
  {
  public:
      Die(/* Probability vector. */);
      int Roll();
  }
  </code></pre>
  
  <p>I can think of several options to implement data validation:</p>
  
  <ol>
  <li><p>The <code>Die</code> constructor is protected and accepts an <code>std::vector&lt;double&gt;</code>. Then have a static public method that performs the data validation, and returns a pointer to a new <code>Die</code> object if this is successful, and a <code>NULL</code> otherwise.</p></li>
  <li><p>Create a <code>ProbabilityVector</code> class, which wraps around an <code>std::vector&lt;double&gt;</code>, and implement the data validation there (with the protected constructor + public static method above). Then the <code>Die</code> constructor accepts a (pointer to a) <code>ProbabilityVector</code>.</p></li>
  <li><p>Implement a separate <code>ProbabilityVectorValidation</code> class, with a static method on an <code>std::vector&lt;double&gt;</code> returning a <code>bool</code>. Then, when necessary, use this method before passing an <code>std::vector&lt;double&gt;</code> to the <code>Die</code> constructor.</p></li>
  </ol>
  
  <p>The disadvantage of (1) is that the validation is carried out every time a <code>Die</code> is created, even though this may not be necessary. (2) gets around this problem, but I'm not sure if the protected constructor + static public approach is elegant, because it involves raw pointers. (3) is looking like an attractive option, but seems less robust than (1) and (2)?</p>