Throwing exceptions when validation failsHandling COM exceptions / busy codesCalculating Earnings from...

When to use the term transposed instead of modulation?

Is this nominative case or accusative case?

A bug in Excel? Conditional formatting for marking duplicates also highlights unique value

Can you run a ground wire from stove directly to ground pole in the ground

The Key to the Door

Remove object from array based on array of some property of that object

Why can't we use freedom of speech and expression to incite people to rebel against government in India?

Can a Mexican citizen living in US under DACA drive to Canada?

How do you make a gun that shoots melee weapons and/or swords?

ESPP--any reason not to go all in?

Can a Mimic (container form) actually hold loot?

Did Amazon pay $0 in taxes last year?

Has a sovereign Communist government ever run, and conceded loss, on a fair election?

Replacing tantalum capacitor with ceramic capacitor for Op Amps

I can't die. Who am I?

How spaceships determine each other's mass in space?

Computing the volume of a simplex-like object with constraints

Is there a math equivalent to the conditional ternary operator?

Are there other characters in the Star Wars universe who had damaged bodies and needed to wear an outfit like Darth Vader?

Why doesn't "adolescent" take any articles in "listen to adolescent agonising"?

Iron deposits mined from under the city

Calculate total length of edges in select Voronoi diagram

What is the oldest European royal house?

Professor forcing me to attend a conference



Throwing exceptions when validation fails


Handling COM exceptions / busy codesCalculating Earnings from attendance detailsUser name and password validation in a MVP applicationProper handling of exceptions in MVPFollow Up post: Proper handling of exceptions in MVPInput validation for text boxes in a FormThrowing exceptions in a database wrapperNullGuard for throwing more informative exceptionsThrowing exceptions if there is not exactly one box retrievedGetting single element or throwing one of two exceptions













7












$begingroup$


When I want to check the validity of an attendance being entered into the system, I perform following action.



AttendancePresenter Class



    void _View_OnCheckValidity(object sender, EventArgs e)
{
//ExecuteAction performs exception handling in Base Class
this.ExecutAction(() =>
{
ValidateAttendance();
});
}

private void ValidateAttendance()
{
//DataService method returns true if the attendance is valid.
var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
//Set the validity of the attendance in a View property.
//So that View can stop execution if validity is false.
_View.AttendanceValidity = validity;
//If validation fails, throw an exception
if (!validity)
{ throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
}


View



private void txtOutTime_KeyPress(object sender, KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Enter & !string .IsNullOrWhiteSpace(txtEmployeeID.Text) & txtOutTime.Text != DefaultText)
{
OnCheckValidity(sender, e);
if (this.AttendanceValidity)
{ OnEnterAttendance(sender, e); } //This line of code enters attendance into the DB
}
}


Appreciate if you could review this code and give your feedback. Specially what I want to know is about the exception thrown in presenter if the validation fails. Is it acceptable? Is this is a standard use of throw?










share|improve this question









$endgroup$

















    7












    $begingroup$


    When I want to check the validity of an attendance being entered into the system, I perform following action.



    AttendancePresenter Class



        void _View_OnCheckValidity(object sender, EventArgs e)
    {
    //ExecuteAction performs exception handling in Base Class
    this.ExecutAction(() =>
    {
    ValidateAttendance();
    });
    }

    private void ValidateAttendance()
    {
    //DataService method returns true if the attendance is valid.
    var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
    //Set the validity of the attendance in a View property.
    //So that View can stop execution if validity is false.
    _View.AttendanceValidity = validity;
    //If validation fails, throw an exception
    if (!validity)
    { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
    }


    View



    private void txtOutTime_KeyPress(object sender, KeyPressEventArgs e)
    {
    if (e.KeyChar == (char)Keys.Enter & !string .IsNullOrWhiteSpace(txtEmployeeID.Text) & txtOutTime.Text != DefaultText)
    {
    OnCheckValidity(sender, e);
    if (this.AttendanceValidity)
    { OnEnterAttendance(sender, e); } //This line of code enters attendance into the DB
    }
    }


    Appreciate if you could review this code and give your feedback. Specially what I want to know is about the exception thrown in presenter if the validation fails. Is it acceptable? Is this is a standard use of throw?










    share|improve this question









    $endgroup$















      7












      7








      7





      $begingroup$


      When I want to check the validity of an attendance being entered into the system, I perform following action.



      AttendancePresenter Class



          void _View_OnCheckValidity(object sender, EventArgs e)
      {
      //ExecuteAction performs exception handling in Base Class
      this.ExecutAction(() =>
      {
      ValidateAttendance();
      });
      }

      private void ValidateAttendance()
      {
      //DataService method returns true if the attendance is valid.
      var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
      //Set the validity of the attendance in a View property.
      //So that View can stop execution if validity is false.
      _View.AttendanceValidity = validity;
      //If validation fails, throw an exception
      if (!validity)
      { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
      }


      View



      private void txtOutTime_KeyPress(object sender, KeyPressEventArgs e)
      {
      if (e.KeyChar == (char)Keys.Enter & !string .IsNullOrWhiteSpace(txtEmployeeID.Text) & txtOutTime.Text != DefaultText)
      {
      OnCheckValidity(sender, e);
      if (this.AttendanceValidity)
      { OnEnterAttendance(sender, e); } //This line of code enters attendance into the DB
      }
      }


      Appreciate if you could review this code and give your feedback. Specially what I want to know is about the exception thrown in presenter if the validation fails. Is it acceptable? Is this is a standard use of throw?










      share|improve this question









      $endgroup$




      When I want to check the validity of an attendance being entered into the system, I perform following action.



      AttendancePresenter Class



          void _View_OnCheckValidity(object sender, EventArgs e)
      {
      //ExecuteAction performs exception handling in Base Class
      this.ExecutAction(() =>
      {
      ValidateAttendance();
      });
      }

      private void ValidateAttendance()
      {
      //DataService method returns true if the attendance is valid.
      var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
      //Set the validity of the attendance in a View property.
      //So that View can stop execution if validity is false.
      _View.AttendanceValidity = validity;
      //If validation fails, throw an exception
      if (!validity)
      { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
      }


      View



      private void txtOutTime_KeyPress(object sender, KeyPressEventArgs e)
      {
      if (e.KeyChar == (char)Keys.Enter & !string .IsNullOrWhiteSpace(txtEmployeeID.Text) & txtOutTime.Text != DefaultText)
      {
      OnCheckValidity(sender, e);
      if (this.AttendanceValidity)
      { OnEnterAttendance(sender, e); } //This line of code enters attendance into the DB
      }
      }


      Appreciate if you could review this code and give your feedback. Specially what I want to know is about the exception thrown in presenter if the validation fails. Is it acceptable? Is this is a standard use of throw?







      c# .net exception mvp






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Aug 15 '14 at 19:02









      CADCAD

      90341835




      90341835






















          4 Answers
          4






          active

          oldest

          votes


















          13












          $begingroup$

          You're throwing System.Exception. Don't do that. If you're going to have to throw an exception for a validation exception, throw a custom ValidationException exception.



          You haven't shown the code where you catch and handle that exception, but it's going to have to look like this:



          try
          {
          // some code
          }
          catch (Exception exception)
          {
          // handle the [validation?] exception
          }


          The problem with that, is that you don't know if the exception you're catching is due to a validation error, or if there's a division by zero, or if you ran out of memory, or if a database connection failed. With a custom exception type, you can do this:



          try
          {
          // some code
          }
          catch (ValidationException exception)
          {
          // handle the validation exception
          }


          And any exception thrown that is not a ValidationException, will bubble up the stack.





          That said, I wouldn't throw an exception for that. Exceptions should be for exceptional things. If you already know how you're going to handle it (show the error message in a message box?), why not just do that instead of throwing?






          share|improve this answer









          $endgroup$













          • $begingroup$
            I wouldn't say there's anything wrong with throwing an exception for failed validation; failing validation is exactly the kind of circumstance which your model-level code can't handle, and should pass upwards. I would never expect a ValidateX method to handle validation errors.
            $endgroup$
            – sapi
            Aug 16 '14 at 0:17






          • 2




            $begingroup$
            @sapi what if it were a function IsValid ()? Would you expect a Validation exception or a false? Exceptions are for Exceptional circumstances. And not for the everyday incorrect user input.
            $endgroup$
            – Vogel612
            Aug 16 '14 at 17:11






          • 2




            $begingroup$
            @Vogel612 If it's named IsValid, I'd expect a bool. I certainly wouldn't expect a normal validation method (eg, database validation) to meekly return False when it gets bad data, though, and I've never used a framework which doesn't throw exceptions for failed validation.
            $endgroup$
            – sapi
            Aug 18 '14 at 3:02



















          8












          $begingroup$


          private void ValidateAttendance()
          {
          //DataService method returns true if the attendance is valid.
          var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
          //Set the validity of the attendance in a View property.
          //So that View can stop execution if validity is false.
          _View.AttendanceValidity = validity;
          //If validation fails, throw an exception
          if (!validity)
          { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
          }



          If you replace valdidity with the more standard isValid name, you could get rid of the comment saying //If Validation fails.... I think it just reads more naturally that way. Give it some breathing space around comments too. Removing comments like set this to that is also a good idea.



          private void ValidateAttendance()
          {
          //DataService method returns true if the attendance is valid.
          var isValid = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);

          //So that View can stop execution if validity is false.
          _View.AttendanceValidity = isValid;

          if (!isValid)
          { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
          }





          share|improve this answer









          $endgroup$





















            5












            $begingroup$

            You shouldn't throw Exception, create a custom Exception as proposed @Mat's Mug and throw that one instead, otherwise you might trap an exception you didn't want to trap (ex : MyDatabaseJustExplodedException)!



            I'd add that it is never good to have as much lines of comment as you have lines of code! Basically, comments shouldn't explain what you are doing but why you are doing it. If you need to explain what you are doing, something is wrong with your code.



            I think the only comment that is worth its place is this one
            //So that View can stop execution if validity is false.



            I would change AttendanceValidity to IsAttendanceValid, it is way more clear what your property is in charge of.



            Finally, I don't think you should have braces around one liners if it is to put them on the same line as your code. What I mean is either do this :



            if (!validity) //changed by isValid as suggested @ckuhn203
            {
            throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");
            }


            or this



            if (!validity) //changed by isValid as suggested @ckuhn203
            throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");





            share|improve this answer









            $endgroup$





















              0












              $begingroup$

              Whenever I do validation I end up with a type that does validation and the Validate method returns a result. I let the thing calling it decide whether or not validation failure is an exceptional circumstance (which in my opinion it isn't).



              public class MyValidator : IValidator<TypeToValidate> {
              public ValidationResult Validate(TypeToValidate objToValidate) {
              // Do whatever validation here...
              return new ValidationResult(false, "Some useful message here");
              }
              }


              I like the result to tell me everything that is wrong with what I passed in to have validated instead of just failing on the first thing and returning. You end up in a situation where the user gets the thing that fails, tries again, sees another thing fail, fixes it, etc. Not a good user experience in my opinion.





              share








              New contributor




              Logan K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
              Check out our Code of Conduct.






              $endgroup$













                Your Answer





                StackExchange.ifUsing("editor", function () {
                return StackExchange.using("mathjaxEditing", function () {
                StackExchange.MarkdownEditor.creationCallbacks.add(function (editor, postfix) {
                StackExchange.mathjaxEditing.prepareWmdForMathJax(editor, postfix, [["\$", "\$"]]);
                });
                });
                }, "mathjax-editing");

                StackExchange.ifUsing("editor", function () {
                StackExchange.using("externalEditor", function () {
                StackExchange.using("snippets", function () {
                StackExchange.snippets.init();
                });
                });
                }, "code-snippets");

                StackExchange.ready(function() {
                var channelOptions = {
                tags: "".split(" "),
                id: "196"
                };
                initTagRenderer("".split(" "), "".split(" "), channelOptions);

                StackExchange.using("externalEditor", function() {
                // Have to fire editor after snippets, if snippets enabled
                if (StackExchange.settings.snippets.snippetsEnabled) {
                StackExchange.using("snippets", function() {
                createEditor();
                });
                }
                else {
                createEditor();
                }
                });

                function createEditor() {
                StackExchange.prepareEditor({
                heartbeatType: 'answer',
                autoActivateHeartbeat: false,
                convertImagesToLinks: false,
                noModals: true,
                showLowRepImageUploadWarning: true,
                reputationToPostImages: null,
                bindNavPrevention: true,
                postfix: "",
                imageUploader: {
                brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
                contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
                allowUrls: true
                },
                onDemand: true,
                discardSelector: ".discard-answer"
                ,immediatelyShowMarkdownHelp:true
                });


                }
                });














                draft saved

                draft discarded


















                StackExchange.ready(
                function () {
                StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f60176%2fthrowing-exceptions-when-validation-fails%23new-answer', 'question_page');
                }
                );

                Post as a guest















                Required, but never shown

























                4 Answers
                4






                active

                oldest

                votes








                4 Answers
                4






                active

                oldest

                votes









                active

                oldest

                votes






                active

                oldest

                votes









                13












                $begingroup$

                You're throwing System.Exception. Don't do that. If you're going to have to throw an exception for a validation exception, throw a custom ValidationException exception.



                You haven't shown the code where you catch and handle that exception, but it's going to have to look like this:



                try
                {
                // some code
                }
                catch (Exception exception)
                {
                // handle the [validation?] exception
                }


                The problem with that, is that you don't know if the exception you're catching is due to a validation error, or if there's a division by zero, or if you ran out of memory, or if a database connection failed. With a custom exception type, you can do this:



                try
                {
                // some code
                }
                catch (ValidationException exception)
                {
                // handle the validation exception
                }


                And any exception thrown that is not a ValidationException, will bubble up the stack.





                That said, I wouldn't throw an exception for that. Exceptions should be for exceptional things. If you already know how you're going to handle it (show the error message in a message box?), why not just do that instead of throwing?






                share|improve this answer









                $endgroup$













                • $begingroup$
                  I wouldn't say there's anything wrong with throwing an exception for failed validation; failing validation is exactly the kind of circumstance which your model-level code can't handle, and should pass upwards. I would never expect a ValidateX method to handle validation errors.
                  $endgroup$
                  – sapi
                  Aug 16 '14 at 0:17






                • 2




                  $begingroup$
                  @sapi what if it were a function IsValid ()? Would you expect a Validation exception or a false? Exceptions are for Exceptional circumstances. And not for the everyday incorrect user input.
                  $endgroup$
                  – Vogel612
                  Aug 16 '14 at 17:11






                • 2




                  $begingroup$
                  @Vogel612 If it's named IsValid, I'd expect a bool. I certainly wouldn't expect a normal validation method (eg, database validation) to meekly return False when it gets bad data, though, and I've never used a framework which doesn't throw exceptions for failed validation.
                  $endgroup$
                  – sapi
                  Aug 18 '14 at 3:02
















                13












                $begingroup$

                You're throwing System.Exception. Don't do that. If you're going to have to throw an exception for a validation exception, throw a custom ValidationException exception.



                You haven't shown the code where you catch and handle that exception, but it's going to have to look like this:



                try
                {
                // some code
                }
                catch (Exception exception)
                {
                // handle the [validation?] exception
                }


                The problem with that, is that you don't know if the exception you're catching is due to a validation error, or if there's a division by zero, or if you ran out of memory, or if a database connection failed. With a custom exception type, you can do this:



                try
                {
                // some code
                }
                catch (ValidationException exception)
                {
                // handle the validation exception
                }


                And any exception thrown that is not a ValidationException, will bubble up the stack.





                That said, I wouldn't throw an exception for that. Exceptions should be for exceptional things. If you already know how you're going to handle it (show the error message in a message box?), why not just do that instead of throwing?






                share|improve this answer









                $endgroup$













                • $begingroup$
                  I wouldn't say there's anything wrong with throwing an exception for failed validation; failing validation is exactly the kind of circumstance which your model-level code can't handle, and should pass upwards. I would never expect a ValidateX method to handle validation errors.
                  $endgroup$
                  – sapi
                  Aug 16 '14 at 0:17






                • 2




                  $begingroup$
                  @sapi what if it were a function IsValid ()? Would you expect a Validation exception or a false? Exceptions are for Exceptional circumstances. And not for the everyday incorrect user input.
                  $endgroup$
                  – Vogel612
                  Aug 16 '14 at 17:11






                • 2




                  $begingroup$
                  @Vogel612 If it's named IsValid, I'd expect a bool. I certainly wouldn't expect a normal validation method (eg, database validation) to meekly return False when it gets bad data, though, and I've never used a framework which doesn't throw exceptions for failed validation.
                  $endgroup$
                  – sapi
                  Aug 18 '14 at 3:02














                13












                13








                13





                $begingroup$

                You're throwing System.Exception. Don't do that. If you're going to have to throw an exception for a validation exception, throw a custom ValidationException exception.



                You haven't shown the code where you catch and handle that exception, but it's going to have to look like this:



                try
                {
                // some code
                }
                catch (Exception exception)
                {
                // handle the [validation?] exception
                }


                The problem with that, is that you don't know if the exception you're catching is due to a validation error, or if there's a division by zero, or if you ran out of memory, or if a database connection failed. With a custom exception type, you can do this:



                try
                {
                // some code
                }
                catch (ValidationException exception)
                {
                // handle the validation exception
                }


                And any exception thrown that is not a ValidationException, will bubble up the stack.





                That said, I wouldn't throw an exception for that. Exceptions should be for exceptional things. If you already know how you're going to handle it (show the error message in a message box?), why not just do that instead of throwing?






                share|improve this answer









                $endgroup$



                You're throwing System.Exception. Don't do that. If you're going to have to throw an exception for a validation exception, throw a custom ValidationException exception.



                You haven't shown the code where you catch and handle that exception, but it's going to have to look like this:



                try
                {
                // some code
                }
                catch (Exception exception)
                {
                // handle the [validation?] exception
                }


                The problem with that, is that you don't know if the exception you're catching is due to a validation error, or if there's a division by zero, or if you ran out of memory, or if a database connection failed. With a custom exception type, you can do this:



                try
                {
                // some code
                }
                catch (ValidationException exception)
                {
                // handle the validation exception
                }


                And any exception thrown that is not a ValidationException, will bubble up the stack.





                That said, I wouldn't throw an exception for that. Exceptions should be for exceptional things. If you already know how you're going to handle it (show the error message in a message box?), why not just do that instead of throwing?







                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Aug 15 '14 at 19:11









                Mathieu GuindonMathieu Guindon

                60.9k14147419




                60.9k14147419












                • $begingroup$
                  I wouldn't say there's anything wrong with throwing an exception for failed validation; failing validation is exactly the kind of circumstance which your model-level code can't handle, and should pass upwards. I would never expect a ValidateX method to handle validation errors.
                  $endgroup$
                  – sapi
                  Aug 16 '14 at 0:17






                • 2




                  $begingroup$
                  @sapi what if it were a function IsValid ()? Would you expect a Validation exception or a false? Exceptions are for Exceptional circumstances. And not for the everyday incorrect user input.
                  $endgroup$
                  – Vogel612
                  Aug 16 '14 at 17:11






                • 2




                  $begingroup$
                  @Vogel612 If it's named IsValid, I'd expect a bool. I certainly wouldn't expect a normal validation method (eg, database validation) to meekly return False when it gets bad data, though, and I've never used a framework which doesn't throw exceptions for failed validation.
                  $endgroup$
                  – sapi
                  Aug 18 '14 at 3:02


















                • $begingroup$
                  I wouldn't say there's anything wrong with throwing an exception for failed validation; failing validation is exactly the kind of circumstance which your model-level code can't handle, and should pass upwards. I would never expect a ValidateX method to handle validation errors.
                  $endgroup$
                  – sapi
                  Aug 16 '14 at 0:17






                • 2




                  $begingroup$
                  @sapi what if it were a function IsValid ()? Would you expect a Validation exception or a false? Exceptions are for Exceptional circumstances. And not for the everyday incorrect user input.
                  $endgroup$
                  – Vogel612
                  Aug 16 '14 at 17:11






                • 2




                  $begingroup$
                  @Vogel612 If it's named IsValid, I'd expect a bool. I certainly wouldn't expect a normal validation method (eg, database validation) to meekly return False when it gets bad data, though, and I've never used a framework which doesn't throw exceptions for failed validation.
                  $endgroup$
                  – sapi
                  Aug 18 '14 at 3:02
















                $begingroup$
                I wouldn't say there's anything wrong with throwing an exception for failed validation; failing validation is exactly the kind of circumstance which your model-level code can't handle, and should pass upwards. I would never expect a ValidateX method to handle validation errors.
                $endgroup$
                – sapi
                Aug 16 '14 at 0:17




                $begingroup$
                I wouldn't say there's anything wrong with throwing an exception for failed validation; failing validation is exactly the kind of circumstance which your model-level code can't handle, and should pass upwards. I would never expect a ValidateX method to handle validation errors.
                $endgroup$
                – sapi
                Aug 16 '14 at 0:17




                2




                2




                $begingroup$
                @sapi what if it were a function IsValid ()? Would you expect a Validation exception or a false? Exceptions are for Exceptional circumstances. And not for the everyday incorrect user input.
                $endgroup$
                – Vogel612
                Aug 16 '14 at 17:11




                $begingroup$
                @sapi what if it were a function IsValid ()? Would you expect a Validation exception or a false? Exceptions are for Exceptional circumstances. And not for the everyday incorrect user input.
                $endgroup$
                – Vogel612
                Aug 16 '14 at 17:11




                2




                2




                $begingroup$
                @Vogel612 If it's named IsValid, I'd expect a bool. I certainly wouldn't expect a normal validation method (eg, database validation) to meekly return False when it gets bad data, though, and I've never used a framework which doesn't throw exceptions for failed validation.
                $endgroup$
                – sapi
                Aug 18 '14 at 3:02




                $begingroup$
                @Vogel612 If it's named IsValid, I'd expect a bool. I certainly wouldn't expect a normal validation method (eg, database validation) to meekly return False when it gets bad data, though, and I've never used a framework which doesn't throw exceptions for failed validation.
                $endgroup$
                – sapi
                Aug 18 '14 at 3:02













                8












                $begingroup$


                private void ValidateAttendance()
                {
                //DataService method returns true if the attendance is valid.
                var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
                //Set the validity of the attendance in a View property.
                //So that View can stop execution if validity is false.
                _View.AttendanceValidity = validity;
                //If validation fails, throw an exception
                if (!validity)
                { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
                }



                If you replace valdidity with the more standard isValid name, you could get rid of the comment saying //If Validation fails.... I think it just reads more naturally that way. Give it some breathing space around comments too. Removing comments like set this to that is also a good idea.



                private void ValidateAttendance()
                {
                //DataService method returns true if the attendance is valid.
                var isValid = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);

                //So that View can stop execution if validity is false.
                _View.AttendanceValidity = isValid;

                if (!isValid)
                { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
                }





                share|improve this answer









                $endgroup$


















                  8












                  $begingroup$


                  private void ValidateAttendance()
                  {
                  //DataService method returns true if the attendance is valid.
                  var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
                  //Set the validity of the attendance in a View property.
                  //So that View can stop execution if validity is false.
                  _View.AttendanceValidity = validity;
                  //If validation fails, throw an exception
                  if (!validity)
                  { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
                  }



                  If you replace valdidity with the more standard isValid name, you could get rid of the comment saying //If Validation fails.... I think it just reads more naturally that way. Give it some breathing space around comments too. Removing comments like set this to that is also a good idea.



                  private void ValidateAttendance()
                  {
                  //DataService method returns true if the attendance is valid.
                  var isValid = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);

                  //So that View can stop execution if validity is false.
                  _View.AttendanceValidity = isValid;

                  if (!isValid)
                  { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
                  }





                  share|improve this answer









                  $endgroup$
















                    8












                    8








                    8





                    $begingroup$


                    private void ValidateAttendance()
                    {
                    //DataService method returns true if the attendance is valid.
                    var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
                    //Set the validity of the attendance in a View property.
                    //So that View can stop execution if validity is false.
                    _View.AttendanceValidity = validity;
                    //If validation fails, throw an exception
                    if (!validity)
                    { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
                    }



                    If you replace valdidity with the more standard isValid name, you could get rid of the comment saying //If Validation fails.... I think it just reads more naturally that way. Give it some breathing space around comments too. Removing comments like set this to that is also a good idea.



                    private void ValidateAttendance()
                    {
                    //DataService method returns true if the attendance is valid.
                    var isValid = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);

                    //So that View can stop execution if validity is false.
                    _View.AttendanceValidity = isValid;

                    if (!isValid)
                    { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
                    }





                    share|improve this answer









                    $endgroup$




                    private void ValidateAttendance()
                    {
                    //DataService method returns true if the attendance is valid.
                    var validity = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);
                    //Set the validity of the attendance in a View property.
                    //So that View can stop execution if validity is false.
                    _View.AttendanceValidity = validity;
                    //If validation fails, throw an exception
                    if (!validity)
                    { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
                    }



                    If you replace valdidity with the more standard isValid name, you could get rid of the comment saying //If Validation fails.... I think it just reads more naturally that way. Give it some breathing space around comments too. Removing comments like set this to that is also a good idea.



                    private void ValidateAttendance()
                    {
                    //DataService method returns true if the attendance is valid.
                    var isValid = _DataService.CheckValidityOfAnAttendance(_View.EmployeeID, _View.Date, _View.ShiftType);

                    //So that View can stop execution if validity is false.
                    _View.AttendanceValidity = isValid;

                    if (!isValid)
                    { throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee"); }
                    }






                    share|improve this answer












                    share|improve this answer



                    share|improve this answer










                    answered Aug 15 '14 at 19:10









                    RubberDuckRubberDuck

                    27.2k456161




                    27.2k456161























                        5












                        $begingroup$

                        You shouldn't throw Exception, create a custom Exception as proposed @Mat's Mug and throw that one instead, otherwise you might trap an exception you didn't want to trap (ex : MyDatabaseJustExplodedException)!



                        I'd add that it is never good to have as much lines of comment as you have lines of code! Basically, comments shouldn't explain what you are doing but why you are doing it. If you need to explain what you are doing, something is wrong with your code.



                        I think the only comment that is worth its place is this one
                        //So that View can stop execution if validity is false.



                        I would change AttendanceValidity to IsAttendanceValid, it is way more clear what your property is in charge of.



                        Finally, I don't think you should have braces around one liners if it is to put them on the same line as your code. What I mean is either do this :



                        if (!validity) //changed by isValid as suggested @ckuhn203
                        {
                        throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");
                        }


                        or this



                        if (!validity) //changed by isValid as suggested @ckuhn203
                        throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");





                        share|improve this answer









                        $endgroup$


















                          5












                          $begingroup$

                          You shouldn't throw Exception, create a custom Exception as proposed @Mat's Mug and throw that one instead, otherwise you might trap an exception you didn't want to trap (ex : MyDatabaseJustExplodedException)!



                          I'd add that it is never good to have as much lines of comment as you have lines of code! Basically, comments shouldn't explain what you are doing but why you are doing it. If you need to explain what you are doing, something is wrong with your code.



                          I think the only comment that is worth its place is this one
                          //So that View can stop execution if validity is false.



                          I would change AttendanceValidity to IsAttendanceValid, it is way more clear what your property is in charge of.



                          Finally, I don't think you should have braces around one liners if it is to put them on the same line as your code. What I mean is either do this :



                          if (!validity) //changed by isValid as suggested @ckuhn203
                          {
                          throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");
                          }


                          or this



                          if (!validity) //changed by isValid as suggested @ckuhn203
                          throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");





                          share|improve this answer









                          $endgroup$
















                            5












                            5








                            5





                            $begingroup$

                            You shouldn't throw Exception, create a custom Exception as proposed @Mat's Mug and throw that one instead, otherwise you might trap an exception you didn't want to trap (ex : MyDatabaseJustExplodedException)!



                            I'd add that it is never good to have as much lines of comment as you have lines of code! Basically, comments shouldn't explain what you are doing but why you are doing it. If you need to explain what you are doing, something is wrong with your code.



                            I think the only comment that is worth its place is this one
                            //So that View can stop execution if validity is false.



                            I would change AttendanceValidity to IsAttendanceValid, it is way more clear what your property is in charge of.



                            Finally, I don't think you should have braces around one liners if it is to put them on the same line as your code. What I mean is either do this :



                            if (!validity) //changed by isValid as suggested @ckuhn203
                            {
                            throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");
                            }


                            or this



                            if (!validity) //changed by isValid as suggested @ckuhn203
                            throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");





                            share|improve this answer









                            $endgroup$



                            You shouldn't throw Exception, create a custom Exception as proposed @Mat's Mug and throw that one instead, otherwise you might trap an exception you didn't want to trap (ex : MyDatabaseJustExplodedException)!



                            I'd add that it is never good to have as much lines of comment as you have lines of code! Basically, comments shouldn't explain what you are doing but why you are doing it. If you need to explain what you are doing, something is wrong with your code.



                            I think the only comment that is worth its place is this one
                            //So that View can stop execution if validity is false.



                            I would change AttendanceValidity to IsAttendanceValid, it is way more clear what your property is in charge of.



                            Finally, I don't think you should have braces around one liners if it is to put them on the same line as your code. What I mean is either do this :



                            if (!validity) //changed by isValid as suggested @ckuhn203
                            {
                            throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");
                            }


                            or this



                            if (!validity) //changed by isValid as suggested @ckuhn203
                            throw new Exception("Invalid Attendance. Already there is a matching attendance for this employee");






                            share|improve this answer












                            share|improve this answer



                            share|improve this answer










                            answered Aug 15 '14 at 19:23









                            IEatBagelsIEatBagels

                            8,98323378




                            8,98323378























                                0












                                $begingroup$

                                Whenever I do validation I end up with a type that does validation and the Validate method returns a result. I let the thing calling it decide whether or not validation failure is an exceptional circumstance (which in my opinion it isn't).



                                public class MyValidator : IValidator<TypeToValidate> {
                                public ValidationResult Validate(TypeToValidate objToValidate) {
                                // Do whatever validation here...
                                return new ValidationResult(false, "Some useful message here");
                                }
                                }


                                I like the result to tell me everything that is wrong with what I passed in to have validated instead of just failing on the first thing and returning. You end up in a situation where the user gets the thing that fails, tries again, sees another thing fail, fixes it, etc. Not a good user experience in my opinion.





                                share








                                New contributor




                                Logan K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                Check out our Code of Conduct.






                                $endgroup$


















                                  0












                                  $begingroup$

                                  Whenever I do validation I end up with a type that does validation and the Validate method returns a result. I let the thing calling it decide whether or not validation failure is an exceptional circumstance (which in my opinion it isn't).



                                  public class MyValidator : IValidator<TypeToValidate> {
                                  public ValidationResult Validate(TypeToValidate objToValidate) {
                                  // Do whatever validation here...
                                  return new ValidationResult(false, "Some useful message here");
                                  }
                                  }


                                  I like the result to tell me everything that is wrong with what I passed in to have validated instead of just failing on the first thing and returning. You end up in a situation where the user gets the thing that fails, tries again, sees another thing fail, fixes it, etc. Not a good user experience in my opinion.





                                  share








                                  New contributor




                                  Logan K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                  Check out our Code of Conduct.






                                  $endgroup$
















                                    0












                                    0








                                    0





                                    $begingroup$

                                    Whenever I do validation I end up with a type that does validation and the Validate method returns a result. I let the thing calling it decide whether or not validation failure is an exceptional circumstance (which in my opinion it isn't).



                                    public class MyValidator : IValidator<TypeToValidate> {
                                    public ValidationResult Validate(TypeToValidate objToValidate) {
                                    // Do whatever validation here...
                                    return new ValidationResult(false, "Some useful message here");
                                    }
                                    }


                                    I like the result to tell me everything that is wrong with what I passed in to have validated instead of just failing on the first thing and returning. You end up in a situation where the user gets the thing that fails, tries again, sees another thing fail, fixes it, etc. Not a good user experience in my opinion.





                                    share








                                    New contributor




                                    Logan K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






                                    $endgroup$



                                    Whenever I do validation I end up with a type that does validation and the Validate method returns a result. I let the thing calling it decide whether or not validation failure is an exceptional circumstance (which in my opinion it isn't).



                                    public class MyValidator : IValidator<TypeToValidate> {
                                    public ValidationResult Validate(TypeToValidate objToValidate) {
                                    // Do whatever validation here...
                                    return new ValidationResult(false, "Some useful message here");
                                    }
                                    }


                                    I like the result to tell me everything that is wrong with what I passed in to have validated instead of just failing on the first thing and returning. You end up in a situation where the user gets the thing that fails, tries again, sees another thing fail, fixes it, etc. Not a good user experience in my opinion.






                                    share








                                    New contributor




                                    Logan K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.








                                    share


                                    share






                                    New contributor




                                    Logan K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.









                                    answered 7 mins ago









                                    Logan KLogan K

                                    1




                                    1




                                    New contributor




                                    Logan K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.





                                    New contributor





                                    Logan K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






                                    Logan K is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
                                    Check out our Code of Conduct.






























                                        draft saved

                                        draft discarded




















































                                        Thanks for contributing an answer to Code Review Stack Exchange!


                                        • Please be sure to answer the question. Provide details and share your research!

                                        But avoid



                                        • Asking for help, clarification, or responding to other answers.

                                        • Making statements based on opinion; back them up with references or personal experience.


                                        Use MathJax to format equations. MathJax reference.


                                        To learn more, see our tips on writing great answers.




                                        draft saved


                                        draft discarded














                                        StackExchange.ready(
                                        function () {
                                        StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fcodereview.stackexchange.com%2fquestions%2f60176%2fthrowing-exceptions-when-validation-fails%23new-answer', 'question_page');
                                        }
                                        );

                                        Post as a guest















                                        Required, but never shown





















































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown

































                                        Required, but never shown














                                        Required, but never shown












                                        Required, but never shown







                                        Required, but never shown







                                        Popular posts from this blog

                                        Fairchild Swearingen Metro Inhaltsverzeichnis Geschichte | Innenausstattung | Nutzung | Zwischenfälle...

                                        Pilgersdorf Inhaltsverzeichnis Geografie | Geschichte | Bevölkerungsentwicklung | Politik | Kultur...

                                        Marineschifffahrtleitung Inhaltsverzeichnis Geschichte | Heutige Organisation der NATO | Nationale und...