title: C# - Where to perform validation
body: <p>I have a question about when to validate inputs on C# form applications.</p>
  
  <p>When taking inputs from a form application, you can run all the validation as you parse in the data from the text fields in the main form class, to then use wherever. For example:</p>
  
  <p><strong>Method 1:</strong></p>
  
  <pre><code>class Car
  {
      private string registration { set; get; } // NO VALIDATION HERE
  }
  // in the form class
  private void add_Click(object sender, EventArgs e)
  {
      // get registration
      int reg_valid = Validate.registration(txtReg.Text); // VALIDATION IS DONE HERE
  
      if(reg_valid)
      {
          Car.registration = txtReg.Text;
      } else {
          // Registration invalid - throw error
      }
  }
  </code></pre>
  
  <p>There will be no validation in the actual Car object as it is all done in the form class.</p>
  
  <p>The other way is to validate the input in the actual class it is stored in like:</p>
  
  <p><br />
  <strong>Method 2:</strong></p>
  
  <pre><code>class Car
  {
      // out registration
      private string registration;
  
      // we can set our registration here and return false if there is an error
      bool set_registration(registration)
      {
          int reg_valid = Validate.registration(registration); // VALIDATION IS DONE HERE
  
          if(reg_valid) {
              this.registration = registration;
          } else {
              return false; // if error
          }
  
          return true; // if all goes well
      }
  }
  // in the form class
  private void add_Click(object sender, EventArgs e)
  {
      // get registration
      string registration = txtReg.Text; // NO VALIDATION DONE HERE
  
      // we can then store this in our object
      if( ! Car.set_registration(registration))
      {
          // Registration invalid - throw error
      }
  }
  </code></pre>
  
  <p>Method 1 seems cleaner, but one of the reasons why we use private attributes is so that we can validate any parsing arguments which is why method 2 seems the better option. Also, using method 2, errors have to be carried up the stack possibly many times, which leads to repeated if statements.</p>
  
  <p>* Please note, this code has not been ran so may contain errors.</p>