Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Having read your comments in Mehrdad's answer, I think I understand your problem a bit better.</p> <p>It appears that you are concerned about the ability of the developer to access private state in the class they are writing, bypassing your validation logic, etc. This suggests that the state should not be contained in the class at all.</p> <p>I would suggest the following strategy. Write a generic class that represents a ValidatedValue. This class holds only the backing value and only allows access/mutation via get and set methods. A delegate is passed to the ValidatedValue to represent the validation logic:</p> <pre><code>public class ValidatedValue&lt; T &gt; { private T m_val; public ValidationFn m_validationFn; public delegate bool ValidationFn( T fn ); public ValidatedValue( ValidationFn validationFn ) { m_validationFn = validationFn; } public T get() { return m_val; } public void set(T v) { if (m_validationFn(v)) { m_val = v; } } } </code></pre> <p>You could, of course, add more delegates as required (eg, to support pre/post change notification).</p> <p>Your class would now use the ValidatedValue in place of a backing store for your property.</p> <p>The example below shows a class, MyClass, with an integer that is validated to be less than 100. Note that the logic to throw an exception is in MyClass, not the ValidatedValue. This allows you to do complex validation rules that depend on other state contained in MyClass. Lambda notation was used to construct the validation delegate - you could have bound to a member function instead.</p> <pre><code>public partial class MyClass { private ValidatedValue&lt;int&gt; m_foo; public MyClass() { m_foo = new ValidatedValue&lt;int&gt;( v =&gt; { if (v &gt;= 100) RaiseError(); return true; } ); } private void RaiseError() { // Put your logic here.... throw new NotImplementedException(); } public int Foo { get { return m_foo.get(); } set { m_foo.set(value); } } } </code></pre> <p>Hope that helps - somewhat off the original topic, but I think it's more inline with your actual concerns. What we have done is taken the validation logic away from the property and put it on the data, which is exactly where you wanted it.</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