Note that there are some explanatory texts on larger screens.

plurals
  1. POIs returning an unthrown exception a bad practice for validating input?
    text
    copied!<p>Is it a bad practice to write methods which return unthrown exceptions for the purpose of input validation? The <code>Validate</code> method will return null if the input is valid, or return the exception that will be thrown should the input actually be submitted.</p> <pre><code>public Exception Validate(object input) { if (!SomeParametersMatch(input)) return new SomeException("Message..."); if (!SomeOtherParametersMatch(input)) return new SomeOtherException("Another message..."); // More cases here... return null; } </code></pre> <p>This way, you can use the same function for validating input, displaying responses to the user, and throwing exceptions in the code:</p> <pre><code>public void Submit(object input) { Exception ex = Validate(input); if (ex != null) throw ex; // Do whatever action here... } </code></pre> <p>For example, if you're using the functions to mark spaces valid to click, you can call <code>Validate</code> for each space, marking them valid if the return value isn't null. Then <code>Submit</code> is only called once the user actually clicks on a space and the choice is finalized. This removes code duplication when you need to be able to ensure an input <em>will</em> be valid should you choose it.</p> <p><strong>I could make <code>Validate</code> return a void and simply throw the exceptions</strong>, but since <a href="https://stackoverflow.com/questions/867017/performance-cost-of-try-in-c-sharp">catching thrown exceptions is the most part of exception throwing</a>, and <code>Validate</code> will be run on many more invalid inputs than valid inputs, it seemed like a waste. If <code>Validate</code> were only used when the user actually submitted data, I would have no problem using a try/catch block. But since it's being used to filter data presented to the user, throwing an exception the majority of the time, only to catch and discard it, seems ecessively wasteful.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload