An opinionated view2016-05-31T19:14:12+00:00https://baks.github.ioArkadiuszActive patterns to improve user experience2016-05-31T00:00:00+00:00https://baks.github.io/2016/05/31/active-patterns-to-improve-user-experience
<h3 id="a-little-bit-about-ui-and-ux">A little bit about UI and UX</h3>
<p>User interface and user experience is a very complex topic. There are many things which influence how user perceivesS UI. Many small pieces which aren’t part of the core domain, but sometimes have huge impact at
final result. If everything is fine, then user even won’t notice that, but if something is wrong with this little piece then it will stand out like a sore thumb.
One example of that is correct noun flexion. Especially in language like Polish, because we have rather than complex flexion rules for nouns based on count. In order to provide proper user experience in application we should try to present content in correct grammar form.
Let see how we can use <code class="highlighter-rouge">F#</code> to help us with that task.</p>
<h3 id="identifying-rules">Identifying rules</h3>
<p>To keep example simple, we will take a look on words in masculine. Yes, the rules are sometimes a bit more complicated ;)
So, below in table, for one example is listed how it should be declined:</p>
<table>
<thead>
<tr>
<th>Count</th>
<th>Word flexion</th>
</tr>
</thead>
<tbody>
<tr>
<td>0</td>
<td>wydatków</td>
</tr>
<tr>
<td>1</td>
<td>wydatek</td>
</tr>
<tr>
<td>2-4,22-24,32-34,…</td>
<td>wydatki</td>
</tr>
<tr>
<td>5-9,15-19,25-29,…</td>
<td>wydatków</td>
</tr>
<tr>
<td>10-14,20-21,30-31,…</td>
<td>wydatków</td>
</tr>
</tbody>
</table>
<p><br />
We can use feature from F# to name those rules and make easier for creating functions that will be using those rules. That feature is called <code class="highlighter-rouge">Active Patterns</code>.</p>
<h3 id="active-patterns">Active patterns</h3>
<p>They are used to state frequent patterns that we use in pattern matching. But they also can act as a way for make complex patterns shorter.
We can leverage active pattern feature to express our rules in following way:</p>
<pre class="fssnip highlighted"><code lang="fsharp"><span class="k">let</span> (|<span class="p">RuleForZeroAndFromFiveToNineAndTens</span>|<span class="p">RuleForOne</span>|<span class="p">RuleForTwoThreeAndFour</span>|<span class="p">RuleFromElevenToNineteen</span>|) <span onmouseout="hideTip(event, 'fs1', 1)" onmouseover="showTip(event, 'fs1', 1)" class="i">n</span> <span class="o">=</span>
<span class="k">match</span> <span onmouseout="hideTip(event, 'fs1', 2)" onmouseover="showTip(event, 'fs1', 2)" class="i">n</span> <span class="k">with</span>
| <span class="n">0</span> <span class="k">-></span> <span class="p">RuleForZeroAndFromFiveToNineAndTens</span>
| <span class="n">1</span> <span class="k">-></span> <span class="p">RuleForOne</span>
| <span onmouseout="hideTip(event, 'fs2', 3)" onmouseover="showTip(event, 'fs2', 3)" class="i">i</span> <span class="k">when</span> <span onmouseout="hideTip(event, 'fs2', 4)" onmouseover="showTip(event, 'fs2', 4)" class="i">i</span> <span class="o">></span><span class="o">=</span> <span class="n">2</span> <span class="o">&&</span> <span onmouseout="hideTip(event, 'fs2', 5)" onmouseover="showTip(event, 'fs2', 5)" class="i">i</span> <span class="o"><=</span> <span class="n">4</span> <span class="k">-></span> <span class="p">RuleForTwoThreeAndFour</span>
| <span onmouseout="hideTip(event, 'fs2', 6)" onmouseover="showTip(event, 'fs2', 6)" class="i">i</span> <span class="k">when</span> (<span onmouseout="hideTip(event, 'fs2', 7)" onmouseover="showTip(event, 'fs2', 7)" class="i">i</span> <span class="o">%</span> <span class="n">10</span> <span class="o">=</span> <span class="n">1</span> <span class="o">&&</span> <span onmouseout="hideTip(event, 'fs2', 8)" onmouseover="showTip(event, 'fs2', 8)" class="i">i</span> <span class="o">%</span> <span class="n">100</span> <span class="o"><></span> <span class="n">11</span>) <span class="k">-></span> <span class="p">RuleForZeroAndFromFiveToNineAndTens</span>
| <span onmouseout="hideTip(event, 'fs2', 9)" onmouseover="showTip(event, 'fs2', 9)" class="i">i</span> <span class="k">when</span> (<span onmouseout="hideTip(event, 'fs2', 10)" onmouseover="showTip(event, 'fs2', 10)" class="i">i</span> <span class="o">%</span> <span class="n">10</span> <span class="o">=</span> <span class="n">2</span> <span class="o">&&</span> <span onmouseout="hideTip(event, 'fs2', 11)" onmouseover="showTip(event, 'fs2', 11)" class="i">i</span> <span class="o">%</span> <span class="n">100</span> <span class="o"><></span> <span class="n">12</span>) <span class="k">-></span> <span class="p">RuleForTwoThreeAndFour</span>
| <span onmouseout="hideTip(event, 'fs2', 12)" onmouseover="showTip(event, 'fs2', 12)" class="i">i</span> <span class="k">when</span> (<span onmouseout="hideTip(event, 'fs2', 13)" onmouseover="showTip(event, 'fs2', 13)" class="i">i</span> <span class="o">%</span> <span class="n">10</span> <span class="o">=</span> <span class="n">3</span> <span class="o">&&</span> <span onmouseout="hideTip(event, 'fs2', 14)" onmouseover="showTip(event, 'fs2', 14)" class="i">i</span> <span class="o">%</span> <span class="n">100</span> <span class="o"><></span> <span class="n">13</span>) <span class="k">-></span> <span class="p">RuleForTwoThreeAndFour</span>
| <span onmouseout="hideTip(event, 'fs2', 15)" onmouseover="showTip(event, 'fs2', 15)" class="i">i</span> <span class="k">when</span> (<span onmouseout="hideTip(event, 'fs2', 16)" onmouseover="showTip(event, 'fs2', 16)" class="i">i</span> <span class="o">%</span> <span class="n">10</span> <span class="o">=</span> <span class="n">4</span> <span class="o">&&</span> <span onmouseout="hideTip(event, 'fs2', 17)" onmouseover="showTip(event, 'fs2', 17)" class="i">i</span> <span class="o">%</span> <span class="n">100</span> <span class="o"><></span> <span class="n">14</span>) <span class="k">-></span> <span class="p">RuleForTwoThreeAndFour</span>
| <span onmouseout="hideTip(event, 'fs2', 18)" onmouseover="showTip(event, 'fs2', 18)" class="i">i</span> <span class="k">when</span> <span onmouseout="hideTip(event, 'fs2', 19)" onmouseover="showTip(event, 'fs2', 19)" class="i">i</span> <span class="o">%</span> <span class="n">10</span> <span class="o">></span><span class="o">=</span><span class="n">5</span> <span class="o">&&</span> <span onmouseout="hideTip(event, 'fs2', 20)" onmouseover="showTip(event, 'fs2', 20)" class="i">i</span> <span class="o">%</span> <span class="n">10</span> <span class="o"><=</span><span class="n">9</span> <span class="k">-></span> <span class="p">RuleForZeroAndFromFiveToNineAndTens</span>
| <span onmouseout="hideTip(event, 'fs2', 21)" onmouseover="showTip(event, 'fs2', 21)" class="i">i</span> <span class="k">when</span> <span onmouseout="hideTip(event, 'fs2', 22)" onmouseover="showTip(event, 'fs2', 22)" class="i">i</span> <span class="o">></span> <span class="n">10</span> <span class="o">&&</span> <span onmouseout="hideTip(event, 'fs2', 23)" onmouseover="showTip(event, 'fs2', 23)" class="i">i</span> <span class="o"><</span> <span class="n">20</span> <span class="k">-></span> <span class="p">RuleFromElevenToNineteen</span>
| <span onmouseout="hideTip(event, 'fs2', 24)" onmouseover="showTip(event, 'fs2', 24)" class="i">i</span> <span class="k">when</span> <span onmouseout="hideTip(event, 'fs2', 25)" onmouseover="showTip(event, 'fs2', 25)" class="i">i</span> <span class="o">%</span> <span class="n">10</span> <span class="o">=</span> <span class="n">0</span> <span class="k">-></span> <span class="p">RuleForZeroAndFromFiveToNineAndTens</span>
</code></pre>
<p>I could squash some rules together but I think there’s sense to leave it in such a way because it will be easier to maintain. It is simple as it looks, based on given count we compute which rule we should apply.</p>
<h3 id="using-active-pattern">Using active pattern</h3>
<p>Having stated our rules as active pattern, we can easily create function which will help us to display proper form on the UI. Let’s see how it can be done:</p>
<pre class="fssnip highlighted"><code lang="fsharp"><span class="k">let</span> <span onmouseout="hideTip(event, 'fs3', 26)" onmouseover="showTip(event, 'fs3', 26)" class="f">wordDeclination</span> <span onmouseout="hideTip(event, 'fs4', 27)" onmouseover="showTip(event, 'fs4', 27)" class="i">wordForZeroAndFromFiveToNineAndTens</span> <span onmouseout="hideTip(event, 'fs5', 28)" onmouseover="showTip(event, 'fs5', 28)" class="i">wordForOne</span> <span onmouseout="hideTip(event, 'fs6', 29)" onmouseover="showTip(event, 'fs6', 29)" class="i">wordForTwoThreeAndFour</span> <span onmouseout="hideTip(event, 'fs7', 30)" onmouseover="showTip(event, 'fs7', 30)" class="i">wordForElevenToNineteen</span> <span onmouseout="hideTip(event, 'fs1', 31)" onmouseover="showTip(event, 'fs1', 31)" class="i">n</span> <span class="o">=</span>
<span class="k">match</span> <span onmouseout="hideTip(event, 'fs1', 32)" onmouseover="showTip(event, 'fs1', 32)" class="i">n</span> <span class="k">with</span>
| <span onmouseout="hideTip(event, 'fs8', 33)" onmouseover="showTip(event, 'fs8', 33)" class="p">RuleForZeroAndFromFiveToNineAndTens</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs4', 34)" onmouseover="showTip(event, 'fs4', 34)" class="i">wordForZeroAndFromFiveToNineAndTens</span>
| <span onmouseout="hideTip(event, 'fs9', 35)" onmouseover="showTip(event, 'fs9', 35)" class="p">RuleForOne</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs5', 36)" onmouseover="showTip(event, 'fs5', 36)" class="i">wordForOne</span>
| <span onmouseout="hideTip(event, 'fs10', 37)" onmouseover="showTip(event, 'fs10', 37)" class="p">RuleForTwoThreeAndFour</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs6', 38)" onmouseover="showTip(event, 'fs6', 38)" class="i">wordForTwoThreeAndFour</span>
| <span onmouseout="hideTip(event, 'fs11', 39)" onmouseover="showTip(event, 'fs11', 39)" class="p">RuleFromElevenToNineteen</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 40)" onmouseover="showTip(event, 'fs7', 40)" class="i">wordForElevenToNineteen</span>
</code></pre>
<p>Thanks to active patterns we do not have to convolute method with logic that is responsible for selecting appropriate word flexion. Entire core logic is hiden in active pattern declaration.
Using function <code class="highlighter-rouge">wordDeclination</code> we can further create small helper functions which will give a word in correct form. There is one important thing to be aware, here arguments order matters, because take a look if we will move <code class="highlighter-rouge">n</code> argument at the beginning then we won’t be able to apply currying to <code class="highlighter-rouge">n</code> argument. It should be clear if you look how we can use function <code class="highlighter-rouge">wordDeclination</code>:</p>
<pre class="fssnip highlighted"><code lang="fsharp"><span class="k">let</span> <span onmouseout="hideTip(event, 'fs12', 41)" onmouseover="showTip(event, 'fs12', 41)" class="f">forUIWydatekDeclination</span> <span class="o">=</span> <span onmouseout="hideTip(event, 'fs3', 42)" onmouseover="showTip(event, 'fs3', 42)" class="f">wordDeclination</span> <span class="s">"wydatków"</span> <span class="s">"wydatek"</span> <span class="s">"wydatki"</span> <span class="s">"wydatków"</span>
</code></pre>
<p>Here, we partially applied <code class="highlighter-rouge">wordDeclination</code> function in <code class="highlighter-rouge">forUIWydatekDeclination</code> function. As a result <code class="highlighter-rouge">forUIWydatekDeclination</code> takes one argument and it is count of items. Looking again at function <code class="highlighter-rouge">wordDeclination</code>, if we didn’t move the <code class="highlighter-rouge">n</code> argument at the end, then we would have to provide also <code class="highlighter-rouge">n</code> argument for <code class="highlighter-rouge">forUIWydatekDeclination</code> function. We didn’t do that, so <code class="highlighter-rouge">n</code> argument is curried. We can use <code class="highlighter-rouge">forUIWydatekDeclination</code> in following way:</p>
<pre class="fssnip highlighted"><code lang="fsharp"><span onmouseout="hideTip(event, 'fs12', 43)" onmouseover="showTip(event, 'fs12', 43)" class="f">forUIWydatekDeclination</span> <span class="n">22</span>
</code></pre>
<h3 id="summary">Summary</h3>
<p>You may think that this is not rocket science, but as I said earlier those things influence overall user perception about application. Of course you could do that using different manner.
But I think this is neat and clean use case for active patterns.</p>
Reusing intermediate values in F# pipe2016-04-27T00:00:00+00:00https://baks.github.io/2016/04/27/reusing-intermediate-values-in-f-pipe
<h3 id="introduction">Introduction</h3>
<p>Since some time, I have been struggling with one problem regarding pipe operator. Sometimes, I’d like to use intermediate values
arising when pipeline is processed. So, previously I was just splitting entire pipeline and create values from those intermediate values using <code class="highlighter-rouge">let</code> binding.</p>
<h3 id="study-case">Study case</h3>
<p>Let’s take a look at this simple example. We want to split list at place where the highest number appears. So, my previous approach for that was something like this:</p>
<pre class="fssnip highlighted"><code lang="fsharp"><span class="k">let</span> <span onmouseout="hideTip(event, 'fs1', 1)" onmouseover="showTip(event, 'fs1', 1)" class="i">inputList</span> <span class="o">=</span> [<span class="n">5</span>;<span class="n">6</span>;<span class="n">7</span>;<span class="n">8</span>;<span class="n">9</span>;<span class="n">10</span>;<span class="n">4</span>;<span class="n">3</span>;<span class="n">2</span>;<span class="n">1</span>]
<span class="k">let</span> <span onmouseout="hideTip(event, 'fs2', 2)" onmouseover="showTip(event, 'fs2', 2)" class="i">index</span> <span class="o">=</span>
<span onmouseout="hideTip(event, 'fs1', 3)" onmouseover="showTip(event, 'fs1', 3)" class="i">inputList</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 4)" onmouseover="showTip(event, 'fs3', 4)" class="t">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs4', 5)" onmouseover="showTip(event, 'fs4', 5)" class="f">indexed</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 6)" onmouseover="showTip(event, 'fs3', 6)" class="t">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs5', 7)" onmouseover="showTip(event, 'fs5', 7)" class="f">maxBy</span> (<span class="k">fun</span> <span onmouseout="hideTip(event, 'fs6', 8)" onmouseover="showTip(event, 'fs6', 8)" class="i">value</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 9)" onmouseover="showTip(event, 'fs7', 9)" class="f">snd</span> <span onmouseout="hideTip(event, 'fs6', 10)" onmouseover="showTip(event, 'fs6', 10)" class="i">value</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs8', 11)" onmouseover="showTip(event, 'fs8', 11)" class="f">fst</span>
<span onmouseout="hideTip(event, 'fs1', 12)" onmouseover="showTip(event, 'fs1', 12)" class="i">inputList</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 13)" onmouseover="showTip(event, 'fs3', 13)" class="t">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs9', 14)" onmouseover="showTip(event, 'fs9', 14)" class="f">splitAt</span> <span onmouseout="hideTip(event, 'fs2', 15)" onmouseover="showTip(event, 'fs2', 15)" class="i">index</span>
</code></pre>
<p>However, recently I had some sort of breakthrough. I’ve realized that consecutive steps in pipe are just ordinary functions.
Definition of pipe operator follows :</p>
<pre class="fssnip highlighted"><code lang="fsharp"><span class="k">val</span> <span class="k">inline</span> ( <span class="o">|></span> ) <span class="o">:</span> <span class="i">arg</span><span class="o">:</span><span class="o">'</span><span class="i">T1</span> <span class="k">-></span> <span class="i">func</span><span class="o">:</span>(<span class="o">'</span><span class="i">T1</span> <span class="k">-></span> <span class="o">'</span><span class="i">U</span>) <span class="k">-></span> <span class="o">'</span><span class="i">U</span>
</code></pre>
<p>It takes left argument and applies it to right function which takes argument with the same type as left argument of pipeline operator. So, what we are actually passing to pipe operator on the right is function. And actually what we have in our <code class="highlighter-rouge">F#</code> toolset are lambda functions, and they are just functions without binding name to it.</p>
<p>For instance, we can create function using lambda functions, but assign name for it using <code class="highlighter-rouge">let</code> binding:</p>
<pre class="fssnip highlighted"><code lang="fsharp"><span class="k">let</span> <span class="i">identity</span> <span class="o">=</span> <span class="k">fun</span> <span class="i">x</span> <span class="k">-></span> <span class="i">x</span>
</code></pre>
<p>The same, we can when we are composing our pipeline. However, there are some nuances. Because we don’t have to use parentheses to declare lambda function I thought that arguments, which lambda function takes, are immediately available for the rest of pipeline. Unfortunately that’s not true. So, that’s what I tried first:</p>
<pre class="fssnip highlighted"><code lang="fsharp">[<span class="n">5</span>;<span class="n">6</span>;<span class="n">7</span>;<span class="n">8</span>;<span class="n">9</span>;<span class="n">10</span>;<span class="n">4</span>;<span class="n">3</span>;<span class="n">2</span>;<span class="n">1</span>]
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs1', 16)" onmouseover="showTip(event, 'fs1', 16)" class="i">inputList</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 17)" onmouseover="showTip(event, 'fs3', 17)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs4', 18)" onmouseover="showTip(event, 'fs4', 18)" class="i">indexed</span> <span onmouseout="hideTip(event, 'fs1', 19)" onmouseover="showTip(event, 'fs1', 19)" class="i">inputList</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 20)" onmouseover="showTip(event, 'fs3', 20)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs5', 21)" onmouseover="showTip(event, 'fs5', 21)" class="i">maxBy</span> (<span class="k">fun</span> <span class="i">value</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 22)" onmouseover="showTip(event, 'fs7', 22)" class="i">snd</span> <span class="i">value</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs8', 23)" onmouseover="showTip(event, 'fs8', 23)" class="i">fst</span>
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs10', 24)" onmouseover="showTip(event, 'fs10', 24)" class="i">max</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 25)" onmouseover="showTip(event, 'fs3', 25)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs9', 26)" onmouseover="showTip(event, 'fs9', 26)" class="i">splitAt</span> <span onmouseout="hideTip(event, 'fs10', 27)" onmouseover="showTip(event, 'fs10', 27)" class="i">max</span> <span onmouseout="hideTip(event, 'fs1', 28)" onmouseover="showTip(event, 'fs1', 28)" class="i">inputList</span>
</code></pre>
<p>But I got an error</p>
<blockquote>
<p>The value or constructor inputList is not defined.</p>
</blockquote>
<p>That actually makes sense if you know that <code class="highlighter-rouge">F#</code> uses indentation to mark scope boundaries.
It’s better to spot when we add parentheses to lambda function</p>
<pre class="fssnip highlighted"><code lang="fsharp">[<span class="n">5</span>;<span class="n">6</span>;<span class="n">7</span>;<span class="n">8</span>;<span class="n">9</span>;<span class="n">10</span>;<span class="n">4</span>;<span class="n">3</span>;<span class="n">2</span>;<span class="n">1</span>]
<span class="o">|></span> (<span class="k">fun</span> <span onmouseout="hideTip(event, 'fs1', 29)" onmouseover="showTip(event, 'fs1', 29)" class="i">inputList</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 30)" onmouseover="showTip(event, 'fs3', 30)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs4', 31)" onmouseover="showTip(event, 'fs4', 31)" class="i">indexed</span> <span onmouseout="hideTip(event, 'fs1', 32)" onmouseover="showTip(event, 'fs1', 32)" class="i">inputList</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 33)" onmouseover="showTip(event, 'fs3', 33)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs5', 34)" onmouseover="showTip(event, 'fs5', 34)" class="i">maxBy</span> (<span class="k">fun</span> <span class="i">value</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 35)" onmouseover="showTip(event, 'fs7', 35)" class="i">snd</span> <span class="i">value</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs8', 36)" onmouseover="showTip(event, 'fs8', 36)" class="i">fst</span>
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs10', 37)" onmouseover="showTip(event, 'fs10', 37)" class="i">max</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 38)" onmouseover="showTip(event, 'fs3', 38)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs9', 39)" onmouseover="showTip(event, 'fs9', 39)" class="i">splitAt</span> <span onmouseout="hideTip(event, 'fs10', 40)" onmouseover="showTip(event, 'fs10', 40)" class="i">max</span> <span onmouseout="hideTip(event, 'fs1', 41)" onmouseover="showTip(event, 'fs1', 41)" class="i">inputList</span>
</code></pre>
<p>Now, we can see that inputList variable is only visible inside lambda function. So, we can add parentheses to subsequent pipeline steps to make them part of this lambda function and allow inputList variable to be visible.</p>
<pre class="fssnip highlighted"><code lang="fsharp">[<span class="n">5</span>;<span class="n">6</span>;<span class="n">7</span>;<span class="n">8</span>;<span class="n">9</span>;<span class="n">10</span>;<span class="n">4</span>;<span class="n">3</span>;<span class="n">2</span>;<span class="n">1</span>]
<span class="o">|></span> (<span class="k">fun</span> <span onmouseout="hideTip(event, 'fs1', 42)" onmouseover="showTip(event, 'fs1', 42)" class="i">inputList</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 43)" onmouseover="showTip(event, 'fs3', 43)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs4', 44)" onmouseover="showTip(event, 'fs4', 44)" class="i">indexed</span> <span onmouseout="hideTip(event, 'fs1', 45)" onmouseover="showTip(event, 'fs1', 45)" class="i">inputList</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 46)" onmouseover="showTip(event, 'fs3', 46)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs5', 47)" onmouseover="showTip(event, 'fs5', 47)" class="i">maxBy</span> (<span class="k">fun</span> <span class="i">value</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 48)" onmouseover="showTip(event, 'fs7', 48)" class="i">snd</span> <span class="i">value</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs8', 49)" onmouseover="showTip(event, 'fs8', 49)" class="i">fst</span>
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs10', 50)" onmouseover="showTip(event, 'fs10', 50)" class="i">max</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 51)" onmouseover="showTip(event, 'fs3', 51)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs9', 52)" onmouseover="showTip(event, 'fs9', 52)" class="i">splitAt</span> <span onmouseout="hideTip(event, 'fs10', 53)" onmouseover="showTip(event, 'fs10', 53)" class="i">max</span> <span onmouseout="hideTip(event, 'fs1', 54)" onmouseover="showTip(event, 'fs1', 54)" class="i">inputList</span>)
</code></pre>
<p>Hmm, but it’s not looking that sexy, because now <code class="highlighter-rouge">List.index inputList</code> expression puts new identation context at which we must ident subsequent expressions of this function.
However, there’s an exception regarding infix operators, you can offset them from the actual offside column by the size of token plus one, so in that case previous code snippet looks like this:</p>
<pre class="fssnip highlighted"><code lang="fsharp">[<span class="n">5</span>;<span class="n">6</span>;<span class="n">7</span>;<span class="n">8</span>;<span class="n">9</span>;<span class="n">10</span>;<span class="n">4</span>;<span class="n">3</span>;<span class="n">2</span>;<span class="n">1</span>]
<span class="o">|></span> (<span class="k">fun</span> <span onmouseout="hideTip(event, 'fs1', 55)" onmouseover="showTip(event, 'fs1', 55)" class="i">inputList</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 56)" onmouseover="showTip(event, 'fs3', 56)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs4', 57)" onmouseover="showTip(event, 'fs4', 57)" class="i">indexed</span> <span onmouseout="hideTip(event, 'fs1', 58)" onmouseover="showTip(event, 'fs1', 58)" class="i">inputList</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 59)" onmouseover="showTip(event, 'fs3', 59)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs5', 60)" onmouseover="showTip(event, 'fs5', 60)" class="i">maxBy</span> (<span class="k">fun</span> <span class="i">value</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 61)" onmouseover="showTip(event, 'fs7', 61)" class="i">snd</span> <span class="i">value</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs8', 62)" onmouseover="showTip(event, 'fs8', 62)" class="i">fst</span>
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs10', 63)" onmouseover="showTip(event, 'fs10', 63)" class="i">max</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 64)" onmouseover="showTip(event, 'fs3', 64)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs9', 65)" onmouseover="showTip(event, 'fs9', 65)" class="i">splitAt</span> <span onmouseout="hideTip(event, 'fs10', 66)" onmouseover="showTip(event, 'fs10', 66)" class="i">max</span> <span onmouseout="hideTip(event, 'fs1', 67)" onmouseover="showTip(event, 'fs1', 67)" class="i">inputList</span>)
</code></pre>
<p>Back to the topic, what we can do to improve our code’s appearance and still be able to access intermediate values from pipeline?
We can move first expression of lambda function to newline and that would mean next expressions in that function must be indented the same as that line. Take a look:</p>
<pre class="fssnip highlighted"><code lang="fsharp">[<span class="n">5</span>;<span class="n">6</span>;<span class="n">7</span>;<span class="n">8</span>;<span class="n">9</span>;<span class="n">10</span>;<span class="n">4</span>;<span class="n">3</span>;<span class="n">2</span>;<span class="n">1</span>]
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs1', 68)" onmouseover="showTip(event, 'fs1', 68)" class="i">inputList</span> <span class="k">-></span>
<span onmouseout="hideTip(event, 'fs3', 69)" onmouseover="showTip(event, 'fs3', 69)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs4', 70)" onmouseover="showTip(event, 'fs4', 70)" class="i">indexed</span> <span onmouseout="hideTip(event, 'fs1', 71)" onmouseover="showTip(event, 'fs1', 71)" class="i">inputList</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 72)" onmouseover="showTip(event, 'fs3', 72)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs5', 73)" onmouseover="showTip(event, 'fs5', 73)" class="i">maxBy</span> (<span class="k">fun</span> <span class="i">value</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 74)" onmouseover="showTip(event, 'fs7', 74)" class="i">snd</span> <span class="i">value</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs8', 75)" onmouseover="showTip(event, 'fs8', 75)" class="i">fst</span>
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs10', 76)" onmouseover="showTip(event, 'fs10', 76)" class="i">max</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 77)" onmouseover="showTip(event, 'fs3', 77)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs9', 78)" onmouseover="showTip(event, 'fs9', 78)" class="i">splitAt</span> <span onmouseout="hideTip(event, 'fs10', 79)" onmouseover="showTip(event, 'fs10', 79)" class="i">max</span> <span onmouseout="hideTip(event, 'fs1', 80)" onmouseover="showTip(event, 'fs1', 80)" class="i">inputList</span>
</code></pre>
<p>But now, we break how pipeline looks like, and I feel this is not intuitive. We can take advantage of previously mentioned exception for infix operators. Anyway, I feel it is improved a litte bit but still doesn’t solve the issue.</p>
<pre class="fssnip highlighted"><code lang="fsharp">[<span class="n">5</span>;<span class="n">6</span>;<span class="n">7</span>;<span class="n">8</span>;<span class="n">9</span>;<span class="n">10</span>;<span class="n">4</span>;<span class="n">3</span>;<span class="n">2</span>;<span class="n">1</span>]
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs1', 81)" onmouseover="showTip(event, 'fs1', 81)" class="i">inputList</span> <span class="k">-></span>
<span onmouseout="hideTip(event, 'fs3', 82)" onmouseover="showTip(event, 'fs3', 82)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs4', 83)" onmouseover="showTip(event, 'fs4', 83)" class="i">indexed</span> <span onmouseout="hideTip(event, 'fs1', 84)" onmouseover="showTip(event, 'fs1', 84)" class="i">inputList</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 85)" onmouseover="showTip(event, 'fs3', 85)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs5', 86)" onmouseover="showTip(event, 'fs5', 86)" class="i">maxBy</span> (<span class="k">fun</span> <span class="i">value</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 87)" onmouseover="showTip(event, 'fs7', 87)" class="i">snd</span> <span class="i">value</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs8', 88)" onmouseover="showTip(event, 'fs8', 88)" class="i">fst</span>
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs10', 89)" onmouseover="showTip(event, 'fs10', 89)" class="i">max</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 90)" onmouseover="showTip(event, 'fs3', 90)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs9', 91)" onmouseover="showTip(event, 'fs9', 91)" class="i">splitAt</span> <span onmouseout="hideTip(event, 'fs10', 92)" onmouseover="showTip(event, 'fs10', 92)" class="i">max</span> <span onmouseout="hideTip(event, 'fs1', 93)" onmouseover="showTip(event, 'fs1', 93)" class="i">inputList</span>
</code></pre>
<p>I feel the most comfortable if we ident lambda function expressions a bit to explicitly denote that they belong to that function</p>
<pre class="fssnip highlighted"><code lang="fsharp">[<span class="n">5</span>;<span class="n">6</span>;<span class="n">7</span>;<span class="n">8</span>;<span class="n">9</span>;<span class="n">10</span>;<span class="n">4</span>;<span class="n">3</span>;<span class="n">2</span>;<span class="n">1</span>]
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs1', 94)" onmouseover="showTip(event, 'fs1', 94)" class="i">inputList</span> <span class="k">-></span>
<span onmouseout="hideTip(event, 'fs1', 95)" onmouseover="showTip(event, 'fs1', 95)" class="i">inputList</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 96)" onmouseover="showTip(event, 'fs3', 96)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs4', 97)" onmouseover="showTip(event, 'fs4', 97)" class="i">indexed</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 98)" onmouseover="showTip(event, 'fs3', 98)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs5', 99)" onmouseover="showTip(event, 'fs5', 99)" class="i">maxBy</span> (<span class="k">fun</span> <span class="i">value</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 100)" onmouseover="showTip(event, 'fs7', 100)" class="i">snd</span> <span class="i">value</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs8', 101)" onmouseover="showTip(event, 'fs8', 101)" class="i">fst</span>
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs10', 102)" onmouseover="showTip(event, 'fs10', 102)" class="i">max</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs3', 103)" onmouseover="showTip(event, 'fs3', 103)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs9', 104)" onmouseover="showTip(event, 'fs9', 104)" class="i">splitAt</span> <span onmouseout="hideTip(event, 'fs10', 105)" onmouseover="showTip(event, 'fs10', 105)" class="i">max</span> <span onmouseout="hideTip(event, 'fs1', 106)" onmouseover="showTip(event, 'fs1', 106)" class="i">inputList</span>
</code></pre>
<p>We can do one more thing to get rid of last lambda function, we can define helper function <code class="highlighter-rouge">flip</code> which does one simple thing. It allows to flip arguments which will be passed to given function. Finally, pipeline looks like this</p>
<pre class="fssnip highlighted"><code lang="fsharp"><span class="k">let</span> <span class="k">inline</span> <span class="i">flip</span> <span class="i">f</span> <span class="i">x</span> <span class="i">y</span> <span class="o">=</span> <span class="i">f</span> <span class="i">y</span> <span class="i">x</span>
[<span class="n">5</span>;<span class="n">6</span>;<span class="n">7</span>;<span class="n">8</span>;<span class="n">9</span>;<span class="n">10</span>;<span class="n">4</span>;<span class="n">3</span>;<span class="n">2</span>;<span class="n">1</span>]
<span class="o">|></span> <span class="k">fun</span> <span onmouseout="hideTip(event, 'fs1', 107)" onmouseover="showTip(event, 'fs1', 107)" class="i">inputList</span> <span class="k">-></span>
<span onmouseout="hideTip(event, 'fs1', 108)" onmouseover="showTip(event, 'fs1', 108)" class="i">inputList</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 109)" onmouseover="showTip(event, 'fs3', 109)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs4', 110)" onmouseover="showTip(event, 'fs4', 110)" class="i">indexed</span>
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs3', 111)" onmouseover="showTip(event, 'fs3', 111)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs5', 112)" onmouseover="showTip(event, 'fs5', 112)" class="i">maxBy</span> (<span class="k">fun</span> <span class="i">value</span> <span class="k">-></span> <span onmouseout="hideTip(event, 'fs7', 113)" onmouseover="showTip(event, 'fs7', 113)" class="i">snd</span> <span class="i">value</span>)
<span class="o">|></span> <span onmouseout="hideTip(event, 'fs8', 114)" onmouseover="showTip(event, 'fs8', 114)" class="i">fst</span>
<span class="o">|></span> <span class="i">flip</span> <span onmouseout="hideTip(event, 'fs3', 115)" onmouseover="showTip(event, 'fs3', 115)" class="i">List</span><span class="o">.</span><span onmouseout="hideTip(event, 'fs9', 116)" onmouseover="showTip(event, 'fs9', 116)" class="i">splitAt</span> <span onmouseout="hideTip(event, 'fs1', 117)" onmouseover="showTip(event, 'fs1', 117)" class="i">inputList</span>
</code></pre>
<h3 id="summary">Summary</h3>
<p>We’ve seen how we can reuse intermediate values from pipeline using lambda functions.
Of course these are not all possibilities of how you can write that pipeline. I hope you will find something useful here, but just use a way that you feel more comfortable with.</p>
Learning functional programming2016-03-16T00:00:00+00:00https://baks.github.io/2016/03/16/learning-functional-programming
<p>It’s been some time since I wrote last post. I hope, now I will be able to write posts more often. Although, it is getting warmer here in Poland, so hiking and cycling will be possible :)</p>
<h3 id="functional-paradigm-everywhere">Functional paradigm everywhere</h3>
<p>Nowadays, functional paradigm is quite popular. <code class="highlighter-rouge">Java</code> has got some features known from functional languages as well as <code class="highlighter-rouge">C#</code>. There’s assumption that functional programming is a way to solve problems we have now in object oriented programming. You can find some blog entry, video tutorial, workshop, presentation everywhere, where someone is talking about how to approach your code by functional programming.
Many people think that functional programming is about immutability. But it is not. You can have immutable types also in <code class="highlighter-rouge">C#</code> or <code class="highlighter-rouge">Java</code>. You don’t have it out of the box, but it is possible. Even more, immutability appeared many years ago, for example Eric Evans in his blue book was talking about immutable value objects and how they help to build code, which is easy to maintain and work on. Not to even mention about advantages when it comes to parallelism.
Being functional means composing higher order functions of small functions. Those functions are so small that we can test them easily and quickly.</p>
<h3 id="how-we-learnt-oo-">How we learnt OO ?</h3>
<p>It seems that we had similar situation before, when object-oriented programming had its time. It was introduced as a better solution than procedural programming. Do you remember how at university we were first introduced to procedural programming and then to object-oriented programming? At the beginning each of us was writing procedural code using object-oriented language. And still many of us are. They introduced us to object orientation in such a way that we have <code class="highlighter-rouge">Shape</code> and from <code class="highlighter-rouge">Shape</code> we can derive <code class="highlighter-rouge">Circle</code>, <code class="highlighter-rouge">Rectangle</code> and so on. And we believed that this is the root what object orientation is about. How to define data in reusable way, that they share common characteristics and how to leverage inheritance. However, we suddenly get into problems like <a href="https://en.wikipedia.org/wiki/Fragile_base_class">Fragile Base Class</a> using this approach.
It’s not possible to write generic code that it will handle every cases, is it?. To be honest, think a while how it’s easy to explain such an approach to OO even to your mum. Because it’s similar to what we have in our life. Every rectangle is a shape, isn’t it? This is the same reason why they explained to us in such a way at university.</p>
<h3 id="another-view-at-oo">Another view at OO</h3>
<p>For a while let’s back to Alan Kay (considered by some as father of object-oriented programming) famous sentence:</p>
<blockquote>
<p>It’s all about messaging.</p>
</blockquote>
<p>There is another view at object-oriented systems. Key is to focus on how objects communicate with each other. What messages they send? Object can receive message, takes parameters and send message to another object or return response. It’s easy to understand when you take a look at <code class="highlighter-rouge">Smalltalk</code> language because there notion of sending messages is explicit. For me it’s quite different view from that one focusing on the structure. I think it’s better because it makes that we think in terms of objects. And then objects are not only holders for data. They play their own roles, they have their responsibilities. They must have their state encapsulated properly, because inproper messages can corrupt object. Proper naming becomes then much more important. Names of objects must reflect what role objects play and must reflect domain. Then it’s easy to reason about it.
When you are looking at OO system using messaging approach, then you realize how important principles like Tell Don’t Ask or Law of Demeter are. To be honest, SOLID rules become more clear. And they pretty good fit to this view.</p>
<h3 id="learn-by-ones-mistakes">Learn by one’s mistakes</h3>
<p>So now I also got a little bit into functional programming. It’s very entertaining for somebody so far familiar with OO languages. I like description that functional programming is about defining recipes for our data. And after that composing functions to perform interesting behavior for us. And those functions are so small that we can test them easily and quickly in REPL environment. This is a huge advantage that we can play with functions at REPL. Also thanks to immutability which is built-in into functional language, compilers can make some additional steps to compile such code to executable code. To be honest, I’m amazed by functional programming. I’m trying to play with Haskell, to learn functional programming correctly. I don’t want to make the same mistake as with OOP, because it took me some time to understand benefits of it (or that’s what I think - as always it is opinionated view). At the end of the day, ultimate goal is to write idiomatic functional code without heritage from OOP.</p>
LINQ Except method explanation2015-12-14T00:00:00+00:00https://baks.github.io/2015/12/14/linq-except-method-explanation
<p><code class="highlighter-rouge">LINQ</code> has been in .NET from 3.5 version. It simplifies a lot many tasks, allowing expressing data processing in more declarative manner. You probably had an occasion to use <code class="highlighter-rouge">Except</code> method. But, do you know exact workings of <code class="highlighter-rouge">Except</code> method?</p>
<p>At <a href="https://msdn.microsoft.com/library/bb300779%28v=vs.100%29.aspx">MSDN</a> we can find that :</p>
<blockquote>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">static</span> <span class="nc">IEnumerable</span><span class="p"><</span><span class="nc">TSource</span><span class="p">></span> <span class="n">Except</span><span class="p"><</span><span class="nc">TSource</span><span class="p">>(</span>
<span class="k">this</span> <span class="nc">IEnumerable</span><span class="p"><</span><span class="nc">TSource</span><span class="p">></span> <span class="n">first</span><span class="p">,</span>
<span class="nc">IEnumerable</span><span class="p"><</span><span class="nc">TSource</span><span class="p">></span> <span class="n">second</span>
<span class="p">)</span>
</code></pre></div>
</blockquote>
<blockquote>
<p>Produces the set difference of two sequences by using the default equality comparer to compare values.<br /></p>
</blockquote>
<p>Having above information, do you have any idea, what would be written into the console when following code is executed?</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">var</span> <span class="n">invalidChars</span> <span class="p">=</span> <span class="nc">Path</span><span class="p">.</span><span class="n">GetInvalidFileNameChars</span><span class="p">();</span>
<span class="k">var</span> <span class="n">fileName</span> <span class="p">=</span> <span class="s">"Availability"</span><span class="p">;</span>
<span class="k">var</span> <span class="n">sanitizedFileName</span> <span class="p">=</span> <span class="k">new</span> <span class="kt">string</span><span class="p">(</span><span class="n">fileName</span><span class="p">.</span><span class="n">Except</span><span class="p">(</span><span class="n">invalidChars</span><span class="p">).</span><span class="n">ToArray</span><span class="p">());</span>
<span class="nc">Console</span><span class="p">.</span><span class="n">WriteLine</span><span class="p">(</span><span class="n">sanitizedFileName</span><span class="p">);</span>
</code></pre></div>
<p>If you initially thought that output will be <em>Availability</em> you are wrong. This is also I thought at first. But there is subtle point in <code class="highlighter-rouge">MSDN</code> explanation of <code class="highlighter-rouge">Except</code> method. It would treat sequences as <em>sets</em>. That means there will be no elements in output sequence from second sequence. This is no surprise. But this also means that every element from the first sequence, which appears more than once, will be omitted in result.</p>
<p>To achieve required behavior, we need a method that would produce the difference between two sequences, so we can do:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">static</span> <span class="nc">IEnumerable</span><span class="p"><</span><span class="nc">TSource</span><span class="p">></span> <span class="n">Without</span><span class="p"><</span><span class="nc">TSource</span><span class="p">>(</span>
<span class="k">this</span> <span class="nc">IEnumerable</span><span class="p"><</span><span class="nc">TSource</span><span class="p">></span> <span class="n">first</span><span class="p">,</span>
<span class="nc">IEnumerable</span><span class="p"><</span><span class="nc">TSource</span><span class="p">></span> <span class="n">second</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span><span class="p">(</span><span class="n">first</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nc">ArgumentNullException</span><span class="p">(</span><span class="s">"first"</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">if</span><span class="p">(</span><span class="n">second</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nc">ArgumentNullException</span><span class="p">(</span><span class="s">"second"</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">return</span> <span class="nf">WithoutIterator</span><span class="p">(</span><span class="n">first</span><span class="p">,</span> <span class="n">second</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">static</span> <span class="nc">IEnumerable</span><span class="p"><</span><span class="n">TSource</span><span class="p">></span> <span class="n">WithoutIterator</span><span class="p"><</span><span class="nc">TSource</span><span class="p">>(</span><br /> <span class="nc">IEnumerable</span><span class="p"><</span><span class="nc">TSource</span><span class="p">></span> <span class="n">first</span><span class="p">,</span><br /> <span class="nc">IEnumerable</span><span class="p"><</span><span class="nc">TSource</span><span class="p">></span> <span class="n">second</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">var</span> <span class="n">withoutElements</span> <span class="p">=</span> <span class="k">new</span> <span class="nc">HashSet</span><span class="p"><</span><span class="nc">TSource</span><span class="p">>(</span><span class="n">second</span><span class="p">);</span>
<span class="k">foreach</span><span class="p">(</span><span class="k">var</span> <span class="n">element</span> <span class="k">in</span> <span class="n">first</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span><span class="p">(!</span><span class="n">withoutElements</span><span class="p">.</span><span class="n">Contains</span><span class="p">(</span><span class="n">element</span><span class="p">))</span>
<span class="p">{</span>
<span class="k">yield</span> <span class="k">return</span> <span class="n">element</span><span class="p">;</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<h3 id="summary">Summary</h3>
<p><code class="highlighter-rouge">Except</code> method is little misleading. When we read the example with sanitizing file name, I bet most of us think that the only <code class="highlighter-rouge">invalidChars</code> will be removed from <code class="highlighter-rouge">fileName</code>. It is good to know that to avoid further confusion. And if we do not want to treat sequences as sets we could always resort to the method like <code class="highlighter-rouge">Without</code> which is shown above.</p>
Design patterns koans - koan #12015-12-05T00:00:00+00:00https://baks.github.io/2015/12/05/design-patterns-koans
<p>Exercises that are intended to check your knowledge of language or teach something about it are called <a href="https://en.wikipedia.org/wiki/K%C5%8Dan">Koans</a>. For example you can find koans for JavaScript language <a href="https://github.com/liammclennan/JavaScript-Koans">here</a>.</p>
<p>Often, I find that applying solution to some problem later turns out that it was a design pattern. So, I thought that it would be good to describe the context of a problem and leave it to figure out the solution as an exercise for you, dear reader. As the mentioned koans contain tests which initially fails, I will try to do the same and also create a suite of tests which should tell you if your solution is good.</p>
<h3 id="problem-context">Problem context</h3>
<p>Let’s assume that we use <a href="http://martinfowler.com/eaaDev/DomainEvent.html">domain event pattern</a> for notifying about events in our system. This is also handy when we want to use <a href="http://martinfowler.com/eaaDev/EventSourcing.html">Event Sourcing</a>. We have a domain event definition that is simply marker interface and looks like this:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">interface</span> <span class="nc">IDomainEvent</span>
<span class="p">{</span>
<span class="p">}</span>
</code></pre></div>
<p>We also have an interface for event handlers which are used to mark implementation that will handle these events:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">interface</span> <span class="nc">IEventHandler</span><span class="p"><</span><span class="nc">T</span><span class="p">></span>
<span class="p">{</span>
<span class="k">void</span> <span class="nf">Handle</span><span class="p">(</span><span class="nc">T</span> <span class="n">domainEvent</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div>
<p>But, new requirement shows up and we need to introduce a <a href="https://github.com/MassTransit/MassTransit">MassTransit library</a> because in the near future we want to use queue messaging system to reliably deliver domain events. So we change our <code class="highlighter-rouge">IEventHandler<T></code> definition to implement <code class="highlighter-rouge">IConsumer<T></code> interface from <code class="highlighter-rouge">MassTransit</code>.</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">interface</span> <span class="nc">IEventHandler</span><span class="p"><</span><span class="nc">T</span><span class="p">></span> <span class="p">:</span> <span class="nc">IConsumer</span><span class="p"><</span><span class="nc">T</span><span class="p">></span> <span class="k">where</span> <span class="nc">T</span> <span class="p">:</span> <span class="k">class</span><span class="p">,</span> <span class="nc">IDomainEvent</span>
<span class="p">{</span>
<span class="k">void</span> <span class="nf">Handle</span><span class="p">(</span><span class="nc">T</span> <span class="n">domainEvent</span><span class="p">);</span>
<span class="p">}</span>
</code></pre></div>
<p>Now, we can use our event handlers along with <code class="highlighter-rouge">MassTransit</code>.</p>
<p>You can find entire solution <a href="https://github.com/baks/DesignPatternsKoans/tree/master/KoanOne">here</a>. There is a simple console application that uses <code class="highlighter-rouge">MassTransit</code> to send messages over bus and shows that everything works. There are also unit tests which initially fails (tests are written using <a href="https://github.com/nunit/nunit">NUnit 3</a>). The first failing test states that <code class="highlighter-rouge">IEventHandler</code> for <code class="highlighter-rouge">UserCreated</code> event should not be assignable from <code class="highlighter-rouge">IConsumer<T></code> <code class="highlighter-rouge">MassTransit</code> interface. The second test states that DomainModel should not have any references to <code class="highlighter-rouge">MassTransit</code> library.</p>
<h3 id="why-bother">Why bother?</h3>
<p>In spirit of the Ports and Adapters architecture we should try to make our domain context independent. Using interface that we do not own from external library make the domain polluted with infrastructural concerns. Also that domain is not reusable if we want to switch to another message library. New domain module, that deals with events must also take dependency to <code class="highlighter-rouge">MassTransit</code>. What we learned in blue book, is that we should isolate domain model from other code.</p>
<h3 id="summary">Summary</h3>
<p>Every craftsmen who would like to become better must practice, as we can read in <a href="http://manifesto.softwarecraftsmanship.org/">Manifesto for Software Craftsmanship</a>. Therefore, I strongly encourage you to <a href="https://github.com/baks/DesignPatternsKoans#fork-destination-box">fork</a>, and try to change the code to make all tests pass. As you know I designed it to apply design pattern to solve the problem. However, this is not only solution, that you may think of. But I designed it having in mind a particular design pattern, so that’s why I called it ‘design pattern koans’.</p>
Simple pattern matching in C#2015-11-08T00:00:00+00:00https://baks.github.io/2015/11/08/simple-pattern-matching-in-c
<p>Nowadays, functional languages are becoming very popular. Few years ago we thought that the object orientation would be the answer for complexity in systems. But now, there is a belief that functional languages are the new solution. We will see what is gonna be the “thing” in the next years.</p>
<p>Lately, I had an occasion to apply one of feature from functional languages i.e pattern matching to code written in C#. But let’s start from the beginning.</p>
<h3 id="switch-statement-case-study">Switch statement case study</h3>
<p>Couple days ago, I encountered a piece of code which you can find below. It checks which hint is passed to the method. Then, it returns appropriate provider.</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="nc">IHintProvider</span> <span class="nf">GetHintProvider</span><span class="p">(</span><span class="kc">string</span> <span class="n">hint</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">switch</span> <span class="p">(</span><span class="n">hint</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">case</span> <span class="n">HintOne</span><span class="p">:</span>
<span class="k">return</span> <span class="k">new</span> <span class="nc">HintOneProvider</span><span class="p">();</span>
<span class="k">case</span> <span class="n">HintTwo</span><span class="p">:</span>
<span class="k">return</span> <span class="k">new</span> <span class="nc">HintTwoProvider</span><span class="p">();</span>
<span class="k">case</span> <span class="n">HintThree</span><span class="p">:</span>
<span class="k">return</span> <span class="k">new</span> <span class="nc">HintThreeProvider</span><span class="p">();</span>
<span class="k">case</span> <span class="n">HintFour</span><span class="p">:</span>
<span class="k">return</span> <span class="k">new</span> <span class="nc">HintFourProvider</span><span class="p">();</span>
<span class="p">}</span>
<span class="k">return</span> <span class="k">new</span> <span class="nc">NullHintProvider</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div>
<p>It looks like a procedural code and I felt bad about the code, especially that I made it and probably forgot to refactor it. Nevertheless, it is not as worst as it could be, because for example it could have used the <code class="highlighter-rouge">if</code> and <code class="highlighter-rouge">else if</code> statements.</p>
<h3 id="table-driven-methods">Table-driven methods</h3>
<p>I started to look for better alternatives, whether I can refactor this slightly to reduce the switch statement noise. This led me to a table-driven method. I have known it before from <a href="http://amzn.com/0735619670">Code Complete book</a>. Basically it means, that sometimes we can precompute answers for given paths and store it in a table (or in our case in dictionary). Then, given an argument we just do lookup and return stored value. Owing to using this technique, we can now refactor <code class="highlighter-rouge">GetHintProvider</code> method:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">private</span> <span class="k">readonly</span> <span class="nc">IDictionary</span><span class="p"><</span><span class="kt">string</span><span class="p">,</span> <span class="nc">IHintProvider</span><span class="p">></span> <span class="n">providers</span> <span class="p">=</span> <span class="k">new</span> <span class="nc">Dictionary</span><span class="p"><</span><span class="kt">string</span><span class="p">,</span> <span class="nc">IHintProvider</span><span class="p">></span>
<span class="p">{</span>
<span class="p">{</span><span class="n">HintOne</span><span class="p">,</span> <span class="k">new</span> <span class="nc">HintOneProvider</span><span class="p">()},</span>
<span class="p">{</span><span class="n">HintTwo</span><span class="p">,</span> <span class="k">new</span> <span class="nc">HintTwoProvider</span><span class="p">()},</span>
<span class="p">{</span><span class="n">HintThree</span><span class="p">,</span> <span class="k">new</span> <span class="nc">HintThreeProvider</span><span class="p">()},</span>
<span class="p">{</span><span class="n">HintFour</span><span class="p">,</span> <span class="k">new</span> <span class="nc">HintFourProvider</span><span class="p">()}</span>
<span class="p">};</span>
<span class="k">public</span> <span class="nc">IHintProvider</span> <span class="nf">GetHintProvider</span><span class="p">(</span><span class="kc">string</span> <span class="n">hint</span><span class="p">)</span> <span class="p">=></span>
<span class="n">providers</span><span class="p">.</span><span class="n">ContainsKey</span><span class="p">(</span><span class="n">hint</span><span class="p">)</span> <span class="p">?</span> <span class="n">providers</span><span class="p">[</span><span class="n">hint</span><span class="p">]</span> <span class="p">:</span> <span class="k">new</span> <span class="nc">NullHintProvider</span><span class="p">();</span>
</code></pre></div>
<h3 id="simple-pattern-matching">Simple pattern matching</h3>
<p>But, as you can see the syntax of creating dictionary mimics somewhat the pattern matching feature from functional languages. I have been wondering if we are able to use this construction to create a simple pattern matching functionality in <code class="highlighter-rouge">C#</code>. It turns out, that <code class="highlighter-rouge">C#</code> compiler in some situations uses kinda <a href="https://en.wikipedia.org/wiki/Duck_typing">duck-typing</a>. If a type implements <code class="highlighter-rouge">IEnumerable</code>, we can use collection initializer while creating object instance of that type. Instances passed in collection initializer compiler translates to corresponding <code class="highlighter-rouge">Add</code> methods with matching signature. Given that, we can create <code class="highlighter-rouge">Match</code> class that stores patterns and associates code with them to execute when pattern matches. With that, we can write <code class="highlighter-rouge">GetHintProvider</code> method as following:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="nc">IHintProvider</span> <span class="nf">GetHintProvider</span><span class="p">(</span><span class="kc">string</span> <span class="n">hint</span><span class="p">)</span> <span class="p">=></span>
<span class="k">new</span> <span class="nc">MatchFunc</span><span class="p"><</span><span class="kc">string</span><span class="p">,</span> <span class="nc">IHintProvider</span><span class="p">></span>
<span class="p">{</span>
<span class="p">{</span><span class="n">HintOne</span><span class="p">,</span> <span class="n">s</span> <span class="p">=></span> <span class="k">new</span> <span class="nc">HintOneProvider</span><span class="p">()},</span>
<span class="p">{</span><span class="n">HintTwo</span><span class="p">,</span> <span class="n">s</span> <span class="p">=></span> <span class="k">new</span> <span class="nc">HintTwoProvider</span><span class="p">()},</span>
<span class="p">{</span><span class="n">HintThree</span><span class="p">,</span> <span class="n">s</span> <span class="p">=></span> <span class="k">new</span> <span class="nc">HintThreeProvider</span><span class="p">()},</span>
<span class="p">{</span><span class="n">HintFour</span><span class="p">,</span> <span class="n">s</span> <span class="p">=></span> <span class="k">new</span> <span class="nc">HintFourProvider</span><span class="p">()},</span>
<span class="p">{</span><span class="nc">Match</span><span class="p">.</span><span class="n">Default</span><span class="p">,</span> <span class="n">s</span> <span class="p">=></span> <span class="k">new</span> <span class="nc">NullHintProvider</span><span class="p">()</span> <span class="p">}</span>
<span class="p">}.</span><span class="n">Func</span><span class="p">(</span><span class="n">hint</span><span class="p">).</span><span class="n">Single</span><span class="p">();</span>
</code></pre></div>
<p>Now, the code looks nice to me and it is more declarative than the original example.</p>
<p>If you are interested in, you can check code for <code class="highlighter-rouge">MatchFunc</code> class <a href="https://github.com/baks/PatternMatching/tree/master/src/SimplePatternMatching">here</a>.</p>
<h3 id="summary">Summary</h3>
<p>Being declarative, expressing intent of code is an advantage of functional languages, that is presented as opposite to imperative code. Actually, I think code is easier to understand and to maintain. I’m curios whether <code class="highlighter-rouge">C#</code> language engineers have thought that its collection initializers syntactic sugar could be used in such a way. If not, it is interesting how the solution to problem in software field can be used in not foreseen ways later.</p>
Creating decorator around large interface - from improvement to contribution2015-10-30T00:00:00+00:00https://baks.github.io/2015/10/30/creating-decorator-around-large-interface---from-improvement-to-contribution
<p>Recently, I’ve caught myself that I was creating <a href="https://en.wikipedia.org/wiki/Decorator_pattern">decorator</a> around interface which has quite a few methods. I was interested only in one particular method, whereas for the others I had to delegate a call to the decoratee. Thus, it was tedious. This leads me to searching a way for doing this task automatically.</p>
<p>Apart from that, we could argue that the interface does not follow <a href="https://en.wikipedia.org/wiki/Interface_segregation_principle">Integrace Segregation Principle</a> as Robert C. Martin pointed out that
>Clients should not be forced to depend upon methods that they do not use.</p>
<p>Unfortunately, we often work with code which we can’t change and that’s the case here.</p>
<h4 id="know-your-tools">Know your tools</h4>
<p>I use <em>ReSharper</em>, so at the beginning I started to look if it can help with that. I started with the following code:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">CachingRepository</span> <span class="p">:</span> <span class="nc">IRepository</span>
<span class="p">{</span>
<span class="p">}</span>
</code></pre></div>
<p>After couple minutes of investigation, I found that if code generation pop-up is invoked (<code class="highlighter-rouge">Alt+Enter</code>) there is an option <em>Delegating members</em>, but it is unavailable. So, I thought that maybe I should add to my class a field of interface type, which I want to decorate.</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">CachingRepository</span> <span class="p">:</span> <span class="nc">IRepository</span>
<span class="p">{</span>
<span class="k">private</span> <span class="k">readonly</span> <span class="nc">IRepository</span> <span class="n">repository</span><span class="p">;</span>
<span class="p">}</span>
</code></pre></div>
<p>After that step, the option <em>Delegating members</em> became available. Moreover, if caret position is on the class name and we press the shortcut for context actions (<code class="highlighter-rouge">Ctrl+Enter</code>), there is also an action <em>Delegate implementation to ‘repository’ field</em> available.</p>
<p><em>Visual Studio 2015</em>, also offers quick actions, which are indicated by light bulb. We can invoke quick actions by using <code class="highlighter-rouge">Ctrl+.</code> shortcut. In earlier mentioned code snippet, if we put caret on interface name in type list of decorator, there would be actions offered by <em>Visual Studio</em>. One of the available fixes is <em>Implement interface through ‘repository’</em>, which produces the same results as the <em>ReSharper</em> code generation option.</p>
<h4 id="more-automation">More automation</h4>
<p>I wondered why there is a requirement to include the field in class for the options to be available. After all, the field could be auto-generated. We can go even further and generate constructor with the decoratee as a parameter.</p>
<p>Let’s assume that we want to create a decorator around <code class="highlighter-rouge">IRepository</code> interface and we have:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">CachingRepository</span> <span class="p">:</span> <span class="nc">IRepository</span>
<span class="p">{</span>
<span class="p">}</span>
</code></pre></div>
<p>Why can’t a tool do the work for us and generate following code?</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">CachingRepository</span> <span class="p">:</span> <span class="nc">IRepository</span>
<span class="p">{</span>
<span class="k">private</span> <span class="k">readonly</span> <span class="nc">IRepository</span> <span class="n">repository</span><span class="p">;</span>
<span class="k">public</span> <span class="nf">CachingRepository</span><span class="p">(</span><span class="nc">IRepository</span> <span class="n">repository</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">repository</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nc">ArgumentNullException</span><span class="p">(</span><span class="k">nameof</span><span class="p">(</span><span class="n">repository</span><span class="p">));</span>
<span class="p">}</span>
<span class="k">this</span><span class="p">.</span><span class="n">repository</span> <span class="p">=</span> <span class="n">repository</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">Save</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">repository</span><span class="p">.</span><span class="n">Save</span><span class="p">();</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">Delete</span><span class="p">()</span>
<span class="p">{</span>
<span class="n">repository</span><span class="p">.</span><span class="n">Delete</span><span class="p">();</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<p>Nowadays, thanks to <a href="https://github.com/dotnet/roslyn">Roslyn</a> kind of task like that are much easier to implement. I thought about implementing it, but as I contribute to <a href="https://github.com/code-cracker/code-cracker">code-cracker</a> project I came up with idea that this would be a good place to propose it as a new refactoring. Code-cracker is an analyzer library which provides helpful analysis and refactorings while you are writing C# (or VB) code. I created <a href="https://github.com/code-cracker/code-cracker/issues/572">new issue</a> in code-cracker project with details how the refactoring should work. Maybe someone else would be eager to implement it, unless I do it by myself.</p>
<h4 id="summary">Summary</h4>
<p>I’m quite surprised, how the idea of adhering to the <a href="https://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY principle</a> turned into a contribution to the code-cracker project. In growing OSS world it is valuable to share your ideas because someone else might find it useful. We just need to find appropriate place where the idea could be used.</p>
Testing for equality2015-10-26T00:00:00+00:00https://baks.github.io/2015/10/26/testing-for-equality
<p>Often, while writing code we discover value objects in our application. Further, we also need to perform some operation on that types that involve determining equality of our value objects.
In <code class="highlighter-rouge">.NET</code> there are established rules how to properly implement equality, but testing equality in value objects involves quite a lot of repetitive work.
Let’s see what we can do with that and adhere to <a href="https://en.wikipedia.org/wiki/Don't_repeat_yourself">DRY principle</a>. At first let’s review the rules that we should take into account while implementing equality.</p>
<h4 id="things-you-should-remember-while-implementing-equality">Things you should remember while implementing equality</h4>
<p>According to various resources, we should adhere to the properties of equality implementation, which are mentioned for example at <a href="https://msdn.microsoft.com/en-us/library/dd183755.aspx">MSDN</a>.</p>
<p>So, the implementation of equality should:</p>
<ul>
<li>be <em>reflexive</em></li>
</ul>
<p><code class="highlighter-rouge">x.Equals(x)</code> returns <code class="highlighter-rouge">true</code></p>
<ul>
<li>be <em>symmetric</em></li>
</ul>
<p><code class="highlighter-rouge">x.Equals(y) == y.Equals(x)</code></p>
<ul>
<li>be <em>transitive</em></li>
</ul>
<p><code class="highlighter-rouge">x.Equals(y) && y.Equals(z) == true</code> then <code class="highlighter-rouge">x.Equals(z) == true</code></p>
<ul>
<li>be <em>consistent</em></li>
</ul>
<p>Invocations of <code class="highlighter-rouge">x.Equals(y)</code> return the same value as long as the values in <code class="highlighter-rouge">x</code> or <code class="highlighter-rouge">y</code> are not modified or references are not changed</p>
<ul>
<li>return <code class="highlighter-rouge">false</code> when compared against <code class="highlighter-rouge">null</code></li>
</ul>
<p><code class="highlighter-rouge">x.Equals(null) == false</code></p>
<p>We should also override <code class="highlighter-rouge">GetHashCode</code> method when overriding <code class="highlighter-rouge">Equals</code> method, even compiler reminds us (as a warning) about that. This is due to implementation of many <code class="highlighter-rouge">.NET</code> classes (for example <code class="highlighter-rouge">Hashtable</code> or <code class="highlighter-rouge">Dictionary</code>), because they rely on the rule that if two objects are equal, they should return the same hash code value.</p>
<h4 id="nice-when-you-do-it-when-implementing-equality">Nice, when you do it when implementing equality</h4>
<p>There are also other guidelines which are good to use while implementing equality:</p>
<ul>
<li>Overload <code class="highlighter-rouge">==</code> and <code class="highlighter-rouge">!=</code> operator</li>
</ul>
<p>As default the <code class="highlighter-rouge">==</code> and <code class="highlighter-rouge">!=</code> operators perform identity check. When we provide our equality implementation we should also overload equality and inequality operators to avoid confusion and bugs while working with our objects.</p>
<ul>
<li>Implement <code class="highlighter-rouge">System.IEquatable<T></code> interface</li>
</ul>
<p>This is an interface which defines a strongly typed <code class="highlighter-rouge">Equals</code> method, which can be used internally by other equality comparison methods. It is worth mentioning that using strongly typed <code class="highlighter-rouge">Equals</code> method avoids boxing while working with structs.</p>
<h4 id="test-do-list-for-testing-equality">Test-Do list for testing equality</h4>
<p>And last but not least, we must put logic for actually performing the equality comparison of our objects. Finally, this is our test-do list for testing equality implementation:</p>
<p> [ ] <code class="highlighter-rouge">Equals</code> and <code class="highlighter-rouge">GetHashCode</code> method are overridden<br />
[ ] Check if implementation is reflexive <br />
[ ] Check if implementation is symmetric<br />
[ ] Check if implementation is transitive<br />
[ ] Check if implementation is consistent<br />
[ ] Check if returns <code class="highlighter-rouge">false</code> when compared to <code class="highlighter-rouge">null</code><br />
[ ] Check whether implementation of equality works according to the comparison logic<br />
[ ] <code class="highlighter-rouge">GetHashCode</code> implementation produces correct results<br />
[ ] <code class="highlighter-rouge">GetHashCode</code> implementation is consistent<br />
[ ] <code class="highlighter-rouge">==</code> and <code class="highlighter-rouge">!=</code> operators are overloaded<br />
[ ] <code class="highlighter-rouge">==</code> and <code class="highlighter-rouge">!=</code> operators produce correct results<br />
[ ] <code class="highlighter-rouge">IEquatable<T></code> is implemented<br />
[ ] <code class="highlighter-rouge">IEquatable<T></code> produces correct results<br /></p>
<h4 id="write-once-run-use-everywhere">Write once, <del>run</del> use everywhere</h4>
<p>It is a lot of work, and our goal is to avoid repeating this every time we introduce value object. We know what to test for, to check equality implementation correctness. It would be the best if we can simply say <em>what</em> we want to test instead of <em>how</em> the equality tests should be done. That reminds me about the <strong>Write once, run everywhere</strong> slogan coined by <code class="highlighter-rouge">Sun</code> for <code class="highlighter-rouge">Java</code>. Actually, in our case we should say <strong>Write once, use everywhere</strong>. We can apply it here, write reusable component, which performs test cases and we can reuse it when we introduce new value objects to the system.</p>
<p>Fortunately, there is a library that can help us. It is <a href="https://github.com/AutoFixture/AutoFixture">AutoFixture</a> (maybe there are other libraries but I don’t know any), and its part <code class="highlighter-rouge">AutoFixture.Idioms</code>. If we use that library, out of the box we can cross four items from test-do list. For the remaining items we can plug into <code class="highlighter-rouge">AutoFixture.Idioms</code> infrastructure and write assertions that performs other test cases.</p>
<p>So, this is the test-do list we have after using <a href="https://github.com/AutoFixture/AutoFixture">AutoFixture</a>:</p>
<p> [ ] <code class="highlighter-rouge">Equals</code> and <code class="highlighter-rouge">GetHashCode</code> method are overridden<br />
<del>[x] Check if implementation is reflexive</del> <strong><a href="https://github.com/AutoFixture/AutoFixture/blob/master/Src/Idioms/EqualsSelfAssertion.cs">EqualsSelfAssertion</a> class from</strong> <code class="highlighter-rouge">AutoFixture.Idioms</code><br />
[ ] Check if implementation is symmetric<br />
[ ] Check if implementation is transitive<br />
<del>[x] Check if implementation is consistent</del> <strong><a href="https://github.com/AutoFixture/AutoFixture/blob/master/Src/Idioms/EqualsSuccessiveAssertion.cs">EqualsSuccessiveAssertion</a> class from</strong> <code class="highlighter-rouge">AutoFixture.Idioms</code><br />
<del>[x] Check if returns false when compare to null</del> <strong><a href="https://github.com/AutoFixture/AutoFixture/blob/master/Src/Idioms/EqualsNullAssertion.cs">EqualsNullAssertion</a> class from</strong> <code class="highlighter-rouge">AutoFixture.Idioms</code><br />
[ ] Check whether implementation of equality works according to the comparison logic <br />
[ ] <code class="highlighter-rouge">GetHashCode</code> implementation produces correct results<br />
<del>[x] <code class="highlighter-rouge">GetHashCode</code> implementation is consistent</del> <strong><a href="https://github.com/AutoFixture/AutoFixture/blob/master/Src/Idioms/GetHashCodeSuccessiveAssertion.cs">GetHashCodeSuccessiveAssertion</a> class from</strong> <code class="highlighter-rouge">AutoFixture.Idioms</code><br />
[ ] <code class="highlighter-rouge">==</code> and <code class="highlighter-rouge">!=</code> operators are overloaded <br />
[ ] <code class="highlighter-rouge">==</code> and <code class="highlighter-rouge">!=</code> operators produce correct results<br />
[ ] <code class="highlighter-rouge">IEquatable<T></code> is implemented<br />
[ ] <code class="highlighter-rouge">IEquatable<T></code> produces correct results<br /></p>
<p>For clarification, the assertions that will be presented are intended to use with immutable value objects. Data used in equality comparison is provided by arguments passed to constructor. Example of that value object is following:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">Point</span>
<span class="p">{</span>
<span class="k">public</span> <span class="nf">Point</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">,</span> <span class="kt">int</span> <span class="n">y</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">X</span> <span class="p">=</span> <span class="n">x</span><span class="p">;</span>
<span class="n">Y</span> <span class="p">=</span> <span class="n">y</span><span class="p">;</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">int</span> <span class="n">X</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">private</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="k">public</span> <span class="k">int</span> <span class="n">Y</span> <span class="p">{</span> <span class="k">get</span><span class="p">;</span> <span class="k">private</span> <span class="k">set</span><span class="p">;</span> <span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<h4 id="making-equalityoperatoroverloadassertion">Making EqualityOperatorOverloadAssertion</h4>
<p>Goal of the <code class="highlighter-rouge">EqualityOperatorOverloadAssertion</code> is to check whether given type overloads <code class="highlighter-rouge">==</code> operator. Assertion derives from <a href="https://github.com/AutoFixture/AutoFixture/blob/master/Src/Idioms/IIdiomaticAssertion.cs">IdiomaticAssertion</a> abstract class that is defined in <code class="highlighter-rouge">AutoFixture.Idioms</code>. <code class="highlighter-rouge">IdiomaticAssertion</code> provides helpful default implementation for methods from <a href="https://github.com/AutoFixture/AutoFixture/blob/master/Src/Idioms/IIdiomaticAssertion.cs">IIdiomaticAssertion</a> interface. In our example we are overriding <code class="highlighter-rouge">Verify</code> method with <code class="highlighter-rouge">Type</code> parameter as this is the information necessary to perform interesting us assertion. After it turns out that type does not overload <code class="highlighter-rouge">==</code> operator, we throw meaningful exception which explains what is wrong.
This is the code for <code class="highlighter-rouge">EqualityOperatorOverloadAssertion</code>:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">class</span> <span class="nc">EqualityOperatorOverloadAssertion</span> <span class="p">:</span> <span class="nc">IdiomaticAssertion</span>
<span class="p">{</span>
<span class="k">public</span> <span class="k">override</span> <span class="k">void</span> <span class="nf">Verify</span><span class="p">(</span><span class="n">Type</span> <span class="n">type</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">if</span> <span class="p">(</span><span class="n">type</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nc">ArgumentNullException</span><span class="p">(</span><span class="s">"type"</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">var</span> <span class="n">equalityOperatorOverload</span> <span class="p">=</span> <span class="n">type</span><span class="p">.</span><span class="n">GetEqualityOperatorMethod</span><span class="p">();</span>
<span class="k">if</span> <span class="p">(</span><span class="n">equalityOperatorOverload</span> <span class="p">==</span> <span class="k">null</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">throw</span> <span class="k">new</span> <span class="nc">EqualityOperatorException</span><span class="p">(</span>
<span class="k">string</span><span class="p">.</span><span class="n">Format</span><span class="p">(</span><span class="s">"Expected type {0} to overload == operator with parameters of type {0}"</span><span class="p">,</span> <span class="n">type</span><span class="p">.</span><span class="n">Name</span><span class="p">));</span>
<span class="p">}</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<p>Usage of <code class="highlighter-rouge">EqualityOperatorOverloadAssertion</code>:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="nc">[Fact]</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">ShouldOverloadEqualityOperator</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">new</span> <span class="nc">EqualityOperatorOverload</span><span class="p">().</span><span class="n">Verify</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="nc">SomeValueObject</span><span class="p">));</span>
<span class="p">}</span>
</code></pre></div>
<p>I think that it doesn’t make sense to put here implementation of every assertion. Therefore, I decided to pick one simple assertion and explain how it is done. If you are interested how other assertions are implemented, please take a look <a href="https://github.com/baks/EqualityTests/tree/master/EqualityTests/Assertions">here</a>.</p>
<h4 id="compose-all-the-assertions">Compose all the assertions</h4>
<p>To write a reusable component that will execute test cases from our test-do list we need to compose all created assertions. We can use <code class="highlighter-rouge">CompositeIdiomaticAssertion</code> class from <code class="highlighter-rouge">AutoFixture.Idioms</code> that allows to supply suite of assertions that will be verified.</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="k">public</span> <span class="k">static</span> <span class="k">class</span> <span class="nc">EqualityTestsFor</span><span class="p"><</span><span class="n">T</span><span class="p">></span> <span class="k">where</span> <span class="n">T</span> <span class="p">:</span> <span class="k">class</span>
<span class="p">{</span>
<span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">Assert</span><span class="p">()</span>
<span class="p">{</span>
<span class="k">var</span> <span class="n">fixture</span> <span class="p">=</span> <span class="k">new</span> <span class="nc">Fixture</span><span class="p">();</span>
<span class="k">var</span> <span class="n">compositeAssertion</span> <span class="p">=</span>
<span class="k">new</span> <span class="nc">CompositeIdiomaticAssertion</span><span class="p">(</span><span class="n">EqualityAssertions</span><span class="p">(</span><span class="n">fixture</span><span class="p">,</span> <span class="k">new</span> <span class="nc">EqualityTestCaseProvider</span><span class="p">(</span><span class="n">fixture</span><span class="p">)));</span>
<span class="n">VerifyCompositeAssertion</span><span class="p">(</span><span class="n">compositeAssertion</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">public</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">Assert</span><span class="p">(</span><span class="n">Func</span><span class="p"><</span><span class="nc">EqualityTestsConfiguration</span><span class="p"><</span><span class="n">T</span><span class="p">>></span> <span class="n">configuration</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">var</span> <span class="n">compositeAssertion</span> <span class="p">=</span>
<span class="k">new</span> <span class="nc">CompositeIdiomaticAssertion</span><span class="p">(</span><span class="n">EqualityAssertions</span><span class="p">(</span><span class="k">new</span> <span class="nc">Fixture</span><span class="p">(),</span> <span class="n">configuration</span><span class="p">()));</span>
<span class="n">VerifyCompositeAssertion</span><span class="p">(</span><span class="n">compositeAssertion</span><span class="p">);</span>
<span class="p">}</span>
<span class="k">private</span> <span class="k">static</span> <span class="k">void</span> <span class="nf">VerifyCompositeAssertion</span><span class="p">(</span><span class="n">CompositeIdiomaticAssertion</span> <span class="n">compositeAssertion</span><span class="p">)</span>
<span class="p">{</span>
<span class="n">compositeAssertion</span><span class="p">.</span><span class="n">Verify</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="n">T</span><span class="p">));</span>
<span class="n">compositeAssertion</span><span class="p">.</span><span class="n">Verify</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="n">T</span><span class="p">).</span><span class="n">GetEqualsMethod</span><span class="p">());</span>
<span class="n">compositeAssertion</span><span class="p">.</span><span class="n">Verify</span><span class="p">(</span><span class="k">typeof</span><span class="p">(</span><span class="n">T</span><span class="p">).</span><span class="n">GetMethod</span><span class="p">(</span><span class="s">"GetHashCode"</span><span class="p">));</span>
<span class="p">}</span>
<span class="k">private</span> <span class="k">static</span> <span class="nc">IEnumerable</span><span class="p"><</span><span class="nc">IdiomaticAssertion</span><span class="p">></span> <span class="n">EqualityAssertions</span><span class="p">(</span><span class="nc">ISpecimenBuilder</span> <span class="n">specimenBuilder</span><span class="p">,</span>
<span class="nc">IEqualityTestCaseProvider</span> <span class="n">equalityTestCaseProvider</span><span class="p">)</span>
<span class="p">{</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">EqualsOverrideAssertion</span><span class="p">();</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">GetHashCodeOverrideAssertion</span><span class="p">();</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">EqualsSelfAssertion</span><span class="p">(</span><span class="n">specimenBuilder</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">EqualsSymmetricAssertion</span><span class="p">(</span><span class="n">specimenBuilder</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">EqualsTransitiveAssertion</span><span class="p">(</span><span class="n">specimenBuilder</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">EqualsSuccessiveAssertion</span><span class="p">(</span><span class="n">specimenBuilder</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">EqualsNullAssertion</span><span class="p">(</span><span class="n">specimenBuilder</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">EqualsValueCheckAssertion</span><span class="p">(</span><span class="n">equalityTestCaseProvider</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">GetHashCodeValueCheckAssertion</span><span class="p">(</span><span class="n">equalityTestCaseProvider</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">GetHashCodeSuccessiveAssertion</span><span class="p">(</span><span class="n">specimenBuilder</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">EqualityOperatorOverloadAssertion</span><span class="p">();</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">InequalityOperatorOverloadAssertion</span><span class="p">();</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">EqualityOperatorValueCheckAssertion</span><span class="p">(</span><span class="n">equalityTestCaseProvider</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">InequalityOperatorValueCheckAssertion</span><span class="p">(</span><span class="n">equalityTestCaseProvider</span><span class="p">);</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">IEquatableImplementedAssertion</span><span class="p">();</span>
<span class="k">yield</span> <span class="k">return</span> <span class="k">new</span> <span class="nc">IEquatableValueCheckAssertion</span><span class="p">(</span><span class="n">equalityTestCaseProvider</span><span class="p">);</span>
<span class="p">}</span>
<span class="p">}</span>
</code></pre></div>
<p>If our value object is using only primitive types in constructor, we can rely on default equality test case provider that can handle this situation. It means, that we can write simple unit test for equality like:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="nc">[Fact]</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">ShouldImplementValueEquality</span><span class="p">()</span>
<span class="p">{</span>
<span class="nc">EqualityTestsFor</span><span class="p"><</span><span class="nc">Point</span><span class="p">>.</span><span class="n">Assert</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div>
<p>But, if we need some more advanced scenarios, we can provide our own instances to describe what the results of equality test cases should be:</p>
<div class="highlight"><pre><code class="language-csharp" data-lang="csharp"><span class="nc">[Fact]</span>
<span class="k">public</span> <span class="k">void</span> <span class="nf">ShouldImplementValueEquality</span><span class="p">()</span>
<span class="p">{</span>
<span class="nc">EqualityTestsFor</span><span class="p"><</span><span class="nc">Point</span><span class="p">>.</span><span class="n">Assert</span><span class="p">(</span>
<span class="p">()</span> <span class="p">=></span>
<span class="nc">EqualityTestsConfigurer</span><span class="p"><</span><span class="nc">Point</span><span class="p">></span>
<span class="p">.</span><span class="n">Instance</span><span class="p">(</span><span class="k">new</span> <span class="nc">Point</span><span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="m">1</span><span class="p">))</span>
<span class="p">.</span><span class="n">ShouldBeEqualTo</span><span class="p">(</span><span class="k">new</span> <span class="nc">Point</span><span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="m">1</span><span class="p">))</span>
<span class="p">.</span><span class="n">ShouldNotBeEqualTo</span><span class="p">(</span><span class="k">new</span> <span class="nc">Point</span><span class="p">(</span><span class="m">1</span><span class="p">,</span> <span class="m">2</span><span class="p">))</span>
<span class="p">.</span><span class="n">ShouldNotBeEqualTo</span><span class="p">(</span><span class="k">new</span> <span class="nc">Point</span><span class="p">(</span><span class="m">2</span><span class="p">,</span> <span class="m">1</span><span class="p">)));</span>
<span class="p">}</span>
</code></pre></div>
<h4 id="wrap-up">Wrap up</h4>
<p>Checking equality implementation in value objects can be repetitive work, hence in this post you can find reusable approach to this problem. <a href="https://github.com/AutoFixture/AutoFixture">AutoFixture</a> was used as a supporting library. It is heavily using <a href="http://martinfowler.com/bliki/RoleInterface.html">role interfaces</a>. Therefore it is very composable and it is a pleasure to work with design like that.</p>
<p>I’d like to add, if we spot in our solution that we are testing something more than once, it is a sign that maybe there is domain concept which should be made explicit. This is a somewhat term <strong>Test once, use everywhere</strong>. I find it useful, because it avoids duplication of the behavior in the system. We put behavior in one component, test it and we can use it everywhere. It also prevents us for combinatorial explosion of test cases when we have to test the same thing many times.</p>
A few thoughts about Agile2015-10-13T00:00:00+00:00https://baks.github.io/2015/10/13/a-few-thoughts-about-agile
<p>These days, Agile lightweight methodologies seem to be used as major software development methods across the world. Even not software development companies are using Agile processes. Scrum is one of the most common implementations of an Agile process. Recently, I’m thinking a lot about agile methodologies and it understanding after fourteen years when the <a href="http://www.agilemanifesto.org/">Agile Manifesto</a> came out and I want to share my thoughts.
Before you read further, think about what is Agile for you?</p>
<p><strong>Quick recall</strong></p>
<p>The other software development process which is often contrasted to Agile methodologies is <a href="https://en.wikipedia.org/wiki/Waterfall_model">waterfall method</a>.
In waterfall process there were phases executed step by step. Input to the next stage was output from the previous. The assumption was, if we spend adequate amount of time on given phase and do it well, there will be no need for changes latter. For example, in design phase there was <a href="https://en.wikipedia.org/wiki/Big_Design_Up_Front">Big Design Up Front</a>, and the argument was if we first design architecture of our system, therefore we don’t have to change anything in implementation phase. Unfortunately, that’s not true, because we can’t foreseen everything and in waterfall we can’t go back and change our design (at least easily). There wasn’t feedback of our design until the implementation phase was finished. That was the problem with waterfall process - lack of early feedback and difficulty in introducing changes. And that is what Agile changed - possibility of getting early feedback and responding to change even in lately development. The phases from waterfall are repeated in small time boxes and that defines iterative and incremental development. Because phases are repeated, therefore we have iterative development. New value to the software product is added feature by feature, therefore we have incremental development.
Apart from that, you can see, that’s no surprise that other methods which gives us early feedback at different levels of creating software product are widely used. That’s why we use <a href="https://en.wikipedia.org/wiki/Test-driven_development">test-driven development</a>, pair programming, code reviews and so on.</p>
<p><strong>What you hear when you ask about Agile?</strong></p>
<p>Probably when you ask somebody about Agile you will hear about sprint planning, board, cards, sprint retrospective and other artifacts and ceremonies connected with Scrum (because is the most common implementation of Agile).
But they are implementation details. And like when we write code if we focus our system too much on implementation details it makes the system tightly coupled. The same I think focusing too much on implementation details prevent us for understanding what agile is aim for.</p>
<p>Introducing an Agile process into company means that you want to collect feedback early and therefore you welcome changes. But what if at the down level the change is hard to implement? You are agile because you write tasks on cards, estimate it and stick to the board or have daily standups? I’ve seen teams that doesn’t use neither Scrum nor any of the known agile frameworks but their code really embrace change. So, you would say they aren’t agile?</p>
<p>I think in the jungle of Scrum ceremonies and artifacts (or maybe not properly understanding what Agile aims for) we forgot about other <a href="http://www.agilemanifesto.org/principles.html">principles that are behind Agile Manifesto</a>. How many times did you see a piece of code that wasn’t good enough and you did nothing about that? The phrase <em>I don’t have time</em> is a poor explanation for professional software developer. We should be responsible for the code that we work on. If we make our code adaptive to change, but have problems with our software management process it’s still better than otherwise.</p>
<p><strong>Leave the code better than you found it. (The Boy Scout Rule)</strong></p>
<p>Yes, that’s important part of being agile. Carrying over the quality of the software product. And if you wonder how you would know that your change would not mess in other parts of the system. The answer is that you didn’t understand Agile idea well, you didn’t build your feedback foundation at the code level - you fooled yourself that the artifacts and events is all what you need to claim that you are agile.</p>
<p><strong>Thank you Scrum inventors!</strong></p>
<p>I’m not saying the Scrum or other Agile method is unnecessary. It is very helpful and we only could be thankful to inventors of the Scrum framework. But we must also understand that the codebase and it’s quality is a huge part of that how the software product is agile (even more bigger part than the process itself). You may listen to as many podcasts about Agile as you want, go to conferences and hear about best Agile practices but that is a waste of time until you build your feedback foundation and make your codebase adaptive to change.</p>
<p><strong>Summary</strong></p>
<p>To wrap up the Agile is more about feedback and embracing changing requirements than particular artifacts and ceremonies.
If you find something interesting in this post, let everybody know, otherwise forget about it.</p>