<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[OrthoCoders]]></title>
  <link href="http://orthocoders.com/atom.xml" rel="self"/>
  <link href="http://orthocoders.com/"/>
  <updated>2013-05-06T14:54:04-05:00</updated>
  <id>http://orthocoders.com/</id>
  <author>
    <name><![CDATA[Amir Barylko]]></name>
    
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <entry>
    <title type="html"><![CDATA[The feature toggle conspiracy]]></title>
    <link href="http://orthocoders.com/blog/2013/02/03/the-attack-of-the-killer-feature-branch/"/>
    <updated>2013-02-03T13:24:00-06:00</updated>
    <id>http://orthocoders.com/blog/2013/02/03/the-attack-of-the-killer-feature-branch</id>
    <content type="html"><![CDATA[<h2>Source Control Workflow</h2>

<p>At the heart of many software projects (if not all), no matter which language you use (framework, IDE, etc) you have source code.</p>

<p>There is lots of tools out there (git, mercurial, SVN, CVS, TFS, etc) that help us to version the code and keep it safe so valuable changes are never lost.</p>

<p>However when working with a team choosing a tool is not enough and a <em>workflow</em> has to be agreed to ensure that the same practices are applied by all the members of the team, changes are merged properly, tests run, etc.</p>

<!-- more -->


<p>Why? If you work with a central repository as soon as you copy the repository code to your local computer it may become out of date, thus you may need to bring someone else&#8217;s changes to have the latest version, and ensure that your changes will work when you actually push (submit) them to production.</p>

<p>How to do so? Well, you have to decide as a team on a series of steps (workflow) to follow in your day to day coding to agree how the changes are merged, resolving conflicts, etc. Usually branching is part of the recipe.</p>

<h2>Branching will save your bacon</h2>

<p>Branching is what we do naturally to write changes, new features, spiking solutions, etc.</p>

<p>It&#8217;s as easy as copying the source to your local hard drive, that&#8217;s a branch right there.</p>

<p>The better your tool is at branching, the easiest it is to make them, switch between branchs, compare branches, etc.</p>

<p>Why this is a good idea? To handle (with little pain as possible) scenarios like these:</p>

<ul>
<li>Feature XXX has to be added but while coding it a super urgent bug that has to be fix appears.</li>
<li>Five new features are being reviewed in user acceptance test, only two get accepted to go to production.</li>
<li>We need to modify production code for a client that has special requests, and keep maintaining both the modification and the main code.</li>
</ul>


<p>And that&#8217;s cool, however we still have one enemy to defeat: <em>merging</em>.</p>

<h3>The dreaded merge</h3>

<p>Branches are a huge benefit once we have a <em>merging</em> workflow that is as painless as possible and avoids overwriting other&#8217;s developers code (who cares? It&#8217;s c!$&amp;*<sup>p</sup> anyways! Just kidding, just kidding&#8230;.) or features.</p>

<p>What should we do? Let&#8217;s review some options:</p>

<h4>One branch shared for the length of the iteration (may be weeks)</h4>

<p>The race is on! Whoever finishes last has to deal with all the changes and do the merge, or just wait until the sprint/iteration it&#8217;s over and then someone has to merge all the code changes (I hope it&#8217;s not you). <strong>The result</strong>: we gain nothing.</p>

<h4>Have a centralized merge <em>guru</em></h4>

<p>When is time to deploy this <em>guru</em> will take what he needs from each branch and solve conflicts, etc.
This process is long, tedius and buggy. How does this <em>guru</em> know what your code supposed to do? Who better than the dev who wrote it? <strong>The result</strong>: we gain nothing.</p>

<h4>A combination of both?</h4>

<p>Yeah, like that would work!</p>

<p>To control the fear and minimize screw ups you can use a policy like the following:</p>

<ul>
<li>Use tests to ensure no feature gets broken.</li>
<li>Branch to start a new feature or fix.</li>
<li>Bring changes and merge them often (once a day? twice? as often as you need!).</li>
<li>Keep the branches lifespan short if possible, no more than one or two days (or even shorter!).</li>
<li>When you are done and quite positive your branch is up to date and no test are broken, merge back.</li>
</ul>


<p>Bringing changes often will produce small &#8220;local merges&#8221; easy to handle instead of waiting to finish the feature and then try to merge with a collection of changes that may break your code and perhaps force you to rewrite a big chunk of your feature.</p>

<p>Every developer is responsible to bring changes and do merge before &#8220;pushing&#8221; any code to the repository making sure that all the tests are green before and after!</p>

<p>The longer you wait to merge, the hardest is going to be.</p>

<h2>What about <em>Feature Toggles</em> ?</h2>

<p>Some time ago at a conference I heard about <em>Feature Toggles</em> as an alternative solution to &#8220;I have too many merging issues and branching is a pain in the neck&#8221;.</p>

<p>Curious I asked what is that, and what I understood is the following:</p>

<pre><code>Instead of worrying about code that doesn't work, you toggle the feature "off" and keep 
adding code (that may not work properly) until the feature is ready and then you release 
it and turn it "on" for the user.
</code></pre>

<p>That&#8217;s cool I thought, but what does it have to do with source control workflow, branching and merging?</p>

<p>How does it help? Don&#8217;t you have the same issues? Wouldn&#8217;t developers still have to merge the code of others developers? What about database changes?</p>

<p>You mean the code is there but not working? Why would I like to put code that doesn&#8217;t work into the app?</p>

<p>Do you have to turn it <em>on</em> in order to test it? No? You don&#8217;t test it? So how do you know is compatible with your current app? What? Am I rambling like an old crazy architect? Get off my lawn!</p>

<p>Having features that can be turned <em>off</em> is part of the application design and architecture. A choice that should be made because adds value to the final product. It&#8217;s not a solution nor an alternative for poor source control tools or weak workflows.</p>

<p>I can&#8217;t just start a new project, no code written, and as part of discussing source control workflow say &#8220;I know, let&#8217;s use Feature Toggles!&#8221;. You have to write code for that to happen, you have to setup the basic architecture, storage, etc. So in the meantime, until that&#8217;s ready, what do you do with the code and the merge conflicts?</p>

<p>Perhaps you know of a case where <em>feature toggles</em> is a good fit due to the environment requirements, limitations of the tools, particularities of the team, etc. And I agree, maybe in that case it is a good solution.</p>

<p>However is not a <strong>general</strong> source control tool nor a <strong>general</strong> merging and branching solution.</p>

<p>Especial case, especial solution, no more, no less.</p>

<h2>The best tool for the job</h2>

<p>It&#8217;s been a few years since I started to use <em>git</em> and I really like it. A lot. You can read <a href="http://git-scm.com/about">online</a> the benefits, features, etc.</p>

<p>When I hear about source control woes, sometimes I suggest to try <em>git</em> out, to alleviate branching and merging pains.</p>

<p>However, I have noticed some reluctance to adopt it because <em>git</em> is harder to learn, or more complex to use compared to the source control tool the team is currently using.</p>

<p>And I agree! It may seem harder than others but like any other tool, it takes a bit of time to get used to it. And the benefits are huge! After all, what do we do with best practices, design patterns, etc? Just put them aside because they are hard to learn or implement? Why source control tools should be different?</p>

<p>I worked with teams that some of the devs had a hard time at first using <em>git</em>, understanding branching, merging, rebasing, etc&#8230; what did I do? Work with them and help them out&#8230; work on a personal repository first, do the workflow together several times until they are comfortable to do it on their own.</p>

<p>Another reason is that <em>git</em> it can be used as a distributed repository, not only because you can work locally completly disconnected from others, but you can decide from which repository you are going to deploy, meaning that is that one that has the latest version.</p>

<p>Does that mean that you have to do the same? Not at all! Nothing to worry about!. You can still have a central repository and even use only one repo with one branch, your choice.</p>

<p>The <em>git</em> police won&#8217;t show up at you cubicle and ask you to surrender your dev badge and your GOF design patterns book!</p>

<p>What puzzles me most is this: If the team is <strong>smart</strong> enough to write high quality code how come they aren&#8217;t <strong>bright</strong> enough to learn <em>git</em>?</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Modern Hiring]]></title>
    <link href="http://orthocoders.com/blog/2012/07/27/stop-hiring-juniors/"/>
    <updated>2012-07-27T14:13:00-05:00</updated>
    <id>http://orthocoders.com/blog/2012/07/27/stop-hiring-juniors</id>
    <content type="html"><![CDATA[<p>Lately I been hearing many companies complain about how hard is to find developers.</p>

<p>I do agree, finding good people is extremely complicated.</p>

<p>But not only because perhaps there&#8217;s a shortage in the city. Also hiring processes are out of date, driven by the wrong people and produce poor results.</p>

<p>I have done my share of interviews trying to find the right candidate for a position. Let me share a bit of what I learned&#8230;</p>

<!-- more -->


<h2>The resume</h2>

<p>Having a HR (non technical) person dedicated to match resumes against a list of required skills is a waste of time.</p>

<p>Why? Because more often than not, the candidate will list subjects just to match what are you looking for, or read an article about, played a bit with, found in a fortune cookie, etc&#8230;.</p>

<p>I tend to ask candidates to be honest with me and tell me in which &#8220;skills&#8221; of the list are truly <em>proficient</em>. Just to make sure I ask the right questions.</p>

<p>Out of 20 skills they may choose two or three.</p>

<p>Using resumes as a main option to try to find good potential aspirants does not work as expected, we need to change that.</p>

<h2>Years of experience</h2>

<p>I don&#8217;t care how many years a developer has been sitting on a chair, participating on one or more projects.</p>

<p>Experience measured in year does not mean a thing. Experience in general is questionable.</p>

<p>Why? Because smart developers will catch up with others that claim to have 10 years of experience in a matter of months.</p>

<p>Find someone bright that has a really good basis in computer science, I&#8217;m sure he will be able to catch up and go beyond your expectations.</p>

<p>Some of the key factors are <em>potential</em> and <em>seniority</em>.</p>

<h2>How to measure <em>seniority</em></h2>

<p>What is the difference between a <em>Sr.</em>, <em>Intermediate</em> and <em>Jr.</em> developer? We just ruled out <em>years of experience</em> so think of something else&#8230; how would you identify them?</p>

<p>I usually ask the candidates to identify themselves, and of course explain why. It&#8217;s a great exercise.</p>

<p>I think that <em>seniority</em> in software comes with the kind of responsibility that a person can accept and produce high quality results without full time coaching.</p>

<p><strong>High Quality</strong> results, not any kind of results. Last week someone asked me about what happens when a so called &#8220;Sr.&#8221; produces poor results, well, that falls into the &#8220;need more coaching&#8221; category.</p>

<p>There&#8217;s nothing wrong with <em>coaching</em>. Is just that most companies don&#8217;t consider that part of the job. If it happens at all is usually by accident.</p>

<p>That&#8217;s another excellent question for an interview: How do you ensure quality?</p>

<p>s## The recipe</p>

<p>First of all find someone (an expert, coach, someone you respect and can make accountable) to help you out and stay with you during the hiring process.</p>

<p>In order to invest wisely, don&#8217;t try to optimize the equation. If you don&#8217;t have budget to hire a Sr. please, don&#8217;t try to see what you can get for less&#8230; it&#8217;s not a grocery store!</p>

<p>If you want to hire Jr. developers make sure you have someone to coach them and teach them the right lessons otherwise is a waste of money.</p>

<p>Seek potential, not a perfect match.</p>

<p>In order to produce great interviews, make sure you have <em>technical</em> people filtering candidates and helping with the process.</p>

<p>Avoid endless meetings, that does not help to show how <em>cool</em> you are.</p>

<p>Use <em>twitter</em> and similar media to reach your target.</p>

<p>Follow up with your interviewee. No matter what&#8217;s your response don&#8217;t make them wait or forget about them.</p>

<p>Show ahead what kind of questions you may have. Send practice questionnaires if you want to. What? What happens if they learn/google all the answers? Awesome! You should hire him on the spot!</p>

<p>Sponsor IT events and user groups. Reach out (respectfully) to the community to find candidates. Even generate events like <em>code competitions</em> or <em>code retreats</em>.</p>

<p>Money is important (very important) however there are other factors that will attract other developers to work for you. How cool your projects are, who works for your company, real training plans, etc.</p>

<p>Encourage your employees to write OSS tools, frameworks, etc. Best personal card ever!</p>

<p>Trust proven concrete projects over theoretical experience. There&#8217;s lots of ways of sharing code today and the right candidate should have some examples of projects that can be shared in order to demonstrate his abilities.</p>

<p>What? No projects to show off? Easy fix, give him a month to build something :)</p>

<h2>The perfect match</h2>

<p>Sometimes is quite complicated to find the person that you are looking for due to the particular set of skills that you need at that moment.</p>

<p>Instead of starting a lengthy (and costly) search consider to build the position your need. That&#8217;s why you have your trustworthy coach to help you out and help you plan the process.</p>

<p>The right team will make things happen. Make sure you are adding <em>value</em> with each new member.</p>

<p>The most important <em>asset</em> that you have is your team. Let them shine.</p>

<p>Care for your team and help them grow, that alone will put the word out there and bring the best to your doorstep.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Kanban Limits]]></title>
    <link href="http://orthocoders.com/blog/2012/07/26/kanban-limits/"/>
    <updated>2012-07-26T21:25:00-05:00</updated>
    <id>http://orthocoders.com/blog/2012/07/26/kanban-limits</id>
    <content type="html"><![CDATA[<h2>Model your process</h2>

<p>Probably by now if you work in the software industry you heard about the word <em>kanban</em> or already are using a <em>Kanban</em> board with your team.</p>

<p>A <em>Kanban</em> board (usually implemented using a whiteboard, wall with stickies, or electronic version) lets you model the series of steps that as a team you have to take in order to produce working software.</p>

<p>Some of the benefits are that you gain visibility, communication and transparency in one simple step. And if you use it right you will be able to show bottlenecks and cope with them or at least elevate the issue to someone that has the power to solve it.</p>

<p>Most important is that you can focus on working based on your team capacity (<strong>Pull</strong>) vs. working by demand (<strong>Push</strong>).</p>

<p>However today I don&#8217;t want to do a 101 post on <em>Kanban</em>. There are plenty of posts for that, you can find them <a href="http://www.kanban101.com/">here</a>, <a href="http://agilemanagement.net/">here</a> and <a href="http://agileconsulting.blogspot.ca/2012/02/kanban-101.html">here</a>.</p>

<p>Today I want to talk about what is the result when, once you read that intro, decide to implement <em>Kanban</em> with your team. What happens next?</p>

<!--more-->


<p></p>

<h2>The quality conundrum</h2>

<p>I have to admit it, having a wall full of stickies looks pretty cool. Looks like you are really busy. If you have a <em>mess</em> at work every day, probably the <em>board</em> will look exactly like that.</p>

<p>Having the board quite full, though it represents accurately what&#8217;s going on, may raise some questions after a while:</p>

<ul>
<li>Why are we doing this? What&#8217;s the benefit?</li>
<li>Isn&#8217;t this the same as the excel spreadsheet but horizontal?</li>
<li>Why can&#8217;t I just put the sticky notes wherever I want?</li>
<li>Can we skip it just for now? Until after the deadline?</li>
<li>Where&#8217;s my Gantt chart?</li>
</ul>


<p>These questions are quite valid. Like any other process, you need buy-in from the team, but also you need to show some kind of improvement.</p>

<p>For some teams, just showing the status on a board is quite a benefit and management sees value right away because they can look at pending work, what&#8217;s going on, etc, with less meetings and less checks on the team.</p>

<p>That is an excellent first step, and for some teams it is ok to stay there. However lets not forget though that the team is still working based on <em>demand</em>, if more features are needed for the release they will go into the queue no matter what.</p>

<p>Finding the team <em>capacity</em> and being able to do more accurate estimations is the next step.</p>

<h2>Continuos improvement culture</h2>

<p>In his <a href="http://agilemanagement.net/index.php/kanbanbook/">book</a>, David J. Anderson talks about <em>Kaizen</em>. The culture of <em>continuos improvement</em>.</p>

<p>But in order to improve we need to know first our reality and identify what is the <em>capacity</em> of the team. Remember, no matter what we think of ourselves, reality always wins.</p>

<p>To do that we need to find the <em>Work In Progress</em> limit for each phase so we can <em>pace</em> the amount of features that enter to the <em>backlog</em>. Otherwise the <em>input queue</em> is the same <em>excel spreadsheet</em> that we had before.</p>

<p>Missing on using the limits or postponing choosing limits may lead to a failure in implementing the board in some cases, and I urge you not to let it be so.</p>

<p>The concept of <em>Lead Time</em> is key. That&#8217;s the time that takes for a feature since was added to the queue to be finished, but really finished, not just compiled (if compiles it works, right?), not 90% tested, done done. Think about it like being a <em>bit</em> pregnant, how many answers you have for that?</p>

<p>That is the measure that we need to improve (to go faster), and that&#8217;s how are we going to tell if the board is working for us or not. Once that metric is calculated and shared, it is easier to discuss about speed, analyze bottlenecks and other problems, and find solutions for them.</p>

<p>Choosing WIP limits is important and it should not be delayed. Start by proposing some numbers, don&#8217;t worry about 100% accuracy. So far no unicorns have been sacrificed in the name of the &#8220;Gantt chart&#8221; god because a team got his WIP limits wrong the first time.</p>

<p>How do you know if it works? Well, check your <em>lead time</em>. Is it improving? Are you happy with it? Is management happy with it?</p>

<p>Tips that help:</p>

<ul>
<li><p>Work as a team: The team has to help to push features faster. When someone has an issue, then the whole team is responsible for it and they need to work together to fix it no matter if they are analysts, BAs, testers, devs, etc.</p></li>
<li><p>Never move a card/story back: That breaks the limits and doesn&#8217;t help. Remember that we are not trying to identify in which phase a card is, but to move faster. If a card needs more work it should stay in the phase that needs more work. And if that happens often, well, time to talk about it.</p></li>
<li><p>Similar sized features: Try to consume a feature every two or three days if possible, that would give you and idea when a feature is too large and has to be split.</p></li>
<li><p>Don&#8217;t waste time estimating: Identifying complexity is fine, but to use that information to calculate days or hours of work is a waste. Use the board to have an idea of how many features you can complete, that&#8217;s your reality.</p></li>
<li><p>Avoid tasks lists to estimate completion: Task lists do not show progress. One day you have 10 tasks, the next day you discover 5 more, the day after that you realize that with 5 tasks is enough, get the gist?</p></li>
<li><p>Watch the board: Don&#8217;t let cards stay for too long on a phase, raise concerns because something not working as expected.</p></li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[I wrote the test, now what?]]></title>
    <link href="http://orthocoders.com/blog/2012/07/24/class-invariants/"/>
    <updated>2012-07-24T22:06:00-05:00</updated>
    <id>http://orthocoders.com/blog/2012/07/24/class-invariants</id>
    <content type="html"><![CDATA[<h2>Working with state</h2>

<p>In the <a href="http://orthocoders.com/blog/2012/07/23/testing-the-test/">previous post</a> I showed some examples of writing specifications using immutable classes. For an introduction to specifications please refer to my post about <a href="http://orthocoders.com/blog/2012/07/22/why-testing-is-so-hard/">testing</a>.</p>

<p>There&#8217;s no denying that immutability can provide lots of benefits in terms of testing, reducing complexity and lowering coupling. Having a language/paradigm that embraces it could be a huge productivity booster.</p>

<p>Unfortunately that&#8217;s not always the case or our choice to make ;).</p>

<!-- more -->


<p>For methods that are <em>immutable</em> specifying the <em>Pre</em> and <em>Post</em> condition is usually enough. However, is quite common in <em>OOP</em> to call methods that not only use the state of the instance but also modify it.</p>

<p>Using <em>interfaces</em> in order to talk about <em>Pre</em> and <em>Post</em> was sufficient because we were describing only the behavior of the method, not implementation. In contrast exploring the state of an instance of a class implies looking at the implementation.</p>

<h2>The class invariant</h2>

<p>Lets imagine that we want to implement a sorted <em>Collection</em> that ensures every time I iterate through the collection all the elements will be return by the default order. This time the method will <strong>modify</strong> the state.</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">/// Using default Comparer&lt;T&gt;</span>
</span><span class='line'><span class="k">public</span> <span class="k">class</span> <span class="nc">SortedCollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">:</span> <span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>    <span class="k">public</span> <span class="k">void</span> <span class="nf">Add</span><span class="p">(</span><span class="n">T</span> <span class="n">e</span><span class="p">)</span> <span class="p">{</span> <span class="p">...</span> <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">public</span> <span class="n">IEnumerator</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">GetEnumerator</span><span class="p">()</span> <span class="p">{</span> <span class="p">....</span> <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Lets focus on the <em>Add</em> method. The test looks like:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="na">[Test]</span>
</span><span class='line'><span class="k">public</span> <span class="k">void</span> <span class="nf">It_should_add_the_value_to_the_collection_in_order</span><span class="p">([</span><span class="n">RandomValue</span><span class="p">]</span><span class="n">T</span> <span class="n">e</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="c1">// arrange</span>
</span><span class='line'>  <span class="n">var</span> <span class="n">c</span> <span class="p">=</span> <span class="n">GenerateRandomCollectionOf</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;();</span>
</span><span class='line'>
</span><span class='line'>  <span class="n">var</span> <span class="n">expected</span> <span class="p">=</span> <span class="n">c</span><span class="p">.</span><span class="n">ToArray</span><span class="p">().</span><span class="n">Concat</span><span class="p">(</span><span class="n">e</span><span class="p">).</span><span class="n">Sort</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// act</span>
</span><span class='line'>  <span class="n">c</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// assert</span>
</span><span class='line'>  <span class="n">Assert</span><span class="p">.</span><span class="n">That</span><span class="p">(</span><span class="n">c</span><span class="p">.</span><span class="n">ToArray</span><span class="p">(),</span> <span class="n">Is</span><span class="p">.</span><span class="n">EquivalentTo</span><span class="p">(</span><span class="n">expected</span><span class="p">));</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The failing test is the first part of following <em>TDD</em> and we used the <em>Pre</em> and <em>Post</em> to help us to write it without leaving any scenario out.</p>

<p>Now, in order to write the implementation of the method, lets think about how are we going to keep the elements sorted.</p>

<p>We could use an array to store the values and keep it sorted. How can we specify this?</p>

<p>Similar to having a <em>predicate</em> to describe what happens before and after calling a method we are going to use another <em>predicate</em> to describe a condition that a class has to satisfy for every instance.</p>

<p>This <em>condition</em> is called <em>class invariant</em> (invariant in the sense that does not change) and will enforce a restriction over the implementation of a class.</p>

<p>Considering the case above I want to enforce that my array is always sorted.</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">/// Invariant: { _sortedElements is always sorted }</span>
</span><span class='line'><span class="k">public</span> <span class="k">class</span> <span class="nc">SortedCollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">:</span> <span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="k">private</span> <span class="n">T</span> <span class="p">[]</span><span class="n">_sortedElements</span><span class="p">;</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>The <em>class invariant</em> has to be satisfied (evaluated to true) before and after each method is called. It is ok if the <em>predicate</em> is <em>false</em> inside the method but we need to work to restore it.</p>

<p>When implementing the <em>Add</em> method we have no choice but to add it to the array and sort it:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">/// Invariant: { _sortedElements is always sorted }</span>
</span><span class='line'><span class="k">public</span> <span class="k">class</span> <span class="nc">SortedCollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">:</span> <span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="k">public</span> <span class="k">void</span> <span class="nf">Add</span><span class="p">(</span><span class="n">T</span> <span class="n">e</span><span class="p">)</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="c1">// The invariant is valid here</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="n">_sortedElements</span> <span class="p">=</span> <span class="n">_sortedElements</span><span class="p">.</span><span class="n">Append</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
</span><span class='line'>    <span class="c1">// The invariant may not be valid here it depends on the value</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="n">_sortedElements</span> <span class="p">=</span> <span class="n">_sortedElements</span><span class="p">.</span><span class="n">Sort</span><span class="p">();</span>
</span><span class='line'>    <span class="c1">// The invariant has to be valid here (and it is)</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Is that the only implementation possible? Why not sort the elements when I need an enumerator? Something like:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
<span class='line-number'>16</span>
<span class='line-number'>17</span>
<span class='line-number'>18</span>
<span class='line-number'>19</span>
<span class='line-number'>20</span>
<span class='line-number'>21</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">/// Invariant: { _sortedElements is always sorted }</span>
</span><span class='line'><span class="k">public</span> <span class="k">class</span> <span class="nc">SortedCollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="p">:</span> <span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="k">public</span> <span class="n">IEnumerator</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">GetEnumerator</span><span class="p">()</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="c1">// The invariant is valid here</span>
</span><span class='line'>
</span><span class='line'>    <span class="n">var</span> <span class="n">result</span> <span class="p">=</span> <span class="n">_sortedElements</span><span class="p">.</span><span class="n">Sort</span><span class="p">().</span><span class="n">GetEnumerator</span><span class="p">();</span>
</span><span class='line'>    <span class="c1">// The invariat is valid here (state wasn&#39;t modified)</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">return</span> <span class="n">result</span><span class="p">;</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">public</span> <span class="k">void</span> <span class="nf">Add</span><span class="p">(</span><span class="n">T</span> <span class="n">e</span><span class="p">)</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="c1">// The invariat is valid here</span>
</span><span class='line'>
</span><span class='line'>    <span class="k">this</span><span class="p">.</span><span class="n">_sortedElements</span> <span class="p">=</span> <span class="n">_sortedElements</span><span class="p">.</span><span class="n">Append</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
</span><span class='line'>    <span class="c1">// The invariant is not valid here!</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>It is true, that should pass the test too. However, if we change the implementation then the code will break the <em>invariant</em>. The <em>class invariant</em> &#8220;guided&#8221; me to choose the implementation.</p>

<p>As an exercise, think about what would be the <em>invariant</em> in that case.</p>

<h2>Summary</h2>

<p>Finding the invariant helps us to discover the implementation and make sure that our methods are not only valid from the interface point of view but also sound in terms of the internal structure.</p>

<p>If finding <em>pre</em> and <em>post</em> is a hard task (the hardest part of TDD) finding the <em>invariant</em> is even harder. I&#8217;m not saying this to discourage you (after reading all the post? C&#8217;mon!). Quite the opposite.</p>

<p>Sometimes when writing a test (and later the implementation) we are not sure where to start. We may spend quite a bit of time looking at the test code or a class code with the feeling that something&#8217;s wrong, and not sure why.</p>

<p>Having the practice of finding <em>Pre</em>, <em>Post</em> and <em>Invariant</em> in your tool belt can help you identify the reason, simplify your task and assist you to find unwanted complexity and <em>code smells</em> right away.</p>

<p>And if it doesn&#8217;t work, clearly is time to go home and have a beer. Either way, you win.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Method specification]]></title>
    <link href="http://orthocoders.com/blog/2012/07/23/testing-the-test/"/>
    <updated>2012-07-23T20:37:00-05:00</updated>
    <id>http://orthocoders.com/blog/2012/07/23/testing-the-test</id>
    <content type="html"><![CDATA[<h2>Stateless</h2>

<p>In the <a href="http://orthocoders.com/blog/2012/07/22/why-testing-is-so-hard/">previous post</a> I introduced the <em>Precondition</em> and <em>Postcondition</em> concepts. Today we are going to explore some examples and see how the specification (pairs of pre and post conditions) will guide our tests.</p>

<p>Let&#8217;s start with methods that don&#8217;t depend on the instance state, usually called <em>static</em> methods.</p>

<h3>Hip to be Square</h3>

<p>Consider a method <em>Square</em> that takes an <em>int</em> and returns the square:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">int</span> <span class="nf">Square</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>What is the <em>Pre</em>? What do we need in order to run <em>Square</em>? Not much, any <em>int</em> should do.
So I just want to indicate that <em>x</em> has a value (any value) by using the constant <em>X<sub>0</sub></em>:</p>

<!-- more-->




<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">/// Pre: x = X0</span>
</span><span class='line'><span class="kt">int</span> <span class="nf">Square</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span>
</span><span class='line'><span class="c1">/// ???</span>
</span></code></pre></td></tr></table></div></figure>


<p>What is the <em>Post</em>? It we have a input value (the result should be X<sub>0</sub><sup>2</sup> no matter what&#8217;s the input value X<sub>0</sub>.</p>

<p>So now our method could look something like (<em>r</em> indicates the result value):</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">/// Pre: x = X0</span>
</span><span class='line'><span class="kt">int</span> <span class="nf">Square</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span>
</span><span class='line'><span class="c1">/// Post: r = X0 * X0</span>
</span></code></pre></td></tr></table></div></figure>


<p>And that would help us to create a test that does something like:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="na">[Test]</span>
</span><span class='line'><span class="k">public</span> <span class="k">void</span> <span class="nf">It_should_return_the_square_value</span><span class="p">([</span><span class="n">Values</span><span class="p">(...)]</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="c1">// arrange (nothing to do)</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// act</span>
</span><span class='line'>  <span class="n">var</span> <span class="n">r</span> <span class="p">=</span> <span class="n">Math</span><span class="p">.</span><span class="n">Square</span><span class="p">(</span><span class="n">x</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// assert</span>
</span><span class='line'>  <span class="n">Assert</span><span class="p">.</span><span class="n">That</span><span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="n">Is</span><span class="p">.</span><span class="n">EqualTo</span><span class="p">(</span><span class="n">x</span> <span class="p">*</span> <span class="n">x</span><span class="p">));</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Last bit, what happens if we use a value that does not <em>satisfy</em> the <em>pre</em>? Diving by zero, etc? Exactly, you get an exception!</p>

<h3>Adding an element to a Collection</h3>

<p>Consider the method of the interface <em>ICollection&lt;T></em> that (to make things easier) returns a new collection.</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">Add</span><span class="p">(</span><span class="n">T</span> <span class="n">e</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>In order to add an element to the collection we don&#8217;t need any particular condition on the element to be added so let&#8217;s write a similar precondition as before to indicate that the element has a value E<sub>0</sub>:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">/// Pre: e = E0</span>
</span><span class='line'><span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">Add</span><span class="p">(</span><span class="n">T</span> <span class="n">e</span><span class="p">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>When the element is added we could say we expect it to be part of the collection:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">/// Pre: e = E0</span>
</span><span class='line'><span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">Add</span><span class="p">(</span><span class="n">T</span> <span class="n">e</span><span class="p">);</span>
</span><span class='line'><span class="c1">/// Post: r should include E0</span>
</span></code></pre></td></tr></table></div></figure>


<p>With that information the test should look like:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="na">[Test]</span>
</span><span class='line'><span class="k">public</span> <span class="k">void</span> <span class="nf">It_should_include_the_value_in_the_collection</span><span class="p">([</span><span class="n">Values</span><span class="p">(...)]</span><span class="n">T</span> <span class="n">e</span><span class="p">)</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="c1">// arrange</span>
</span><span class='line'>  <span class="n">var</span> <span class="n">c</span> <span class="p">=</span> <span class="k">new</span> <span class="n">TCollection</span><span class="p">();</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// act</span>
</span><span class='line'>  <span class="n">var</span> <span class="n">r</span> <span class="p">=</span> <span class="n">c</span><span class="p">.</span><span class="n">Add</span><span class="p">(</span><span class="n">e</span><span class="p">);</span>
</span><span class='line'>
</span><span class='line'>  <span class="c1">// assert</span>
</span><span class='line'>  <span class="n">Assert</span><span class="p">.</span><span class="n">That</span><span class="p">(</span><span class="n">r</span><span class="p">,</span> <span class="n">List</span><span class="p">.</span><span class="n">Contains</span><span class="p">(</span><span class="n">e</span><span class="p">));</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Now that we have test, we can write the actual implementation.</p>

<p>Pair programming is great and when doing <em>TDD</em> is nice to play &#8220;ping pong&#8221; by letting one of the developers write the test and the other one write the implementation to <em>satisfy</em> that test (and only that). Is an excellent exercise to see how complete our tests are.</p>

<p>So given the test and specification above the implemented code could look like:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="k">public</span> <span class="n">SomeCollection</span> <span class="p">:</span> <span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span>
</span><span class='line'><span class="p">{</span>
</span><span class='line'>  <span class="k">public</span> <span class="nf">SomeCollection</span><span class="p">(</span><span class="n">T</span> <span class="p">[]</span><span class="n">elements</span><span class="p">)</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="c1">// store the elements</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'>
</span><span class='line'>  <span class="k">public</span> <span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">Add</span><span class="p">(</span><span class="n">T</span> <span class="n">e</span><span class="p">)</span>
</span><span class='line'>  <span class="p">{</span>
</span><span class='line'>    <span class="k">return</span> <span class="k">new</span> <span class="n">SomeCollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;(</span><span class="k">new</span> <span class="p">[]{</span><span class="n">e</span><span class="p">});</span>
</span><span class='line'>  <span class="p">}</span>
</span><span class='line'><span class="p">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Does it pass the test? Yes it does.</p>

<p>Does it smell? Yes it does!</p>

<p>But why? Where&#8217;s the problem? Exactly, our specification is incomplete!</p>

<p>The test should work for any given collection not only <em>empty</em> ones. We are not making any reference to the values in the collection before the method is called and after. Let&#8217;s do a new version including the values of the collection c as C<sub>0</sub>:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="c1">/// Pre: e = E0 and c = C0</span>
</span><span class='line'><span class="n">ICollection</span><span class="p">&lt;</span><span class="n">T</span><span class="p">&gt;</span> <span class="n">Add</span><span class="p">(</span><span class="n">T</span> <span class="n">e</span><span class="p">);</span>
</span><span class='line'><span class="c1">/// Post: r = C0 + E0 (no matter the order)</span>
</span></code></pre></td></tr></table></div></figure>


<h3>What&#8217;s next?</h3>

<p>The completeness of the test will depend on how good our specifications are.</p>

<p>With a bit of practice we will feel more comfortable writing specifications and use them to drive our unit tests.</p>

<p>Looking at examples that work with immutable classes is the first step, but not always classes are immutable or we can work with a paradigm/language/framework that supports natively that kind of operations.</p>

<p>In the next post I&#8217;ll cover working with the instance state and use it in our specifications.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Why testing is so hard]]></title>
    <link href="http://orthocoders.com/blog/2012/07/22/why-testing-is-so-hard/"/>
    <updated>2012-07-22T14:54:00-05:00</updated>
    <id>http://orthocoders.com/blog/2012/07/22/why-testing-is-so-hard</id>
    <content type="html"><![CDATA[<h2>Choosing what to test</h2>

<p>Testing is the process we apply in order to make sure that software applications work as expected.</p>

<p>Sounds easy, but it is not.</p>

<p>Starting from the outside in approach, the <em>first</em> form of validation is writing an <em>acceptance criteria</em> for a feature that may include many valid scenarios. This kind of test is called <strong>aceptance testing</strong>, should be end to end crossing all the layers and, a black box in the sense we don&#8217;t know the details of how it is implemented.</p>

<p>Acceptance can be done either automated (using tools like <a href="http://specflow.org">Specflow</a>, <a href="http://cukes.info">Cucumber</a>, etc), manually or a combination of both.</p>

<!-- more -->


<p>The <em>second</em> form of validation is writing a test for a <em>class</em>, more specific a <em>method</em> that should implement a piece of functionality. That is what is called <strong>unit testing</strong> and is associated to one class, one method. All the collaborators should be &#8220;faked&#8221; in order to avoid coupling and to make sure the test is for the class and not for the dependencies.</p>

<p>The <em>third</em> form of validation is writing a test that involves two or more classes to validate how they interact. This is called <strong>integration testing</strong>. <em>Integration</em> is usually used when having doubts how the classes will work together (though unit test should take care of that) and writing an <strong>acceptance test</strong> is very difficult.</p>

<p>I am going to focus today on <strong>unit testing</strong> more specifically when using <strong>Test Driven Development</strong>.</p>

<h2>Test Driven Development adoption</h2>

<p>Writing a test after the method is already written is playing catch up. Not very useful.</p>

<p>On the other hand, <strong>TDD</strong> proposes the <em>test first approach</em>, here are the rules by Uncle Bob <a href="http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd">Rules of TDD</a> if you are unfamiliar with the methodology.</p>

<p>Using <strong>TDD</strong> changes completely the way we write software. <em>Quality</em> as a driver gives us the confidence of modifying our code and makes more enjoyable our task. And don&#8217;t make me start about all the design benefits!</p>

<p>However, if it is all ponies and rainbows with such awesome results, why most teams don&#8217;t use it? Why adoption is so low?</p>

<p>The problem is that writing <em>tests</em> is <strong>harder</strong> than writing <em>regular code</em>.</p>

<h2>Harder than <em>what</em>?</h2>

<p>But, isn&#8217;t that crazy? Isn&#8217;t writing tests actually writing more code? If we know how to code, shouldn&#8217;t we know for sure how to write tests? Maybe I forgot to take my meds this morning?</p>

<p><strong>Test first</strong> help us discover coupling issues and identify <em>smelly</em> code. How? Whenthe test  is getting complex that indicates we have an abstraction problem, some dependencies that should be there, or something even smellier lurking in the code.</p>

<p>One of the questions I usually get asked about <em>TDD</em> is <strong>how are you going to write a test for a method that does not exist yet?</strong>.</p>

<p>How are you going to write code for method that you don&#8217;t know what is supossed to do? Well, you don&#8217;t.</p>

<p>For sure you need some kind of idea, hint or inkling of what should happen. We need a  trustworthy approach, a bit more formal perhaps, that will take us through the <em>TDD</em> path letting the methodology become our ally and <strong>code quality driver</strong>.</p>

<h3>What does this method do?</h3>

<p>Each method can be defined in terms of the input parameters and the output values based on those parameteres.</p>

<p>That means that each method will have a <em>set</em> (collection) of values that can be passed (the domain) as valid parameters and a <em>set</em> of values that will be the result based on the input.</p>

<p>In order to identify either <em>set</em> I will use a <em>predicate</em> that will help filter which values are valid. Each value that satisfies the <em>predicate</em> (returns <em>true</em>) will be part of the set.</p>

<p>The <em>predicate</em> that defines the values that are a valid input is called <em>Precondition</em>. The <em>Precondition</em> will help us indentify the domain of values that we could use as valid inputs for the test.</p>

<p>The <em>predicate</em> that describes the output of the method is called <em>Postcondition</em>. The <em>Postcondition</em> will help us identify the <em>asssertions</em> to write and the <em>scenarios</em> to test in order to ensure that the method works.</p>

<p>I know, is a lot to take in one post, so rest a bit and think about the following exercise:</p>

<p>Find the <em>Pre</em> and <em>Post</em> for the method <em>Square</em> that takes an <em>int</em> and returns the square:</p>

<figure class='code'> <div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='csharp'><span class='line'><span class="kt">int</span> <span class="nf">Square</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>In the next post I&#8217;m going to show examples and consider what happens when the method modifies the state of the class.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Agile vs. Craftsmanship]]></title>
    <link href="http://orthocoders.com/blog/2012/07/20/agile-vs-craftsmanship/"/>
    <updated>2012-07-20T18:12:00-05:00</updated>
    <id>http://orthocoders.com/blog/2012/07/20/agile-vs-craftsmanship</id>
    <content type="html"><![CDATA[<h2>The <strong>Agile</strong> chain reaction</h2>

<p>Some time ago I was doing a presentation for a company about <strong>Kanban</strong> discussing the benefits of using it and how Kanban can be adapted to their process without modifying anything.</p>

<p>I was discussing the concept of <strong>Lead Time</strong> and wanted to hear from the atendees if they had an idea of what was the <em>lead time</em> in their current projects. So I asked each of the participants what they thought in turns, and after two or tree answers one of them said something like:</p>

<blockquote><p>Participant: &#8220;But this is Agile! And I worked in an agile project and failed!&#8221;</p>

<p>Me: &#8220;Well, actually it can be used with any process not only Agile&#8221;</p>

<p>Participant: &#8220;It doesn&#8217;t matter! It smells like Agile!&#8221;</p></blockquote>

<p>So I moved on, but made a mental note, that I had to analyze what had just happened later.</p>

<!-- more -->


<h2>Ponchos and flip flops</h2>

<p>When I meet with a client or I&#8217;m doing a training that involves discussing <strong>Agile</strong> concepts my first bit of advice is <strong>Never, ever, ever use the word <em>Agile</em>!</strong></p>

<p>Why you ask? Because as soon the word <strong>Agile</strong> is mentioned it depicts an image of developers wearing <a href="http://en.wikipedia.org/wiki/Poncho">ponchos</a> and flip flops riding <a href="http://starwars.wikia.com/wiki/Tauntaun">tauntauns</a> in a crusade to abolish planning, estimates, and budgets while holding a banner that says <em>&#8220;Down with Gantt charts!&#8221;</em>. And it&#8217;s all downhill from there&#8230;</p>

<p>What is the trick then? Call it <strong>Good practices</strong> (or any other positive yet somehow ambiguos term) from now on, and remove that barrier that causes people to recoil and ask for oxygen! Who will be against <strong>Good practices</strong> after all? Just keep implementing them, having great results and if someone asks you about &#8220;Isn&#8217;t this Agile?&#8221;, just find your most &#8220;outraged&#8221; face , deny it and move on.</p>

<h2>The elephant in the room</h2>

<p>However, that is not enough. <strong>Agile</strong> already left a sour taste in more than one mouth and the feedback I got in my presentation was a clear example of that. What can cause such a reaction?</p>

<p>Similar to any other thought process that we apply when chosing banks, cell phone companies, supermarkets and software, bad experiences will teach us to never try a particular vendor, brand, etc. again. The effect of having experienced a process change setup under an <strong>Agile</strong> banner and that went really, really bad produces the exact same result.</p>

<p><strong>Agile</strong> is not a <em>silver bullet</em> or a <em>pill</em> that you can take in the morning to <em>enlarge</em> your estimation abilities, work better with your team, and improve your results.</p>

<p>Reading a book about <strong>Agile</strong> is not enough. Doing a training about <strong>Agile</strong> is not enough.</p>

<p>It is true that you can start by implementing Scrum or using Kanban (or any combination) to improve your planning, communication, transparency etc&#8230; and that&#8217;s indeed pretty good.</p>

<p>However you will find that there is a bump on the road that is unavoidable. The quality of your code.</p>

<h2>Software craftsmanship is the key</h2>

<p>Writing code is an art that has to be honed, cared for, and continuosly improved.</p>

<p>Coding is at the heart of most software projects, we can&#8217;t forget that or put it aside.</p>

<p>In order to improve our work we need to be <em>craftsmen</em> and make sure that we can generate code with the highest quality possible.  Not doing so, will always keep us from embracing a culture of continuos improvement where we deliver on time, on budget, and enjoy what we do once again.</p>

<p>In his <em>Kanban</em> book, <em>David Anderson</em>, as part of his recipe for success he lists in first place to <em>&#8220;Focus on quality&#8221;</em>. <strong>First</strong>, not second, not third&#8230;</p>

<p>How we become <em>craftmen</em>? Here are some tips:</p>

<ul>
<li>Embrace testing in all forms, unit testing, acceptance testing and let <strong>TDD</strong> and <strong>BDD</strong> drive your coding</li>
<li>Practice, practice, practice (Katas, exercises, etc&#8230;)</li>
<li>Participate in events related to your interests and others that may challenge you</li>
<li>Learn a functional language and apply concepts on your job</li>
<li>Find a Mentor that can review what you do and &#8220;slap&#8221; you when necesary</li>
</ul>


<p>Want to be faster? More accurate? Become better at what you do.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[WPF MVVM demystified]]></title>
    <link href="http://orthocoders.com/blog/2011/12/02/wpf-mvvm-demistified/"/>
    <updated>2011-12-02T00:00:00-06:00</updated>
    <id>http://orthocoders.com/blog/2011/12/02/wpf-mvvm-demistified</id>
    <content type="html"><![CDATA[<h2>Motivation</h2>
Lately I have been hearing a few discussion about using MVVM as a pattern to work with desktop apps when using .NET and WPF.

The first question usually is about justifying the use of the pattern compared to MVC or MVP. It&#8217;s all about responsibilities and how the data and logic is organized.

While I&#8217;m not going to describe all the differences I want to highlight some important aspects of the pattern when working with WPF applications.

<!-- more -->

<em>First</em> Highlight: WPF is not WinForms. Why? <strong>NO CODE BEHIND</strong>!

Second Highlight: What are the benefits of it? <strong>BINDING</strong>!

<em>Third</em> Highlight: Is binding important when using WPF? <strong>ESSENTIAL</strong>!

<em>Fourth</em> Highlight: What about generating the M - V - VM? <strong>NOT ENCOURAGED, BE CAREFUL</strong>!
<h2>The good old days with no binding</h2>
Before using WPF there was WinForms&#8230;

The &#8220;idiomatic&#8221; way of making the views update in WinForms was either using code behind or letting the controller manipulate the view by knowing which view (or interface) was using, thus creating a dependency between them.

The problem with that approach is that we are breaking encapsulation and assigning multiple responsibilities to classes that should be dedicated to only one of them. Remember, one source multiple views, and all that jazz. We should be able to create new views with no additional pain.

I remember clearly wondering about :
<blockquote>&#8220;Wouldn&#8217;t be great to have a way to <em>bind</em> my view to some kind of class so I don&#8217;t have to keep having controllers that update the text field view when the text changes, etc?&#8221;</blockquote>
So I decided to create my collection of <em>binders</em> to make my life easier and look what happened next&#8230;
<h2>Binding as a first citizen</h2>
The next iteration of MS desktop tools brought <strong>WPF </strong>and the idiomatic way of building views was using <strong>Binding</strong>! Yay!

Why is so good? Because the views use reflection to know when your source has changed!

What&#8217;s the tradeoff you ask? You need to implement a protocol to notify when change happens. Either using <em>INotifyPropertyChanged </em>interface or dependency properties.

&#8220;Awesome!&#8221; - You say.

&#8220;Now I can just grab my models and add the notification, and no more controllers, and&#8230;&#8221; - STOP!

Wow, slow down&#8230;.. take a deep breath, sit down&#8230; keep reading.
<h2>Modelling, abstraction and everything nice</h2>
We have clear responsibilities assigned between view and model.

<em>View</em> is in charge of displaying what the <em>Model</em> represents.

Now, because we want to use WPF we should not litter our classes with other responsibilities. Imagine tomorrow we have a different framework, what are we going to do? Change them again?

And here is why the <em>ViewModel</em> makes so much sense.

The class that matches with a <em>ViewModel</em> will provide all the necessary binding fields so they can be displayed in that view or any other view. Multiples views, same <em>ViewModel. </em>Is just binding after all.
<h2>No rule, to rule them all</h2>
Now, would that mean the we are going to have always an association one to one between <em>Model</em>, <em>View</em> and <em>ViewModel</em>?

Even more, would that mean that all my &#8220;Models&#8221; are entities populated from an ORM?

Not at all! There&#8217;s no <em>rule</em>, just good design and modelling practices.

A <em>ViewModel</em> may use multiple entities, or no entities at all! The fact that the name is <em>Model</em> does not imply necessarily that is a particular kind of class.

Remember, is a pattern, so we identify the components of the pattern and named them accordingly. However patterns overlap, collaborate and some times use each other (sounds promiscuous, I know).

So be careful! Code generation in my experience will bring you more sorrow than happy days!

What classes are you going to generate anyways? How can you be sure before hand what all the models, etc, look like?

Forcing all the objects to inherit base classes because they are all &#8220;ViewModels&#8221; or &#8220;Models&#8221; may produce the same result.

There&#8217;s no magic bullet or pill you can take.

So what to do? Use binding, will save you lots of time, write some nice code (with tests to add confidence), and then when you have a very clear idea of what are you building and you can justify it, abstract, refactor and generate code or create base classes if needed.
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Meet the Clojure programming language]]></title>
    <link href="http://orthocoders.com/blog/2011/10/14/meet-the-clojure-programming-language/"/>
    <updated>2011-10-14T00:00:00-05:00</updated>
    <id>http://orthocoders.com/blog/2011/10/14/meet-the-clojure-programming-language</id>
    <content type="html"><![CDATA[<h4 class='highlight'>
  <section>
I have the pleasure to welcome 
<a title="Sebasitan Galkin's twitter" href="http://twitter.com/paraseba" target="_blank">Sebastian Galkin </a>
as a guest contributor to my blog. 

I have known Sebastian for some years, since I used to be his manager in one of his first jobs in a software company. At that time he already had a degree in Electrical Engineering and a Masters in Physics under the belt.

I have been always very impressed with how smart Sebastian is, his uncanny thirst for knowledge and how little time he needs in order to learn and get familiar with new technologies.

Sebastian simply excels at sofware development. He is one of the most knowledgeable developers I know and he has been working with Clojure now for more than a year.

I always enjoy to bounce ideas with him to help me realize how wrong I am.

Please read on, I am positive you are in for a treat!
</section>
</h4>

<!-- more -->

<h2>Introduction</h2>
In this post I&#8217;ll present you with the Clojure programming language. I hope I&#8217;ll be able to show you how writing Clojure code <em>feels</em>, and motivate you to dive deeper into it.

If you want to know more about Clojure, you can&#8217;t miss the three days <a href="http://maventhought.com/?p=882">hands-on training</a> I&#8217;ll be giving in Winnipeg, November 2011.
<h2>What is Clojure</h2>
Clojure is a general purpose language that runs on top of the Java Virtual Machine or the Common Language Runtime or, even, JavaScript. So, if you already have systems running Java or .NET you can easily integrate Clojure in your workflow.

Clojure inherits powerful traits from the Lisp family of languages, and its ubiquity from the host platform (JVM, CLR, js). It encourages functional programming style and brings to the table a great set of multithreading primitives to make multithreaded programming easier.

You may be thinking: &#8220;But I don&#8217;t have the chance to use Clojure at work!&#8221;, and wondering why you should keep reading. Read a bit more, you won&#8217;t regret it.

Here is the secret: Learning Clojure will greatly improve your toolbox as a programmer. You will find that after spending some time reading about it and using it, the way you write code will change dramatically .

If we look at the market, there is a big wave of interest in functional languages, ranging from Haskell and F#, to Scala and Clojure. This is motivated in part by the increased complexity in our systems and the need to embrace multiple hardware cores.
<div style="width: 540px;"><a title="ruby,java,scala,clojure Job Trends" href="http://www.indeed.com/jobtrends?q=ruby%2Cjava%2Cscala%2Cclojure&amp;relative=1&amp;relative=1">
<img class="alignleft" src="http://www.indeed.com/trendgraph/jobgraph.png?q=ruby%2Cjava%2Cscala%2Cclojure&amp;relative=1" alt="ruby,java,scala,clojure Job Trends graph" width="540" height="300" border="0" />
</a>
<table style="font-size: 80%;" width="100%" border="0" cellspacing="0" cellpadding="6"><caption>This job trends graph shows relative growth for jobs we find matching your search terms</caption>
<tbody>
<tr>
<td><a href="http://www.indeed.com/jobtrends?q=ruby%2Cjava%2Cscala%2Cclojure&amp;relative=1&amp;relative=1">ruby,java,scala,clojure Job Trends</a></td>
<td align="right"><a href="http://www.indeed.com/jobs?q=Ruby">Ruby jobs</a> - <a href="http://www.indeed.com/jobs?q=Java">Java jobs</a> - <a href="http://www.indeed.com/jobs?q=Scala">Scala jobs</a> - <a href="http://www.indeed.com/jobs?q=Clojure">Clojure jobs</a></td>
</tr>
</tbody>
</table>
</div>
<h2>Sounds very nice, but where&#8217;s the code?</h2>
Instead of enumerating the primitives and syntax constructs of the language, lets look at some examples and go over the explanation in detail togeteher.

We will use a simple problem I just made up to showcase some of Clojure features. Here is the problem:
<blockquote><em>We have a file with words, one word per line. We want to read that file and print all 10 character words in it.</em></blockquote>
Simple, artificial and useless; but more than enough to illustrate the traits of the language. Read on&#8230; read on&#8230;.

First lets define a constant holding the path to the file:

[code language=&#8221;clojure&#8221; light=&#8221;true&#8221;]
(def file-path &quot;words.txt&quot;)
[/code]

What&#8217;s going on here:
<ul>
	<li>Clojure uses <em>Lisp</em> syntax: function calls begin with an opening parentheses, followed by the function name, followed by the
arguments separated by spaces and ending with a closing parentheses. So, in this case, we are &#8220;calling&#8221; <code>def</code>, passing <code>file-path</code> and <code>"words.txt"</code> as arguments.</li>
	<li>As you can see, <em>Clojure</em> uses prefix notation, if we would want to add two numbers we would write <em><code>(+ 3 4)</code></em>, again start with &#8220;(&#8220;, then the function name, then the arguments and finally the &#8221;)&#8221;. In <em>Clojure <strong><code>+</code></strong></em> is just a function name, there is no special behavior for operators.</li>
	<li><em><code>def</code></em> associates or binds a name with a value, it receives two arguments, first the new name, then the value associated with it. So, <em><code>file-path</code></em> is the name of the constant we are defining.</li>
	<li><code>"words.txt"</code> is a literal string. In <em>Clojure</em> strings are delimited by double quotes.</li>
</ul>
Now if we use <em><code>file-path</code></em> in our code, it will get &#8220;replaced&#8221; by its value, the string <em>words.txt</em>.

Back to our problem, how do we read the file contents?

[code language=&#8221;clojure&#8221;]
(with-open [reader (clojure.java.io/reader file-path)]
  &#8230;..
  &#8230;..)
[/code]

Lets peel this onion (fine, orange for you) from the inside out:

[code language=&#8221;clojure&#8221; light=&#8221;true&#8221;]
(clojure.java.io/reader file-path)
[/code]

You already guessed this is a function call, because it conforms to the pattern we saw before with <code>clojure.java.io/reader</code> as the function name.

The part of the name before the &#8220;/&#8221; is just a namespace, don&#8217;t worry about it for now, it&#8217;s just a function name. What this line does is open a <code>java.io.Reader</code> pointing to words.txt file in the current directory.

A <code>java.io.Reader</code> is a Java object that allows you to read from a stream, in this case, a file. We will use this reader to get all the words from the file.

[code language=&#8221;clojure&#8221;]
(with-open [reader &#8230;.(1)&#8230;.]
  &#8230;&#8230;.(2)&#8230;..)
[/code]

<code>with-open</code> is a function that binds a name (in this case <code>reader</code>) to a value (in this case the expression (1)), then executes the nested body (in this case (2)), and finally calls the reader&#8217;s <code>close</code> method. Inside the body of <code>with-open</code>, the expression (2), you can use the <code>reader</code> variable.

So, why we use <code>with-open</code>? To make sure that it doesn&#8217;t matter what happens inside the body, the reader gets always closed.
<blockquote>
<h5>Short digression:</h5>
We just saw new syntax, the square brackets. Square brackets are the syntax for literal vectors in Clojure. [0 29 &#8220;hi&#8221; &#8220;bye&#8221;] is a vector with 4 elements. Also, parentheses are not just the syntax for function calls, it&#8217;s also the syntax for
lists, so (1 2 3 4) is a Clojure list. Lists and vectors differ in their complexity guarantees as you would expect.

What we see here, is that Clojure code is written using Clojure data structures!

Think about that for a moment, a function call in Clojure is just a list, and we saw that Clojure vectors also appear as part of Clojure code.

This is a property of all Lisp languages and has fantastic implications!</blockquote>
Back to the problem again, we already have our file opened, we need to read all lines and process them. We&#8217;ll create a function to make it easy to reuse:

[code language=&#8221;clojure&#8221;]
(def process-lines
  (fn [path f]
    (with-open [reader (clojure.java.io/reader path)]
      (f (line-seq reader)))))
[/code]

Lots of parenthesis, I know&#8230;

Our old friend <code>def</code> helps us bind the name <code>process-lines</code> to a new function. <code>(fn [...] ...)</code> is how we create new functions, <code>[...]</code> is a vector of arguments to the function.

In <code>process-lines</code> we are receiving two arguments: <code>path</code> and <code>f</code>. Anything that comes after the arguments and inside the <code>(fn)</code> call, is called the function&#8217;s body.

The result of the function will be the last expression evaluated in its body.

Then, <code>process-lines</code> is a function which takes two arguments. <code>path</code> indicates the location of the file to read, that&#8217;s easy, but
what is the <code>f</code> argument?

In Clojure functions are first-class citizens, we can pass them as arguments to other functions return them from function calls, put them inside collections, or whatever we can do with other values such as integers or strings. So, <code>process-lines</code> is taking a function <code>f</code> as argument.

That function will take care of processing all lines in the file.

Do you see how we are reverting the usual flow here?

We don&#8217;t expect <code>process-lines</code> to return the files contents, instead, it receives a function that will do the work. <code>f </code>is called with the result of <code>line-seq</code>, a sequence of strings read from the file, one string for each line.

Now we need to create this function that will take care of printing the matching words, that is, the function that we will pass to <code>process-lines</code>

[code language=&#8221;clojure&#8221;]
(def print-matching
  (fn [words]
    (prn &#8230;)))
[/code]

<code>print-matching</code> receives the sequence of all words, selects the ones matching and prints the result using <code>prn</code>, we still need to fill the
blanks. In some traditional languages you would use the following scheme to obtain the matching words:
<ul>
	<li>Create an empty vector/list</li>
	<li>loop through all the strings in the line sequence</li>
	<li>if a string has 10 characters add it to the vector/list and continue with the next step of the loop</li>
	<li>if a string length is not 10, just go to the next step of the loop</li>
	<li>when the loop ends, return the populated vector/list</li>
</ul>
You probably have no problem understanding this, because it&#8217;s familiar to you from languages such as C or Java. But it&#8217;s not <strong>conceptually simple</strong> at all.

There are lots of interactions to track, lots of interleaving moving parts. What we want to do is simpler, we just want to <em>filter</em> the list of words, keeping only those with length 10.

Instead, we could write:

[code language=&#8221;clojure&#8221; light=&#8221;true&#8221;]
(filter length-10? words)
[/code]

Simple, right? This line express exactly what we have in mind.

Let&#8217;s dive in:
<ul>
	<li>Of course, this is a call to the Clojure function <code>filter</code></li>
	<li>the first argument <code>length-10?</code> is a function we didn&#8217;t define yet, which will return true whenever its only argument is a string of length 10. Function names can contain symbols, and the final &#8220;?&#8221; is just a convention used for functions that return a boolean</li>
	<li><code>words</code> is the argument to <code>print-matching</code>: the sequence with all words in the file</li>
	<li>the result of the <code>filter</code> call will be a new sequence of strings, containing only those string in the input, that make
<code>length-10?</code> return true. That&#8217;s exactly what we wanted.</li>
	<li>Notice that the original sequence of words is not modified. <code>filter</code> returns a new sequence leaving the input sequence intact.</li>
	<li>In fact, all Clojure collections are immutable, you can&#8217;t modify its contents. Sounds weird? Don&#8217;t worry we self impose this constraint to get code that&#8217;s easier to reason with, easier to test, to debug and to parallelize.</li>
	<li>And, to get the cherry on top, we still can do everything you would do with traditional, mutable collections.</li>
</ul>
Lets write <code>length-10?</code> now:

[code language=&#8221;clojure&#8221;]
(def length-10?
  (fn [word]
    (= 10 (count word))))
[/code]

We are defining a function, that takes one argument <code>word</code>. It returns the result of calling the function <code>=</code> which is the equality comparison function (in some other languages <code>==</code> is used for this).

<code>(count word)</code> returns the length of the word. So this function returns the boolean true value if the argument has length 10 and false otherwise.

Now, we have written all the parts, we just need to call <code>process-lines </code>passing the appropriate arguments. Lets see the whole program

[code language=&#8221;clojure&#8221;]
(def file-path &quot;words.txt&quot;)

(def process-lines
  (fn [path f]
    (with-open [reader (clojure.java.io/reader path)]
      (f (line-seq reader)))))

(defn length-10? [word]
  (= 10 (count word)))

(def print-matching
  (fn [words]
    (prn (filter length-10? words))))

(process-lines file-path print-matching)
[/code]

As you can see, we are calling <code>process-lines</code> passing our file path constant and the function <code>print-matching</code>. Passing a function as argument is easy, we already have a constant defined with <code>def </code>(<code>print-matching</code>) pointing to that function, so we just use that
constant, exactly the same thing we are doing with the other argument <code>file-path</code>.
<h2>Smelly, smelly, naughty, naughty!</h2>
That&#8217;s it, that works and it&#8217;s easy to understand (once you get used to the parentheses), but let&#8217;s improve it a little bit. <code>length-10?</code> smells bad. If the requirements changed to match 15 characters words, we don&#8217;t want to change the function name.

We are going to generalize the function. Lets go top-down and write first how we would like to use it:

[code language=&#8221;clojure&#8221; light=&#8221;true&#8221;]
(filter (length-matcher 10) words)
[/code]

That&#8217;s better, 10 is just an argument to a function call, we could easily change it to other number or read it from the console. Now, we know <code>filter </code>takes as its first argument a boolean function, and that means that the result of the <code>(length-matcher 10)</code> call must be a function.

If you never saw something like this in other languages, your head may be spinning right now.
<code>length-matcher</code> is a function that, when called, will return another function. If you think about it, it&#8217;s not as fancy as it sounds, functions are just another type of values, we can do whatever we want with them. Lets right <code>length-matcher</code> then

[code language=&#8221;clojure&#8221;]
(def length-matcher
  (fn  [n]
    (fn [word]
      (= n (count word)))))
[/code]

Wow, there is a lot of <em>functioning</em> there, we are writting functional code after all.
<ul>
	<li><code>length-matcher</code> is a function of 1 argument <code>n</code>, the length of the words we want to match</li>
	<li>as you should remember <code>(fn)</code> is what we use to create new functions in Clojure, so the result of <code>length-matcher</code> will be
another function</li>
	<li>this returned function will also have 1 argument <code>word</code>, and will return a boolean, the result of the equality comparison.</li>
</ul>
So, <code>length-matcher</code> is a function that, when called with <code>n</code> will return a new function that when called with a word, will
return true if that word has length n. Phew&#8230;. I need some water&#8230; feel free and get some too&#8230;.

Little test to make sure you are following so far:
<ul>
	<li>What is the type of <code>length-matcher</code>?</li>
	<li>What is the type of <code>(length-matcher 10)</code>?</li>
	<li>What is the type of <code>((length-matcher 10) "hello")</code>?</li>
</ul>
Solutions:
<ul>
	<li>A function of one integer argument that returns a function of one string argument</li>
	<li>A function of one string argument</li>
	<li>A boolean. The result of <code>(length-matcher 10)</code> is a function, we are calling that function passing &#8220;hello&#8221; as argument.</li>
</ul>
OK, now you understand how our new code works and how easy is to change the length matched.

Here is the full program

[code language=&#8221;clojure&#8221;]
(def file-path &quot;words.txt&quot;)

(def process-lines
  (fn [path f]
    (with-open [reader (clojure.java.io/reader path)]
      (f (line-seq reader)))))

(def length-matcher
  (fn [n]
    (fn [word]
      (= n (count word)))))

(def print-matching
  (fn [words]
    (prn (filter (length-matcher 10) words))))

(process-lines file-path print-matching)
[/code]
<h2>What else do we get?</h2>
<strong>Short</strong>: Size is a great predictor for number of bugs. Short code has fewer bugs.

<strong>Abstract</strong>:We are embracing the powerful filter abstraction. To understand and modify the code, you don&#8217;t need to understand the details of the iteration mechanism, filtering is an abstract operation that we translate directly to code.

<strong>Declarative</strong>: We are just expressing what the code must do, not how to do it. For instance, we are not giving details about how the file should be read, nor how the sequence should be traversed, nor how a temporary sequence should be populated. These are details we don&#8217;t what to deal with, this allows as to work at a higher level of abstraction.

<strong>Testable</strong>: You could test <code>length-matcher</code>, <code>print-matching</code> and <code>process-lines</code> in isolation. The result of each of this functions depends only on its arguments, there is no hidden state or side-effects, that makes them much easier to test. This is a huge advantage of the functional style.

<strong>Maintainable</strong>: If requirements change, and you no longer need to output 10 characters strings, you just need to change the filtering function. Suppose you are asked to match all words with less than 10 characters. That&#8217;s easy, change your length-matcher (or create a new function) to:

[code language=&#8221;clojure&#8221;]
(defn length-matcher [n]
  (fn [word]
    (&lt; (count word) 10)))
[/code]

<strong>Lazy</strong>: This would need a whole new post to explain it but it&#8217;s so cool that I need to tell you about it.
Suppose the file were 10 GB in size. Suppose you don&#8217;t need to get all 10 character words, but only the first 50. What would you do?

Clearly our code is too naive to deal with this use case. You don&#8217;t want to load all 10 GB of words in memory, filter all of them to get a huge sequence of 10 characters words, and then, only keep the first 50 words. That would be awful.

The key here is that <strong>our code is not too naive!</strong>. Clojure will do it for you:

[code language=&#8221;clojure&#8221;]
(take 50
      (filter (length-matcher 10) (read-lines file-path)))
[/code]

That will get the first 50 words. But the good news is that read-lines and filter are lazy functions (remember that read-lines is our own code, but is lazy anyway).

Those functions will only process information when they are required to. The program will run without a problem on big files, because it won&#8217;t process more than it needs to.

Think about how would you do this in your language of choice. Chances are that you will need to change all the design and interfaces. Clojure embraces laziness in their sequence processing functions.
<h2>Homework</h2>
The code is not fully decoupled, there is a lot of room for improvements. You could try your hand at Clojure by fixing some of the following <em>smells</em>:
<ul>
	<li><code>print-matching</code> has the double responsibility of filtering and
printing the results</li>
	<li><code>print-matching</code> &#8220;hardcodes&#8221; the length of the matched word</li>
	<li>We are ugly-printing the matching words. To do a better job we need to
iterate the result words and print each one individually.</li>
</ul>
<h2>Conclusion</h2>
Clojure is an unbelievable expressive language, with some of the most powerful abstractions I have seen in any language. We didn&#8217;t even scratch the surface here, there is a lot of awesome features you will want to know about.

If you are interested, hurry up and get the early bird discount to the three days, hands-on <a href="http://maventhought.com/?p=882">Clojure training</a> we are doing in Winnipeg November 6, 7 &amp; 8.

See you there!
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Bowling Game Kata - First attempt]]></title>
    <link href="http://orthocoders.com/blog/2011/09/05/the-bowling-game-kata-first-attempt/"/>
    <updated>2011-09-05T00:00:00-05:00</updated>
    <id>http://orthocoders.com/blog/2011/09/05/the-bowling-game-kata-first-attempt</id>
    <content type="html"><![CDATA[Last week I did a presentation about the <a title="Uncle Bob's Bowling Game Kata" href="http://butunclebob.com/ArticleS.UncleBob.TheBowlingGameKata" target="_blank">Bowling Game kata</a> in C#.

<!-- more -->
I created a <a title="Bowling Game Src Code @ GitHub" href="https://github.com/amirci/bowling_game" target="_blank">repository</a> on GitHub with the code so I can share my first attempt.

You can follow the commit comments to get an idea of the train of thought.

Or if u prefer, just keep reading :)
<h2>The Methodology</h2>
I used TDD and somehow BDD all the way. Started with an acceptance test and jumped in and out from the unit tests until the feature passed.

Why is a good idea to start with an acceptance test?

When you know where you want to go, what you want to achieve, is easier to keep the focus.

Having a way of identifying if the current feature is finished is a lot of power in your hands, so do the minimum necessary to make it work and then - once the test is passing - do refactoring as you see fit.

In the solution you will find three projects:
<ol>
	<li>BowlingKata: Classes that implement the Kata</li>
	<li>BowlingKata.Unit.Tests: Unit tests</li>
	<li>BowlingKata.Acceptance.Test: Features that I&#8217;m looking for in a bowling game</li>
</ol>
<h2>Design Decisions (fast forward TDD)</h2>
As soon as I started to write a unit test for the <em>BowlingGame</em> class I wonder how am I going to design the solution.

My first test was for the method <em>Roll(pins)</em>. And right there I had to assign responsibilities.

What should this method do? Do the &#8220;registration&#8221; only? Do the calculation as well? Is there any other class involved?

I decided on keep things simple and separate two clear responsibilities:
<ol>
	<li>Keeping the number of pins knocked down on each ball (or frames later)</li>
	<li>Calculating the score based on the information on each frame</li>
</ol>
<div>So I created two interfaces with that purpose:</div>
<div>
<ul>
	<li><em>IFrameKeeper</em>: In charge of registering the pins down in each frame</li>
	<li><em>IScoreCalculator</em>: in charge of calculating the score over a sequence of frames (10 frames + 1 optional extra)</li>
</ul>
<div>You can follow all the tests to see how the interfaces grew in complexity to fullfil the intended responsibility.</div>
<div>
<h2>What&#8217;s next?</h2>
After the first approach I thought that would be nice to refactor again and explore other solutions:
<ul>
	<li>Change the frame class <em>IBowlingFrame</em> to be able to calculate the score, maybe having regular frames, spare, and strike.</li>
	<li>Find a way of registering the pins and also add some kind of bonus to avoid the iteration over the frames to get the score</li>
</ul>
<div>Which option did you implement? Please share!</div>
<div>Feedback is more than welcome.</div>
</div>
</div>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Using multiple sources for Nuget]]></title>
    <link href="http://orthocoders.com/blog/2011/04/09/using-multiple-sources-for-nuget/"/>
    <updated>2011-04-09T00:00:00-05:00</updated>
    <id>http://orthocoders.com/blog/2011/04/09/using-multiple-sources-for-nuget</id>
    <content type="html"><![CDATA[<a title="Nuget for local teams" href="http://orthocoders.com/2011/03/26/nuget-for-local-teams/" target="_blank">Last post</a> I talked about installing a local Nuget server and the benefits. However the implementation wasn&#8217;t as simple and straightforward as I expected, here is the roadblocks I found and what I had to do to make it work.

First I installed a local server and then updated the projects to use some of the packages from the local server.

The references were updated. Solution builds fine.

<!-- more -->
So I decided to update the <em>rake </em>build script and add the  local source.  First roadblock ahead.
<h3>More than one source</h3>
Now, I run the <em>rake</em> script to get all the packages to make sure it works and I found that when installing the packages the source is not stored in the  <em>packages.config </em>file<em>.</em>

What a disappointment&#8230; but don&#8217;t let this drag you down&#8230; there&#8217;s still hope!

First I checked on twitter and confirmed that in the current version the source is not part of the packages config and I started a <a title="Nuget Multiple Sources" href="http://nuget.codeplex.com/discussions/251351" target="_blank">discussion</a> on the codeplex nuget site to talk about it.

Now, I have to figure out how to identify the local packages&#8230;
<h3>Using a config file for the local packages</h3>
Because I can&#8217;t store the source of the packages in the packages.config file I decided to use another file, packages_local.config to store my local packages.

Then, I changed the rakefile task to do the following:

[sourcecode lang=&#8221;ruby&#8221;]

FileList[&quot;**/packages_local.config&quot;].each do |file|
	cp file, &quot;packages.config&quot;
	sh &quot;nuget install packages.config /OutputDirectory Packages /source #{local_feed}&quot;
end

[/sourcecode]

If you are wondering why I need to copy the local to &#8220;packages.config&#8221;, is because the command line only accepts &#8220;packages.config&#8221; as a configuration file. Yeah, I know&#8230;.
<h3>Thank god for contributors!</h3>
Luckily, when I was writing this post I received an updated from the nuget <a title="Nuget discussion - Avoid committing depenedencies" href="http://nuget.codeplex.com/discussions/249628">discussion</a> (look at the end) forum talking about using multiple sources.

In the update <a title="Dan Turner @ codeplex" href="http://www.codeplex.com/site/users/view/dant199" target="_blank">Dan Turner</a> mentioned a <a title="Fork that combines both features" href="http://nuget.codeplex.com/SourceControl/network/Forks/dant199/NuGetDanTurner" target="_blank">fork</a> he did of the command line project to add two things:
<ul>
	<li>Using multiple sources</li>
	<li>Using repositories.config (file left inside packages folder) to load all the packages.config</li>
</ul>
Awesome! So I cloned the fork, build the solution, grab the new <em>nuget.exe</em> and voila! It works!

Here is the final version of the rakefile:

[sourcecode lang=&#8221;ruby&#8221;]
desc &quot;Setup dependencies for nuget packages&quot;
task :dep do
	remote_feed = &quot;https://go.microsoft.com/fwlink/?LinkID=206669&quot;
	local_feed = &quot;http://wpgbuild02:8090/dataservices/packages.svc&quot;
	FileList[&quot;**/packages.config&quot;].each do |file|
		sh %Q{nuget install #{file} /OutputDirectory Packages /Source &quot;#{remote_feed};#{local_feed}&quot;}
	end
end
[/sourcecode]

I&#8217;m still using the <em>FileList</em> to get all the packages.config because the <em>Packages</em> folder is removed and not stored in the repository.

The drawback is that is not the official release, thus getting updates is going to be a problem. Hopefully they will merge them soon.

Hope it works for you, let me know if you have any questions.
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Nuget for local teams]]></title>
    <link href="http://orthocoders.com/blog/2011/03/26/nuget-for-local-teams/"/>
    <updated>2011-03-26T00:00:00-05:00</updated>
    <id>http://orthocoders.com/blog/2011/03/26/nuget-for-local-teams</id>
    <content type="html"><![CDATA[Two weeks ago I started migrating all my .NET projects to <a title="Nuget package management" href="http://nuget.org" target="_blank">Nuget</a>, you can read more about it in my <a title="Nuget Gotcha" href="http://orthocoders.com/2011/03/13/nuget-gotcha-avoid-storing-packages-in-the-repository/" target="_blank">previous post</a>.

After I was done with my <a title="MT Projects @ github" href="https://github.com/amirci" target="_blank">OSS projects</a>, I decided to share the goodness with some of my clients and then came to realize a few issues with my &#8221;<em>stop storing dependencies in the repository</em>&#8221; crusade.

First, many of the dependencies can&#8217;t be published to the public nuget.org server. That means that we need to find a way to store them locally.

<strong>Solution</strong>: Install local nuget feed.
<h3>Why a local Nuget feed is a good idea</h3>
Having a local feed allows your company leverage all the benefits of package management internally.

Plus you can use it to cache common used packages in case you have issues downloading them.

How to do this you ask? Well, is not as straightforward as I hoped. Luckily I had the help of <a title="David Alpert" href="http://twitter.com/davidalpert" target="_blank">@davidalpert</a> to fight IIS configuration and <a title="Rob Reynolds on Twitter" href="http://twitter.com/ferventcoder" target="_blank">@ferventcoder</a> and <a title="David Fowler" href="http://twitter.com/davidfowl" target="_blank">@davidfawl</a> to answer all our questions.

After approximately 3 weeks of tinkering with the server, David managed to make it work. (Kudos, yay!)

Here are a few links to follow in order to install the server locally:
<ul>
	<li><a title="Hosting local and remote feeds" href="http://haacked.com/archive/2010/10/21/hosting-your-own-local-and-remote-nupack-feeds.aspx" target="_blank">Hosting your own local and remote feed by Phil Haack</a></li>
	<li><a title="404 on remote server" href="http://nuget.codeplex.com/discussions/246387" target="_blank">404 on remote server discussion on nuget site</a></li>
</ul>
Key points:
<ul>
	<li>URL should be <em>http://yourserver:port/dataservices/packages.svc</em></li>
	<li>Add the .nupkg as mime type with application/zip</li>
	<li>Remember that the new server is not an MVC application</li>
	<li>Be patient, very patient&#8230;</li>
</ul>
<h3>I got the server running, now what?</h3>
Well now we have to tackle a different problem. I found that some of the projects are using libraries that are not yet published to the public feed.

Though I could package and publish them (I have done so with <a title="StructureMap automocking package" href="http://nuget.org/List/Packages/structuremap.automocking" target="_blank">Structuremap.Automocking</a> and others), some of them are a bit out of date and others are the result of downloading the source, modifying it and compiling it locally.

Either case, I thought that I&#8217;d like an easy way of packaging and publishing these packages to the local feed in order to keep using them.

Doing so is also a great solution if you don&#8217;t have the time to review if an upgrade would work, or is to risky to do it.

If you read my previous post you already know that I&#8217;m using <a title="Albacore on Github" href="https://github.com/derickbailey/Albacore" target="_blank">Albacore</a> to generate the nuspec file, build the package, etc.

My first thought was to use those tasks for each of the packages in need to create. And I started to do so.
<h3>Rake again and again</h3>
After creating a rakefile, copying the libs, etc for the third time,  my <em>laziness sense</em> (similar to spider sense without the <em>awesome</em> and the <em>great responsibility</em> thing) started to tingle indicating that should be a way of avoiding this repetitive task.
<ul>
	<li>Copy the assemblies to a lib folder</li>
	<li>Generate the nuspec with the name of the library and the version</li>
	<li>Compile the nuspec and create the package</li>
	<li>Copy the package to the destination to be served by the local feed</li>
</ul>
Instead of writing one rakefile per package, why not just add parameters to the rakefile so I can call it from command line specifying:
<ul>
	<li>Name of the package</li>
	<li>Version of the package</li>
	<li>Folder where to get all the assemblies</li>
</ul>
And voila! <a title="Gist with rakefile to generate nuget packages" href="https://gist.github.com/888798" target="_blank">Here</a> is the result, I hope you find it useful.

To use it, you will have to type something like this:
<blockquote>rake deploy:publish[AvalonDock, 1.0, &#8220;c:\project\lib\avalondock&#8221;]</blockquote>
Are you doing anything else cool with nuget? Please share!
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Nuget gotcha: Avoid storing packages in the repository]]></title>
    <link href="http://orthocoders.com/blog/2011/03/13/nuget-gotcha-avoid-storing-packages-in-the-repository/"/>
    <updated>2011-03-13T00:00:00-06:00</updated>
    <id>http://orthocoders.com/blog/2011/03/13/nuget-gotcha-avoid-storing-packages-in-the-repository</id>
    <content type="html"><![CDATA[It&#8217;s been a while since <a title="Nuget project to manage packages" href="http://nuget.org/" target="_blank">Nuget</a> project was released. Since the project birth I&#8217;ve been watching closely to see when would be a good opportunity to start using it for my projects and recommend using it for my clients.

Basically, the Nuget project solves dependency management for all your .NET projects. That means that you don&#8217;t need to search any more for libraries that you need to use like NHibernate or nUnit and just install them from a centralized server.
<h2>The path to Nuget</h2>
So far I&#8217;ve been using <a title="Rake - ruby make" href="http://rake.rubyforge.org/" target="_blank">Rake</a> for all my builds and I&#8217;m super happy with it. Using a DSL specifically designed for building projects is a great advantage, Ruby gives you lots of flexibility and the <a title="Albacore gem for building .net projects" href="https://github.com/derickbailey/Albacore" target="_blank">Albacore</a> gem is the cherry on top.

One of the many things that I like about the <a title="Ruby installer for windows" href="http://rubyinstaller.org/" target="_blank">Ruby</a> world is <a title="Rubygems project" href="http://rubygems.org/" target="_blank">gem</a> + <a title="Bundler dependency management" href="http://gembundler.com/" target="_blank">bundler</a> combination. For .NET projects I&#8217;ve been using also <a title="Noodle uses bundler to pull dependencies" href="https://github.com/spraints/noodle" target="_blank">noodle</a> to copy the dependencies to my local folder (usually called <em>lib</em>).

However not everything is ponies and rainbows:
<ul>
	<li>Ruby based solutions are not always well received in .NET project (no matter how good they are)</li>
	<li>Not many developers publish their libraries / frameworks</li>
	<li>Creating gems with .NET assemblies is discouraged since Nuget was born</li>
</ul>
All this reasons plus the fact that the .NET community was embracing the idea of package management using Nuget make me consider it as a great option.

However one thing was keeping me from doing the change, and that is the <strong>ability of reading a configuration file and use it to download all dependencies</strong> (very similar to what <a title="Manage dependencies" href="http://gembundler.com/" target="_blank">Bundler</a> does).

And that was it&#8230;. Until a couple of days ago&#8230;.
<h2><strong>Nuget Adoption</strong></h2>
Last week I say a tweet by <a title="David Ebbo Twitter" href="http://twitter.com/davidebbo/status/46031701809430529" target="_blank">@davidebbo</a> saying that Nuget supports now reading from a config file!

Why is that so important? Because I don&#8217;t want to store my dependencies in the repository any more!

The assemblies that we use in a project usually don&#8217;t change until we update a newer version. What&#8217;s the point of storing them with our code if we can use just a reference to them and download them at our leisure?

It takes way less space to store our repositories and updating the packages quite easier because you just change the references and the configuration file, and that&#8217;s it, everyone gets them.

Also imagine sharing in your company all the internal assemblies by publishing them to a local Nuget server instead of having a share drive or similar.  Update the version whenever you want! No more versioning dependencies nightmares! And everything is treated the same way, they are all packages!

So I installed latest version of Nuget (following the <a title="Using Nuget with configuration files" href="http://bit.ly/g2ploU" target="_blank">link</a> above) and started the conversion:
<h3>Step 1: Changing the References</h3>
Open your .sln file, remove all your references and add them again by doing <em>right click + Add Package Reference</em>. That would accomplish the following:
<ul>
	<li>Find the reference in the package server</li>
	<li>Install it to a local package folder (usually called Packages)</li>
	<li>Write a config file with the dependency installed (in the same folder as the project)</li>
</ul>
<h3>Step 2: Modify the Rakefile</h3>
I need dependencies in order to build, so I need to make sure that before building all my dependencies are satisfied, to do so I modified the task <em>setup:dep</em> to do the following:

[sourcecode language=&#8221;ruby&#8221;]
namespace :setup do
	desc &quot;Setup dependencies for nuget packages&quot;
	task :dep do
		FileList[&quot;**/packages.config&quot;].each do |file|
			sh &quot;nuget install #{file} /OutputDirectory Packages&quot;
		end
	end
end
[/sourcecode]

And I need to make sure this happens every time before building, so I need a dependency in the build task (remember that I&#8217;m using <a title="Albacore gem for .NET projects" href="http://albacorebuild.net/" target="_blank">Albacore</a> for the msbuild tasks).

[sourcecode language=&#8221;ruby&#8221;]
	desc &quot;Build the project&quot;
	msbuild :all, [:config] =&gt; [:setup] do |msb, args|
		msb.properties :configuration =&gt; args[:config] || : Debug
		msb.targets :Build
		msb.solution = solution_file
	end
[/sourcecode]
<h3>Step 3: Enjoy!</h3>
That&#8217;s it! Super easy! If you want to check the code please go to <a title="Source for MT Testing" href="https://github.com/amirci/mt_testing" target="_blank">github</a> and download it.
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Testing with random values: is it really dangerous?]]></title>
    <link href="http://orthocoders.com/blog/2011/03/06/testing-with-random-values-is-it-really-dangerous/"/>
    <updated>2011-03-06T00:00:00-06:00</updated>
    <id>http://orthocoders.com/blog/2011/03/06/testing-with-random-values-is-it-really-dangerous</id>
    <content type="html"><![CDATA[Last Saturday I presented a session about automation at the Winnipeg Code Camp.

I&#8217;ve been doing presentations a the WPG CC for the past three years, and is always a blast! Great sessions, lots of networking and great food is an awesome combination!

After my session, some of the attendes approached me and started to talk about CI, their gotchas about testing and woes :).

One of them mentioned that he wasn&#8217;t sure about the way they were using &#8220;hardcoded&#8221; values with the tests. He felt that probably should be a better way of defining valid inputs that could avoid the &#8220;smell&#8221;.

My suggestions was to consider using auto generated values. Random values are a great tool to avoid hardcoding inputs. Using &#8220;factories&#8221; to create valid test values helps us to make sure we have better coverage of the domain of valid inputs for our tests.
<h2>How do I know what input is valid?</h2>
You may wonder &#8220;But, if the values are random, the test may pass once and then fail at runtime, that&#8217;s really, really, dangerous!!!&#8221;.

The answer is <strong>No</strong>, not at all. The key is to identify the domain that makes your test pass and use the random generation tools to get values that are part of that domain. How to do that? Keep reading &#8230;

When you write a unit test you may have more than one scenario. For each scenario you need to find a set of inputs that make it pass.

For example, let&#8217;s use a method that verifies if a string is a <em>palindrome</em>. Definition of <em>palindrome</em> in wikipedia:
<blockquote>A <strong>palindrome</strong> is a word, phrase, <a title="Palindromic number" href="http://en.wikipedia.org/wiki/Palindromic_number">number</a> or other sequence of units that can be read the same way in either direction</blockquote>
Our method may look something like this in C#:

[sourcecode language=&#8221;csharp&#8221;]
bool IsPalindrome(string word)
[/sourcecode]

So now, what should we do? Write one test that takes random strings as input, run it once and if we are lucky and passes then we are done? Woah, slow down your horses&#8230;.. take a deep breath&#8230; maybe two&#8230;.
<h2>Preconditions, postconditions and domains</h2>
The <em>precondition</em> of the method is the set of values that are valid in order to call the method. Valid means that we don&#8217;t get an exception when we use it, no matter what the result of the method is.

So, what are the values that are valid to use for <em>IsPalindrome</em>? It seems to me that any string should work, except <em>null</em>, therefore:
<ul>
	<li>Precondition: Any <strong>not</strong> <em>null</em> <em>string</em> instance.</li>
</ul>
Great! Now let&#8217;s think about the <em>postcondition</em> and discover our scenarios. The <em>postcondition</em> defines what are the expected results and under what conditions are calculated.

Following our definition of what the method does, we can have two possible outputs:
<ul>
	<li><em>True: </em>if the input is <em>palindrome </em></li>
	<li><em>False</em>: if the input is <strong>not</strong> <em>palindrome</em></li>
</ul>
Thus, we have two scenarios:
<ul>
	<li>When the word is palindrome it should return true</li>
	<li>When the word is not palindrome it should return false</li>
</ul>
<h2>Writing the test</h2>
We need to test two scenarios and the best way of doing that is to write one test per scenario.

The first test should check the first part of the <em>postcondition</em>, I want to get <em>true </em>as result, and to do that the domain I need to use would be all the words that actually are <em>palindrome</em>. Let&#8217;s write the scenario:
<blockquote><strong>Given</strong> I have a <em>palindrome</em> phrase

<strong>When</strong> I check <em>IsPalindrome</em>

<strong>Then</strong> I should get <em>true</em></blockquote>
I like to use the <a title="Using Given-When-Then (GWT) syntax" href="https://github.com/amirci/mt_testing/wiki/Given-When-Then">Given-When-Then</a> syntax, it&#8217;s very descriptive. I&#8217;m using the <a title="Maventhought Testing Framework" href="https://github.com/amirci/mt_testing">MT Testing</a> library that enforces GWT. Here is the scenario using C# and just one example:

[sourcecode language=&#8221;csharp&#8221;]
protected override void GivenThat()
{
    this._phrase = &quot;Madam Im adam&quot;;
}

protected override void WhenIRun()
{
   this.Actual = PalindromeChecker.IsPalindrome(this._phrase);
}

[It]
public void Should_validate_the_phrase_is_palindrome()
{
    this.Actual.Should().Be.True();
}
[/sourcecode]

The test looks good, a bit of TDD and all green. Don&#8217;t worry about the implementation, you can <a title="MT Testing library with the example" href="https://github.com/amirci/mt_testing">download</a> all the source and check it out at the later ;).
<h2>Using Factories</h2>
I&#8217;d like to make sure that for any <em>palindrome</em> phrase (that&#8217;s the domain we got from the pre and post condition) the test passes, no just for one example.

However, though generating all the <em>palindrome </em>words is a bit ambitious, we could settle for generating a collection of phrases that are <em>palindrome</em> and use that as input.

<a title="MbUnit V3" href="http://gallio.org/">MbUnit</a> provides an attribute named &#8220;Factory&#8221; that allows a <em>static method</em> to define a collection of values to be passed to the test, let&#8217;s look at the code:

[sourcecode language=&#8221;csharp&#8221;]
        private readonly string _phrase;

        [Factory(&quot;PalindromeFactory&quot;)]
        public When_palindrome_checker_checks_a_palindrome_phrase(string phrase)
        {
            _phrase = phrase;
        }

        protected override void WhenIRun()
        {
            this.Actual = PalindromeChecker.IsPalindrome(this._phrase);
        }

        [It]
        public void Should_check_the_word_as_palindrome()
        {
            this.Actual.Should().Be.True();
        }

        protected static IEnumerable&lt;string&gt; PalindromeFactory()
        {
            yield return &quot;Madam I&#8217;m adam&quot;;
            yield return &quot;Draw pupil&#8217;s lip upward&quot;;
            yield return &#8230;.
        }
[/sourcecode]

Using the attribute, we indicate the runner that the test should be run for every value in the collection.

We run the test, and we can see in the result window something like:

[sourcecode language=&#8221;txt&#8221;]
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Madam I&#39;m adam&quot;): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Draw pupil&#39;s lip upward&quot;): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Gateman sees name, garageman sees name tag&quot;): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Go hang a salami; I&#39;m a lasagna hog&quot;): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;I roamed under it as a tired, nude Maori&quot;): passed ###
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Live not on evil&quot;): passed ###
[/sourcecode]
<h2>Using random strings</h2>
One case covered, one to go.

The second test should verify the second part of the <em>postcondition</em>. I want to get <em>false</em> as result, so the domain I need to use is all the words that are <em>not palindrome</em>. Let&#8217;s write the scenario:
<blockquote><strong>Given</strong> I don&#8217;t have palindrome phrase

<strong>When</strong> I check IsPalindrome

<strong>Then</strong> I should get false</blockquote>
And the code:

[sourcecode language=&#8221;csharp&#8221;]
        private string _phrase;

        protected override void GivenThat()
        {
            this._phrase = &quot;This is not palindrome&quot;;
        }

        protected override void WhenIRun()
        {
            this.Actual = PalindromeChecker.IsPalindrome(this._phrase);
        }

        [It]
        public void Should_not_validate_the_phrase_as_palindrome()
        {
            this.Actual.Should().Be.False();
        }
[/sourcecode]

The code works fine. However we have a similar situation as before, I&#8217;d like to have more values that belong to the domain that makes the method fail, that means any phrase that is <em>not palindrome</em>.

Factories are a good idea when we have a set of values that we want to use. In this case I don&#8217;t want to hardcode <em>non palindrome</em> phrases. I would prefer to have a way of creating those phrases without needing to enumerate all the examples.

Luckily MbUnit has another attribute that we can use to generate random strings. It&#8217;s called <em>RandomStrings</em> and it takes a regular expression to describe the string. Adding the attribute the code looks like this:

[sourcecode language=&#8221;csharp&#8221;]
        private readonly string _phrase;

        public When_palindrome_checker_checks_a_non_palindrome_phrase(
            [RandomStrings(Count=10, Pattern=@&quot;Weird [A-Z]{5,8} [0-9]{2}&quot;)]string phrase)
        {
            _phrase = phrase;
        }

        protected override void WhenIRun()
        {
            this.Actual = PalindromeChecker.IsPalindrome(this._phrase);
        }

        [It]
        public void Should_not_validate_the_phrase_as_palindrome()
        {
            this.Actual.Should().Be.False();
        }

[/sourcecode]

I&#8217;m using a regular expression that <em>uses </em>numbers at the end to make sure the phrase is not <em>palindrome</em>.

We run the tests, and here is the output:

[sourcecode language=&#8221;txt&#8221;]
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird VGSKTTZ 64&quot;): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird VLMEWIJ 59&quot;): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird NDICJK 08&quot;): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird FEMBMSKK 88&quot;): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird IHOIOWN 38&quot;): passed ###
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird ITIRCHAA 63&quot;): passed ###
[/sourcecode]
<h2>The moral of the story</h2>
Random values are a powerful tool, not dangerous per se. They are part of our toolbox as developers. Can we use it wrong? Sure, but that&#8217;s a completely different story &#8230;.

If you want to get the full code, download it from the examples in <a title="MavenThought Testing Framework" href="https://github.com/amirci/mt_testing">MT Testing</a>. Check the <em>Palindrome</em> folder.

Do you have any other stories or comments about random values that you would like to share, please leave a comment, feedback is more than welcome.

Want to see an example with major complexity? Something that fits better your case? Tell me about it and I&#8217;ll add it to the MT Testing framework as an example of usage (and I&#8217;ll give you credit for it too!).
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[MVC virtual conference #2]]></title>
    <link href="http://orthocoders.com/blog/2011/02/20/mvc-virtual-conference-2/"/>
    <updated>2011-02-20T00:00:00-06:00</updated>
    <id>http://orthocoders.com/blog/2011/02/20/mvc-virtual-conference-2</id>
    <content type="html"><![CDATA[On Feb 8th I participated on the MVC Conf #2. It was a great experience, though is still a bit weird not to see the crowd :-).

My session was about &#8220;Quality driven acceptance tests using Capybara&#8221; and it was a bit of a shock because many .NET developers weren&#8217;t expecting Ruby as a tool and many got confused and thought I was using Ruby on Rails&#8230; but I guess that&#8217;s material for another post.

Overall I really enjoyed presenting and I hope  to do it again next time.

You can download the slides and source code from <a title="MVC Conf #2 Slides and Source" href="http://orthocoders.com/presentations" target="_blank">presentations</a>. I just updated the README file with some troubleshooting.

If you have any issues running the code, or with the setup let me know.
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Presentation at Codemash]]></title>
    <link href="http://orthocoders.com/blog/2011/01/13/presentation-at-codemash/"/>
    <updated>2011-01-13T00:00:00-06:00</updated>
    <id>http://orthocoders.com/blog/2011/01/13/presentation-at-codemash</id>
    <content type="html"><![CDATA[Wow, first day of CodeMash and so far it&#8217;s being great! It&#8217;s really an awesome conference!

Yesterday at the precompiler, I went to the &#8221; Getting Published in an Evolving Industry:
How to Survive and Even Thrive&#8221; with Jason Gilmore (@wjgilmore) and learnt a lot about writing books and how to publish, I&#8217;m really tempted to write an ebook!

Then in the afternoon I went to the &#8220;Git Immersion&#8221; session and was pretty interesting, is a tough call because for every session I go there is another four I can&#8217;t &#8230;

Today I&#8217;m going to do my presentation about IronRuby. I uploaded the slides and code to the <a title="Presentations page" href="http://orthocoders.com/presentations" target="_blank">presentation</a> page, please feel free to download it and check it out before the conference.

In order to run ir u need to:
* Install Iron Ruby from <a title="Iron Ruby at Codeplex" href="http://ironruby.codeplex.com/" target="_blank">http://ironruby.codeplex.com/</a>

* Remember to put it in the path

* Install rake: igem install rake

* Install bundler: igem install bundler

* Check the tasks: rake -T

* Setup dependencies: rake setup

* Build: rake

* Run the tests: rake test

That&#8217;s it! Please contact me at @abarylko or amir@barylko.com if you have any issues.

Hope to see you at the session! Say hi if you are at codemash!

Now, in the afternoon, which session to go&#8230;. which session to go&#8230;..
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Microsoft Techdays 2010]]></title>
    <link href="http://orthocoders.com/blog/2010/12/07/microsoft-techdays-2010/"/>
    <updated>2010-12-07T00:00:00-06:00</updated>
    <id>http://orthocoders.com/blog/2010/12/07/microsoft-techdays-2010</id>
    <content type="html"><![CDATA[Wow! First day of Techdays is gone and I&#8217;ve done both of my presentations:
<ul>
	<li>Test Driven Development Patterns</li>
	<li>Top 10 mistakes in unit testing</li>
</ul>
The attendance was pretty good and all the attendees were great! Thank you everyone, I had a great time!

I&#8217;ve uploaded to <a title="Presentation material for TechDays" href="http://orthocoders.com/presentations" target="_blank">presentations</a> the slides and a link to the source. Both presentations using the same code.

Please follow each commit that mimics the steps I did in the presentation.

If u want to run the code please do the following:
<ul>
	<li>Download the code</li>
	<li>Install ruby (if u don&#8217;t have it)</li>
	<li>Install rake: gem install rake</li>
	<li>Install bundler: gem install bundler</li>
	<li>Then do setup: rake setup</li>
	<li>Run the test to make sure: rake tests</li>
</ul>
Please let me know if you have any issues or questions.
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Protegra SDEC 2010]]></title>
    <link href="http://orthocoders.com/blog/2010/10/13/protegra-sdec-2010/"/>
    <updated>2010-10-13T00:00:00-05:00</updated>
    <id>http://orthocoders.com/blog/2010/10/13/protegra-sdec-2010</id>
    <content type="html"><![CDATA[I&#8217;m really excited about participating tomorrow of <a href="http://www.sdec10.com">Protegra SDEC 2010</a>!

I&#8217;ll be doing two presentations, check the schedule!

As usual all the presentation will be uploaded to the <a href="http://orthocoders.com/presentations">presentations</a> page.

Any comments or questions feel free to contact me!
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[BDD presentation at Calgary .NET User Group]]></title>
    <link href="http://orthocoders.com/blog/2010/09/29/bdd-presentation-at-calgary-net-user-group/"/>
    <updated>2010-09-29T00:00:00-05:00</updated>
    <id>http://orthocoders.com/blog/2010/09/29/bdd-presentation-at-calgary-net-user-group</id>
    <content type="html"><![CDATA[This week I&#8217;m doing Udi Dahan&#8217;s training in SOA in Calgary and I thought that would be a good opportunity to do a presentation in the local .NET user group.

So I talked to the organizers (many thanks to Blake and David!) and tonight at 5:00 PM I’ll be doing a presentation to the Calgary .NET user group about behaviour driven development.

We are going to see how to implement BDD with little effort but with huge gains for our day to day work. I&#8217;m going to do an introduction to the subject and then we&#8217;ll  do a demo together step by step.

As usual I&#8217;ll upload the link to the code and the presentation to the <a title="Presentations" href="http://orthocoders.com/presentations">presentations</a> section in the blog.

Hope to see u there!
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Iron Ruby presentation at Dot Net User Group]]></title>
    <link href="http://orthocoders.com/blog/2010/09/21/iron-ruby-presentation-at-dot-net-user-group/"/>
    <updated>2010-09-21T00:00:00-05:00</updated>
    <id>http://orthocoders.com/blog/2010/09/21/iron-ruby-presentation-at-dot-net-user-group</id>
    <content type="html"><![CDATA[Tonight at 6:00 PM I&#8217;ll be presenting a demo showing how to use Iron Ruby with .NET.
Ruby is an awesome language that has lots of frameworks and tools that can be used to improve our day to day development.
I uploaded the link to the code and the presentation to the <a title="Presentations" href="http://orthocoders.com/presentations">presentations</a> section in the blog.

See u there!
]]></content>
  </entry>
  
</feed>
