Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Add your own checks prior to invoking the supplied delegate. This way, you can check all of the requirements are met prior to invoking and the checking is done in one place (instead of duplicated in each implementation).</p> <pre><code>public void DoStuff(List&lt;int&gt; list) { CheckPreconditions(list); double ans = Calculate(list); } private void CheckPreconditions(List&lt;int&gt; list) { if(list == null) // throw ... if(list.Length == 0) // throw ... if(Length &lt; list.Count) throw ArgumentException("list", "list must have blah blah blah to satisfy requirements"); } </code></pre> <p>This is similar to the <a href="http://en.wikipedia.org/wiki/Template_method_pattern" rel="nofollow noreferrer">template method pattern</a> except instead of using inheritance, you're delegating to a user-supplied function :)</p> <p>Also, if you make Calculate a field instead of a public property, you can force it to be executed through the DoStuff method, so the checks will always be carried out.</p> <p>Something like:</p> <pre><code>class Test { public int Length{ get; set; } private Func&lt;List&lt;int&gt;, double&gt; m_calculate; // Inject into ctor public Test(Func&lt;List&lt;int&gt;, double&gt; calculate) { if(calculate == null) throw new ArgumentNullException("calculate"); m_calculate = calculate; } // all access to Calculate is now through this method public void DoStuff(List&lt;int&gt; list) { CheckPreconditions(list); double ans = m_calculate(list); } } </code></pre> <p>This would be a good fit if Calculate is only ever set once.</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

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