Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>Passing in a method as a parameter can be used to prevent dependencies and coupling. Let's take a look at how this can be used for the Strategy pattern:</p> <p>Let's say we have a method <code>PrintReport</code>, which prints a given list of items, which might be sorted by Name or by Type, based on a parameter. This is the naive approach:</p> <pre><code>public void PrintReport (List&lt;Item&gt; data, SortOrder sortBy) { List&lt;Item&gt; sortedItems; switch (sortBy) { case SortOrder.Name: sortedItems = SortByName(data); break; case SortOrder.Type: sortedItems = SortByType(data); break; } Print(sortedItems); } </code></pre> <p>It's simple but it works. But what happens when we want to add a new sort order? We need to update the SortOrder enum, go into <code>PrintReport</code> and add a new <code>case</code> and call the new <code>SortByWhatever</code> method. </p> <p>But if we passed in a method as a parameter, our <code>PrintReport</code> can be simpler and not care about the sort implementation:</p> <pre><code>public void PrintReport (List&lt;Item&gt; data, Func&lt;List&lt;Item&gt;, List&lt;Item&gt;&gt; sorter) { List&lt;Item&gt; sortedItems = sorter(data); Print(sortedItems); } </code></pre> <p>Now the sorting function can be defined anyway, possibly even in a different assembly that <code>PrintReport</code> isn't even aware of. It can be a lambda function or an anonymous method defined ad-hoc. But in all cases, our method will receive the delegate, use it to sort, and then print the report. </p> <p>Here's a usage example. At first it looks like we merely moved the switch/case outside of the function, which is important enough since it allows different callers to have different logic. But watch for the third case.</p> <pre><code>public void HandleData() { switch (ReportItemOrder) { case SortOrder.Name: PrintReport(data, SortByName); break; case SortOrder.Type: PrintReport(data, SortByType); break; case SortOrder.Whatever: Func&lt;List&lt;Item&gt;, List&lt;Item&gt;&gt; customSort = (items) =&gt; /* do something */; PrintReport(data, customSort); } } </code></pre>
    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. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    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