<?xml version="1.0" encoding="UTF-8"?>
<rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>ORTHOcoders &#187; Development</title>
	<atom:link href="http://orthocoders.com/category/development/feed/" rel="self" type="application/rss+xml" />
	<link>http://orthocoders.com</link>
	<description>U can code it, we can help</description>
	<lastBuildDate>Fri, 13 Jan 2012 07:16:10 +0000</lastBuildDate>
	<language>en</language>
	<sy:updatePeriod>hourly</sy:updatePeriod>
	<sy:updateFrequency>1</sy:updateFrequency>
	<generator>http://wordpress.org/?v=3.2.1</generator>
		<item>
		<title>WPF MVVM demystified</title>
		<link>http://orthocoders.com/2011/12/02/wpf-mvvm-demistified/</link>
		<comments>http://orthocoders.com/2011/12/02/wpf-mvvm-demistified/#comments</comments>
		<pubDate>Fri, 02 Dec 2011 22:13:37 +0000</pubDate>
		<dc:creator>Amir Barylko</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Patterns]]></category>
		<category><![CDATA[binding]]></category>
		<category><![CDATA[dotnet]]></category>
		<category><![CDATA[Presentation]]></category>
		<category><![CDATA[wpf]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=499</guid>
		<description><![CDATA[Why using MVVM as a presentation pattern is a good idea? What does that mean? What is the difference with MVP or MVC?]]></description>
			<content:encoded><![CDATA[<h2>Motivation</h2>
<p>Lately I have been hearing a few discussion about using MVVM as a pattern to work with desktop apps when using .NET and WPF.</p>
<p>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.</p>
<p>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.</p>
<p><em>First</em> Highlight: WPF is not WinForms. Why? <strong>NO CODE BEHIND</strong>!</p>
<p>Second Highlight: What are the benefits of it? <strong>BINDING</strong>!</p>
<p><em>Third</em> Highlight: Is binding important when using WPF? <strong>ESSENTIAL</strong>!</p>
<p><em>Fourth</em> Highlight: What about generating the M &#8211; V &#8211; VM? <strong>NOT ENCOURAGED, BE CAREFUL</strong>!</p>
<h2>The good old days with no binding</h2>
<p>Before using WPF there was WinForms.</p>
<p>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.</p>
<p>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.</p>
<p>I remember clearly wondering about :</p>
<blockquote><p>&#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;</p></blockquote>
<p>So I decided to create my collection of <em>binders</em> to make my life easier and look what happened next&#8230;</p>
<h2>Binding as a first citizen</h2>
<p>The next iteration of MS desktop tools brought <strong>WPF </strong>and the idiomatic way of building views was using <strong>Binding</strong>! Yay!</p>
<p>Why is so good? Because the views use reflection to know when your source has changed!</p>
<p>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.</p>
<p>&#8220;Awesome!&#8221; &#8211; You say.</p>
<p>&#8220;Now I can just grab my models and add the notification, and no more controllers, and&#8230;&#8221; &#8211; STOP!</p>
<p>Wow, slow down&#8230;.. take a deep breath, sit down&#8230; keep reading.</p>
<h2>Modelling, abstraction and everything nice</h2>
<p>We have clear responsibilities assigned between view and model.</p>
<p><em>View</em> is in charge of displaying what the <em>Model</em> represents.</p>
<p>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?</p>
<p>And here is why the <em>ViewModel</em> makes so much sense.</p>
<p>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.</p>
<h2>No rule, to rule them all</h2>
<p>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>?</p>
<p>Even more, would that mean that all my &#8220;Models&#8221; are entities populated from an ORM?</p>
<p>Not at all! There&#8217;s no <em>rule</em>, just good design and modelling practices.</p>
<p>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.</p>
<p>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).</p>
<p>So be careful! Code generation in my experience will bring you more sorrow than happy days!</p>
<p>What classes are you going to generate anyways? How can you be sure before hand what all the models, etc, look like?</p>
<p>Forcing all the objects to inherit base classes because they are all &#8220;ViewModels&#8221; or &#8220;Models&#8221; may produce the same result.</p>
<p>There&#8217;s no magic bullet or pill you can take.</p>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://orthocoders.com/2011/12/02/wpf-mvvm-demistified/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Meet the Clojure programming language</title>
		<link>http://orthocoders.com/2011/10/14/meet-the-clojure-programming-language/</link>
		<comments>http://orthocoders.com/2011/10/14/meet-the-clojure-programming-language/#comments</comments>
		<pubDate>Fri, 14 Oct 2011 20:44:09 +0000</pubDate>
		<dc:creator>sgalkin</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Training]]></category>
		<category><![CDATA[clojure]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=420</guid>
		<description><![CDATA[Clojure is an awesome language with lots of good traits. Not only will improve your skills as developer but will give you more tools that would be really useful in your day to day job...]]></description>
			<content:encoded><![CDATA[<p><span style="color: #ffff99;">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.</span></p>
<p><span style="color: #ffff99;">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. </span></p>
<p><span style="color: #ffff99;">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. </span></p>
<p><span style="color: #ffff99;">I always enjoy to bounce ideas with him to help me realize how wrong I am.</span></p>
<p><span style="color: #ffff99;">Please read on, I am positive you are in for a treat!</span></p>
<h2>Introduction</h2>
<p>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.</p>
<p>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.</p>
<h2>What is Clojure</h2>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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 .</p>
<p>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.</p>
<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"><br />
<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" /><br />
</a></p>
<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> &#8211; <a href="http://www.indeed.com/jobs?q=Java">Java jobs</a> &#8211; <a href="http://www.indeed.com/jobs?q=Scala">Scala jobs</a> &#8211; <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>
<p>Instead of enumerating the primitives and syntax constructs of the language, lets look at some examples and go over the explanation in detail togeteher.</p>
<p>We will use a simple problem I just made up to showcase some of Clojure features. Here is the problem:</p>
<blockquote><p><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></p></blockquote>
<p>Simple, artificial and useless; but more than enough to illustrate the traits of the language. Read on&#8230; read on&#8230;.</p>
<p>First lets define a constant holding the path to the file:</p>
<pre class="brush: clojure; light: true; title: ; notranslate">
(def file-path &quot;words.txt&quot;)
</pre>
<p>What&#8217;s going on here:</p>
<ul>
<li>Clojure uses <em>Lisp</em> syntax: function calls begin with an opening parentheses, followed by the function name, followed by the<br />
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>
<p>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>.</p>
<p>Back to our problem, how do we read the file contents?</p>
<pre class="brush: clojure; title: ; notranslate">
(with-open [reader (clojure.java.io/reader file-path)]
  .....
  .....)
</pre>
<p>Lets peel this onion (fine, orange for you) from the inside out:</p>
<pre class="brush: clojure; light: true; title: ; notranslate">
(clojure.java.io/reader file-path)
</pre>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<pre class="brush: clojure; title: ; notranslate">
(with-open [reader ....(1)....]
  .......(2).....)
</pre>
<p><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.</p>
<p>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.</p>
<blockquote>
<h5>Short digression:</h5>
<p>We just saw new syntax, the square brackets. Square brackets are the syntax for literal vectors in Clojure. [0 29 "hi" "bye"] is a vector with 4 elements. Also, parentheses are not just the syntax for function calls, it&#8217;s also the syntax for<br />
lists, so (1 2 3 4) is a Clojure list. Lists and vectors differ in their complexity guarantees as you would expect.</p>
<p>What we see here, is that Clojure code is written using Clojure data structures!</p>
<p>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.</p>
<p>This is a property of all Lisp languages and has fantastic implications!</p></blockquote>
<p>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:</p>
<pre class="brush: clojure; title: ; notranslate">
(def process-lines
  (fn [path f]
    (with-open [reader (clojure.java.io/reader path)]
      (f (line-seq reader)))))
</pre>
<p>Lots of parenthesis, I know&#8230;</p>
<p>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.</p>
<p>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.</p>
<p>The result of the function will be the last expression evaluated in its body.</p>
<p>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<br />
what is the <code>f</code> argument?</p>
<p>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.</p>
<p>That function will take care of processing all lines in the file.</p>
<p>Do you see how we are reverting the usual flow here?</p>
<p>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.</p>
<p>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></p>
<pre class="brush: clojure; title: ; notranslate">
(def print-matching
  (fn [words]
    (prn ...)))
</pre>
<p><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<br />
blanks. In some traditional languages you would use the following scheme to obtain the matching words:</p>
<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>
<p>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.</p>
<p>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.</p>
<p>Instead, we could write:</p>
<pre class="brush: clojure; light: true; title: ; notranslate">
(filter length-10? words)
</pre>
<p>Simple, right? This line express exactly what we have in mind.</p>
<p>Let&#8217;s dive in:</p>
<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<br />
<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>
<p>Lets write <code>length-10?</code> now:</p>
<pre class="brush: clojure; title: ; notranslate">
(def length-10?
  (fn [word]
    (= 10 (count word))))
</pre>
<p>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).</p>
<p><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.</p>
<p>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</p>
<pre class="brush: clojure; title: ; notranslate">
(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)
</pre>
<p>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<br />
constant, exactly the same thing we are doing with the other argument <code>file-path</code>.</p>
<h2>Smelly, smelly, naughty, naughty!</h2>
<p>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.</p>
<p>We are going to generalize the function. Lets go top-down and write first how we would like to use it:</p>
<pre class="brush: clojure; light: true; title: ; notranslate">
(filter (length-matcher 10) words)
</pre>
<p>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.</p>
<p>If you never saw something like this in other languages, your head may be spinning right now.<br />
<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</p>
<pre class="brush: clojure; title: ; notranslate">
(def length-matcher
  (fn  [n]
    (fn [word]
      (= n (count word)))))
</pre>
<p>Wow, there is a lot of <em>functioning</em> there, we are writting functional code after all.</p>
<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<br />
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>
<p>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<br />
return true if that word has length n. Phew&#8230;. I need some water&#8230; feel free and get some too&#8230;.</p>
<p>Little test to make sure you are following so far:</p>
<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>
<p>Solutions:</p>
<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>
<p>OK, now you understand how our new code works and how easy is to change the length matched.</p>
<p>Here is the full program</p>
<pre class="brush: clojure; title: ; notranslate">
(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)
</pre>
<h2>What else do we get?</h2>
<p><strong>Short</strong>: Size is a great predictor for number of bugs. Short code has fewer bugs.</p>
<p><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.</p>
<p><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.</p>
<p><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.</p>
<p><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:</p>
<pre class="brush: clojure; title: ; notranslate">
(defn length-matcher [n]
  (fn [word]
    (&lt; (count word) 10)))
</pre>
<p><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.<br />
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?</p>
<p>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.</p>
<p>The key here is that <strong>our code is not too naive!</strong>. Clojure will do it for you:</p>
<pre class="brush: clojure; title: ; notranslate">
(take 50
      (filter (length-matcher 10) (read-lines file-path)))
</pre>
<p>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).</p>
<p>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.</p>
<p>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.</p>
<h2>Homework</h2>
<p>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>:</p>
<ul>
<li><code>print-matching</code> has the double responsibility of filtering and<br />
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<br />
iterate the result words and print each one individually.</li>
</ul>
<h2>Conclusion</h2>
<p>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.</p>
<p>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.</p>
<p>See you there!</p>
]]></content:encoded>
			<wfw:commentRss>http://orthocoders.com/2011/10/14/meet-the-clojure-programming-language/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>The Bowling Game Kata &#8211; First attempt</title>
		<link>http://orthocoders.com/2011/09/05/the-bowling-game-kata-first-attempt/</link>
		<comments>http://orthocoders.com/2011/09/05/the-bowling-game-kata-first-attempt/#comments</comments>
		<pubDate>Tue, 06 Sep 2011 05:55:41 +0000</pubDate>
		<dc:creator>Amir Barylko</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Kata]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Training]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=400</guid>
		<description><![CDATA[Katas are practice exercises to keep your skills sharp. The Bowling Kata lets you model the game and the rules.]]></description>
			<content:encoded><![CDATA[<p>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#.</p>
<p>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.</p>
<p>You can follow the commit comments to get an idea of the train of thought.</p>
<p>Or if u prefer, just keep reading <img src='http://orthocoders.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> </p>
<h2>The Methodology</h2>
<p>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.</p>
<p>Why is a good idea to start with an acceptance test?</p>
<p>When you know where you want to go, what you want to achieve, is easier to keep the focus.</p>
<p>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 &#8211; once the test is passing &#8211; do refactoring as you see fit.</p>
<p>In the solution you will find three projects:</p>
<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>
<p>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.</p>
<p>My first test was for the method <em>Roll(pins)</em>. And right there I had to assign responsibilities.</p>
<p>What should this method do? Do the &#8220;registration&#8221; only? Do the calculation as well? Is there any other class involved?</p>
<p>I decided on keep things simple and separate two clear responsibilities:</p>
<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>
<p>After the first approach I thought that would be nice to refactor again and explore other solutions:</p>
<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:encoded>
			<wfw:commentRss>http://orthocoders.com/2011/09/05/the-bowling-game-kata-first-attempt/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Nuget for local teams</title>
		<link>http://orthocoders.com/2011/03/26/nuget-for-local-teams/</link>
		<comments>http://orthocoders.com/2011/03/26/nuget-for-local-teams/#comments</comments>
		<pubDate>Sun, 27 Mar 2011 01:09:39 +0000</pubDate>
		<dc:creator>Amir Barylko</dc:creator>
				<category><![CDATA[Build Tools]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Management]]></category>
		<category><![CDATA[Rake]]></category>
		<category><![CDATA[Nuget]]></category>
		<category><![CDATA[Process]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=349</guid>
		<description><![CDATA[Two weeks ago I started migrating all my .NET projects to Nuget, you can read more about it in my previous post. After I was done with my OSS projects, I decided to share the goodness with some of my clients and then came to realize a few issues with my &#8220;stop storing dependencies in [...]]]></description>
			<content:encoded><![CDATA[<p>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>.</p>
<p>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 &#8220;<em>stop storing dependencies in the repository</em>&#8221; crusade.</p>
<p>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.</p>
<p><strong>Solution</strong>: Install local nuget feed.</p>
<h3>Why a local Nuget feed is a good idea</h3>
<p>Having a local feed allows your company leverage all the benefits of package management internally.</p>
<p>Plus you can use it to cache common used packages in case you have issues downloading them.</p>
<p>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.</p>
<p>After approximately 3 weeks of tinkering with the server, David managed to make it work. (Kudos, yay!)</p>
<p>Here are a few links to follow in order to install the server locally:</p>
<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>
<p>Key points:</p>
<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>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>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.</p>
<p>My first thought was to use those tasks for each of the packages in need to create. And I started to do so.</p>
<h3>Rake again and again</h3>
<p>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.</p>
<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>
<p>Instead of writing one rakefile per package, why not just add parameters to the rakefile so I can call it from command line specifying:</p>
<ul>
<li>Name of the package</li>
<li>Version of the package</li>
<li>Folder where to get all the assemblies</li>
</ul>
<p>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.</p>
<p>To use it, you will have to type something like this:</p>
<blockquote><p>rake deploy:publish[AvalonDock, 1.0, "c:\project\lib\avalondock"]</p></blockquote>
<p>Are you doing anything else cool with nuget? Please share!</p>
]]></content:encoded>
			<wfw:commentRss>http://orthocoders.com/2011/03/26/nuget-for-local-teams/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Nuget gotcha: Avoid storing packages in the repository</title>
		<link>http://orthocoders.com/2011/03/13/nuget-gotcha-avoid-storing-packages-in-the-repository/</link>
		<comments>http://orthocoders.com/2011/03/13/nuget-gotcha-avoid-storing-packages-in-the-repository/#comments</comments>
		<pubDate>Sun, 13 Mar 2011 18:26:10 +0000</pubDate>
		<dc:creator>Amir Barylko</dc:creator>
				<category><![CDATA[Build Tools]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Management]]></category>
		<category><![CDATA[Rake]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Albacore]]></category>
		<category><![CDATA[Automation]]></category>
		<category><![CDATA[Dependencies]]></category>
		<category><![CDATA[Deployment]]></category>
		<category><![CDATA[MSbuild]]></category>
		<category><![CDATA[Nuget]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=322</guid>
		<description><![CDATA[Usually when working a .NET project we store the dependencies (assemblies) in a folder that gets added to the version control system of choice (TFS, SVN, Git, HG, etc).
This practice brings quite a few headaches: version updates, repository size, sharing, etc....
For the Ruby world using gems and bundler show how to solve this issue. I've been using rake + gems + bundler for my .NET project waiting for Nuget project to provide more functionality for command line usage, now the wait is over..... ]]></description>
			<content:encoded><![CDATA[<p>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.</p>
<p>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.</p>
<h2>The path to Nuget</h2>
<p>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.</p>
<p>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>).</p>
<p>However not everything is ponies and rainbows:</p>
<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>
<p>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.</p>
<p>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).</p>
<p>And that was it&#8230;. Until a couple of days ago&#8230;.</p>
<h2><strong>Nuget Adoption</strong></h2>
<p>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!</p>
<p>Why is that so important? Because I don&#8217;t want to store my dependencies in the repository any more!</p>
<p>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?</p>
<p>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.</p>
<p>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!</p>
<p>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:</p>
<h3>Step 1: Changing the References</h3>
<p>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:</p>
<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>
<p>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:</p>
<pre class="brush: ruby; title: ; notranslate">
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
</pre>
<p>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).</p>
<pre class="brush: ruby; title: ; notranslate">
	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
</pre>
<h3>Step 3: Enjoy!</h3>
<p>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.</p>
]]></content:encoded>
			<wfw:commentRss>http://orthocoders.com/2011/03/13/nuget-gotcha-avoid-storing-packages-in-the-repository/feed/</wfw:commentRss>
		<slash:comments>2</slash:comments>
		</item>
		<item>
		<title>Testing with random values: is it really dangerous?</title>
		<link>http://orthocoders.com/2011/03/06/testing-with-random-values-is-it-really-dangerous/</link>
		<comments>http://orthocoders.com/2011/03/06/testing-with-random-values-is-it-really-dangerous/#comments</comments>
		<pubDate>Mon, 07 Mar 2011 04:37:34 +0000</pubDate>
		<dc:creator>Amir Barylko</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Unit Testing]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=254</guid>
		<description><![CDATA[Using random values can be a great tool when writing any kind of tests, however the word "random" sometimes scare developers and gives the idea that if we use unknown values how can we be sure the test is actually working? The key is to discover the tests scenarios, and the valid domain for each scenario...]]></description>
			<content:encoded><![CDATA[<p>Last Saturday I presented a session about automation at the Winnipeg Code Camp.</p>
<p>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!</p>
<p>After my session, some of the attendes approached me and started to talk about CI, their gotchas about testing and woes <img src='http://orthocoders.com/wp-includes/images/smilies/icon_smile.gif' alt=':)' class='wp-smiley' /> .</p>
<p>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;.</p>
<p>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.</p>
<h2>How do I know what input is valid?</h2>
<p>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;.</p>
<p>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;</p>
<p>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.</p>
<p>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:</p>
<blockquote><p>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</p></blockquote>
<p>Our method may look something like this in C#:</p>
<pre class="brush: csharp; title: ; notranslate">
bool IsPalindrome(string word)
</pre>
<p>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;.</p>
<h2>Preconditions, postconditions and domains</h2>
<p>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.</p>
<p>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:</p>
<ul>
<li>Precondition: Any <strong>not</strong> <em>null</em> <em>string</em> instance.</li>
</ul>
<p>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.</p>
<p>Following our definition of what the method does, we can have two possible outputs:</p>
<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>
<p>Thus, we have two scenarios:</p>
<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>
<p>We need to test two scenarios and the best way of doing that is to write one test per scenario.</p>
<p>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:</p>
<blockquote><p><strong>Given</strong> I have a <em>palindrome</em> phrase</p>
<p><strong>When</strong> I check <em>IsPalindrome</em></p>
<p><strong>Then</strong> I should get <em>true</em></p></blockquote>
<p>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:</p>
<pre class="brush: csharp; title: ; notranslate">
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();
}
</pre>
<p>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 <img src='http://orthocoders.com/wp-includes/images/smilies/icon_wink.gif' alt=';)' class='wp-smiley' /> .</p>
<h2>Using Factories</h2>
<p>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.</p>
<p>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.</p>
<p><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:</p>
<pre class="brush: csharp; title: ; notranslate">
        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'm adam&quot;;
            yield return &quot;Draw pupil's lip upward&quot;;
            yield return ....
        }
</pre>
<p>Using the attribute, we indicate the runner that the test should be run for every value in the collection.</p>
<p>We run the test, and we can see in the result window something like:</p>
<p>### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Madam I\&#8217;m adam&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Draw pupil\&#8217;s lip upward&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Gateman sees name, garageman sees name tag&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Go hang a salami; I\&#8217;m a lasagna hog&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;I roamed under it as a tired, nude Maori&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_palindrome_phrase(&quot;Live not on evil&quot;): passed ###</p>
<h2>Using random strings</h2>
<p>One case covered, one to go.</p>
<p>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:</p>
<blockquote><p><strong>Given</strong> I don&#8217;t have palindrome phrase</p>
<p><strong>When</strong> I check IsPalindrome</p>
<p><strong>Then</strong> I should get false</p></blockquote>
<p>And the code:</p>
<pre class="brush: csharp; title: ; notranslate">
        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();
        }
</pre>
<p>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>.</p>
<p>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.</p>
<p>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:</p>
<pre class="brush: csharp; title: ; notranslate">
        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();
        }
</pre>
<p>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>.</p>
<p>We run the tests, and here is the output:</p>
<p>### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird VGSKTTZ 64&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird VLMEWIJ 59&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird NDICJK 08&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird FEMBMSKK 88&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird IHOIOWN 38&quot;): passed ###<br />
### Step When_palindrome_checker_checks_a_non_palindrome_phrase(&quot;Weird ITIRCHAA 63&quot;): passed ###</p>
<h2>The moral of the story</h2>
<p>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;.</p>
<p>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.</p>
<p>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.</p>
<p>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!).</p>
]]></content:encoded>
			<wfw:commentRss>http://orthocoders.com/2011/03/06/testing-with-random-values-is-it-really-dangerous/feed/</wfw:commentRss>
		<slash:comments>3</slash:comments>
		</item>
		<item>
		<title>MVC virtual conference #2</title>
		<link>http://orthocoders.com/2011/02/20/mvc-virtual-conference-2/</link>
		<comments>http://orthocoders.com/2011/02/20/mvc-virtual-conference-2/#comments</comments>
		<pubDate>Sun, 20 Feb 2011 20:50:56 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Rake]]></category>
		<category><![CDATA[Ruby]]></category>
		<category><![CDATA[Capybara]]></category>
		<category><![CDATA[MVC]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=247</guid>
		<description><![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 [...]]]></description>
			<content:encoded><![CDATA[<p>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 <img src='http://orthocoders.com/wp-includes/images/smilies/icon_smile.gif' alt=':-)' class='wp-smiley' /> .</p>
<p>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.</p>
<p>Overall I really enjoyed presenting and I hope  to do it again next time.</p>
<p>You can download the slides and source code from <a title="MVC Conf #2 Slides and Source" href="/presentations" target="_blank">presentations</a>. I just updated the README file with some troubleshooting.</p>
<p>If you have any issues running the code, or with the setup let me know.</p>
]]></content:encoded>
			<wfw:commentRss>http://orthocoders.com/2011/02/20/mvc-virtual-conference-2/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Protegra SDEC 2010</title>
		<link>http://orthocoders.com/2010/10/13/protegra-sdec-2010/</link>
		<comments>http://orthocoders.com/2010/10/13/protegra-sdec-2010/#comments</comments>
		<pubDate>Wed, 13 Oct 2010 07:38:07 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Uncategorized]]></category>
		<category><![CDATA[TDD]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=220</guid>
		<description><![CDATA[I&#8217;m really excited about participating tomorrow of Protegra SDEC 2010! I&#8217;ll be doing two presentations, check the schedule! As usual all the presentation will be uploaded to the presentations page. Any comments or questions feel free to contact me!]]></description>
			<content:encoded><![CDATA[<p>I&#8217;m really excited about participating tomorrow of <a href="http://www.sdec10.com">Protegra SDEC 2010</a>!</p>
<p>I&#8217;ll be doing two presentations, check the schedule!</p>
<p>As usual all the presentation will be uploaded to the <a href="/presentations">presentations</a> page.</p>
<p>Any comments or questions feel free to contact me!</p>
]]></content:encoded>
			<wfw:commentRss>http://orthocoders.com/2010/10/13/protegra-sdec-2010/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>Iron Ruby presentation at Dot Net User Group</title>
		<link>http://orthocoders.com/2010/09/21/iron-ruby-presentation-at-dot-net-user-group/</link>
		<comments>http://orthocoders.com/2010/09/21/iron-ruby-presentation-at-dot-net-user-group/#comments</comments>
		<pubDate>Tue, 21 Sep 2010 20:28:48 +0000</pubDate>
		<dc:creator>Amir Barylko</dc:creator>
				<category><![CDATA[Development]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[Ruby]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=207</guid>
		<description><![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 presentations section in [...]]]></description>
			<content:encoded><![CDATA[<p>Tonight at 6:00 PM I&#8217;ll be presenting a demo showing how to use Iron Ruby with .NET.<br />
Ruby is an awesome language that has lots of frameworks and tools that can be used to improve our day to day development.<br />
I uploaded the link to the code and the presentation to the <a title="Presentations" href="/presentations">presentations</a> section in the blog.</p>
<p>See u there!</p>
]]></content:encoded>
			<wfw:commentRss>http://orthocoders.com/2010/09/21/iron-ruby-presentation-at-dot-net-user-group/feed/</wfw:commentRss>
		<slash:comments>0</slash:comments>
		</item>
		<item>
		<title>ASP.NET MVC CONF 2010</title>
		<link>http://orthocoders.com/2010/07/22/asp-net-mvc-conf-2010/</link>
		<comments>http://orthocoders.com/2010/07/22/asp-net-mvc-conf-2010/#comments</comments>
		<pubDate>Thu, 22 Jul 2010 20:14:00 +0000</pubDate>
		<dc:creator>admin</dc:creator>
				<category><![CDATA[BDD]]></category>
		<category><![CDATA[Development]]></category>
		<category><![CDATA[Presentations]]></category>
		<category><![CDATA[TDD]]></category>
		<category><![CDATA[Training]]></category>

		<guid isPermaLink="false">http://orthocoders.com/?p=194</guid>
		<description><![CDATA[Just finished my presentation about BDD for the ASP.NET MVC virtual conference! It was fun to have a virtual audience. I uploaded the code and slides to the presentations page. Any feedback would be appreciated! Feel free to ask any questions. Enjoy!]]></description>
			<content:encoded><![CDATA[<p>Just finished my presentation about BDD for the ASP.NET MVC virtual conference!</p>
<p>It was fun to have a virtual audience.</p>
<p>I uploaded the code and slides to the <a title="Presentations page" href="wordpress/presentations">presentations</a> page.</p>
<p>Any feedback would be appreciated! Feel free to ask any questions.</p>
<p>Enjoy!</p>
]]></content:encoded>
			<wfw:commentRss>http://orthocoders.com/2010/07/22/asp-net-mvc-conf-2010/feed/</wfw:commentRss>
		<slash:comments>1</slash:comments>
		</item>
	</channel>
</rss>

