Sunday, August 24, 2014

Functional Programming All the Things OR How to Use Curry to Make Your Test More Readable

"I read in's looks"
-- Shakespeare, Henry VIII
Act I, Scene I, Line 125.2

We, the software craftsmen, understand that tests are a first class citizen.  If the system code was deleted it would be a great opportunity to rewrite the system and know once all the tests pass that the system has all the same functionality.  The question is should tests have the same style as the system code?

Say you have the Coin Changer kata and you want to use a function which takes both the coin value and the amount of change to be given.

If we wrote this in a C-style interface it look something like the following:

int[] changeFor(int[] coins, int amount)

While testing this we have a choice: we can either pass in the coins each time in the test thus violating the DRY principle or we could some how fill in the coins we want to use on each test in a testing series.  The second choice is very interesting since it is screaming for currying the coins per testing series.  Following this idea we have the following for the Coin Changer kata using AngularJS.



We have the following for the system code of the changeFor function.

    $scope.changeFor = function(coins, amount) {
      if (_.isEmpty(coins)) return [];

      return _.reduce(coins, function(m, coin) {
        m.change.push(Math.floor(m.amount / coin));
        m.amount %= coin;
        return m;
      }, {
        amount: amount,
        change: []
      }).change;
    };

We see that lodash's isEmpty makes sure that we have an array of coins before we go to the aggregation using the reduce function.  In the reduce we create an object with the current amount and change calculated so that we do not have to mutate the values passed in to the changeFor function.

We test the cases when we have no coins being passed in with the following code from appSpec.js.

describe('given no coins', function() {
var noCoinsFor;
beforeEach(function() {
noCoinsFor = _.curry($scope.changeFor)([]);
});
it('should return nothing for 0 cents', function() {
expect(noCoinsFor(0)).toEqual([]);
});
it('should return nothing for 99 cents', function() {
expect(noCoinsFor(99)).toEqual([]);
});
});

We set up changeFor function by currying with an empty array for the coins in the beforeEach in the top level describe.  Using curry in the beforeEach we do not have to pass in the empty array on each call in the its.  This makes the test a bit more readable.

Similarly when we test the penny series we can curry the penny.

describe('given pennies', function(){
var penniesFor;
beforeEach(function(){
penniesFor = _.curry($scope.changeFor)([1]);
});
it('should return nothing for 0 cents', function(){
expect(penniesFor(0)).toEqual([0]);
});
it('should return 1 penny for 1 cents', function(){
expect(penniesFor(1)).toEqual([1]);
});
it('should return 2 pennies for 2 cents', function(){
expect(penniesFor(2)).toEqual([2]);
});
});

This makes the grouping in the describe seem more logical and the test more readable.

The same with the nickel and penny.

describe('given nickels and pennies', function(){
var nickelsPenniesFor;
beforeEach(function(){
nickelsPenniesFor = _.curry($scope.changeFor)([5, 1]);
});
it('should return nothing for 0 cents', function(){
expect(nickelsPenniesFor(0)).toEqual([0, 0]);
});
it('should return 1 penny for 1 cents', function(){
expect(nickelsPenniesFor(1)).toEqual([0, 1]);
});
it('should return 1 nickel and 1 penny for 6 cents', function(){
expect(nickelsPenniesFor(6)).toEqual([1, 1]);
});
});

Finally our integration tests for US coins.

describe('given quarters, dimes, nickels, and pennies', function(){
var changeFor;
beforeEach(function(){
changeFor = _.curry($scope.changeFor)([25, 10, 5, 1]);
});
it('should return nothing for 0 cents', function(){
expect(changeFor(0)).toEqual([0, 0, 0, 0]);
});
it('should return 1 penny for 1 cents', function(){
expect(changeFor(1)).toEqual([0, 0, 0, 1]);
});
it('should return 3 quarters, 2 dimes, 0 nickels and 4 pennies for 99 cents', function(){
expect(changeFor(99)).toEqual([3, 2, 0, 4]);
});
});

By using the curry function we have added to the readability of the Jasmine tests.  This style is a bit different than the system code in the AngularJS application.

Check out the plunker which goes with this post.


Thursday, August 14, 2014

Continuous Learning - How to Get Your Knowledge Share On OR Notes from That Conference 2014 Open Space

"And have my learning from some true reports"
-- Shakespeare, Antony and Cleopatra
Act II, Scene II, Line 51

Here is a summary of my experience running an Open Space on Continuous Learning at my third That Conference

Ways to Share Knowledge at an Organization

  • Scheduled reports / presentation which are record 
    It is very important that they are scheduled as a recurrent event so that everyone will feel the need to take part in them.  It is also very important that they are recorded so that they can be used in on-boarding.
  • Tech Talks
    Part of being in IT is knowing about what is happening in technology.  Have your new people and interns talk about what they use to communicate with their friends, I bet they use things you have not even heard of.
  • Project Show and Tell
    Every project big or small has interesting challenges, share your solutions since they will more than likely be face again and again by others.
  • Tech and Try
    Have someone do a quick 5 to 10 minute talk on a topic and then have everyone do what was just talked about.  An example of this would be have someone present on a framework then have everyone do a code kata using that framework, you now have a bunch of people who have at least used that framework a little.

Ways to Learn More on Your Own

  • Code Kata
    Try doing the FizzBuzz kata in a bunch of different ways with a bunch of different frameworks and languages, then compare implementations.
  • Online Classes
    Pluralsight, Egghead.io, Codecademy, ... all have different ways to learn new things, find the one which works best for you.
  • User Groups
    I am a bit bias since I am a co-lead for an User Group, but there is more-likely-than-not a group of people that get together and talk about something you are interested in, join them.  If you cannot find any existing group, start one, all you need is a place to meet and other people.
  • Present at a Conference
    There is no better way to learn something than teaching others.  I know presenting and coding are two very different skill sets, but developing the ability to present and develop software will open all kinds of doors.

Saturday, July 26, 2014

Look Mom I'm FizzBuzzing in Chrome OR Intro to AngularJS

"Like captives bound to a triumphant car."
-- Shakespeare, Henry VI Part I
Act I, Scene I, Line 22

Tell me what you program in and I'll tell you how to FizzBuzz in it.

Not being an "UI guy" but wanting to become a Full Stack Developer the question came up, how do I do Code Katas using a more full stack approach?  How would I do FizzBuzz using AngularJS?

The great thing about AngularJS is that you can simply add it to whatever HTML you currently have meaning you can add it to your html tag, body, or even just a simple div.

Say you have some HTML like the following.


<html> <head> <link href="style.css" rel="stylesheet"></link> </head> <body> <h1> ng-fizzbuzz</h1> <div> <input /> <h1> FIZZBUZZ_RESULT</h1> </div> </body> </html>
You would like have an input box which will display the FizzBuzz value, thus given 3 in the input box will display Fizz and likewise 2 would give 2.  Let's add some simple JavaScript using AngularJS to FizzBuzz this.



Looking at this gist we see the following in the HTML:



We see we have three parts

  • ng-app => which Angular application are we going to use
  • ng-controller => which controller on the application are we going to use
  • ng-model => what data on the controller are we going to use
These parts align with the JavaScript code:


var app = angular.module('fizzbuzzApp', []);
 

names the application


app.controller('FizzBuzzCtrl', ['$scope',
function($scope) {
$scope.translate = function(value) {
var ret = "";
if (!value) return "";
if (value % 3 === 0) ret += "Fizz";
if (value % 5 === 0) ret += "Buzz";
return ret || value;
};
}
]);


defines the function for the controller

We do not see the value defined in the ng-model anywhere in the JavaScript code, so what gives?

{{translate(value)}}

calls the translate on the controller giving it the value of value bound in the ng-model on the input tag

This is one of the easier ways to do FizzBuzz with AngularJS.

This code is on Plunker: http://plnkr.co/edit/HMxS8H?p=info

Enjoy.

Saturday, July 5, 2014

I Have No Freaking Clue What I Am Doing... OR Saving Throws with Property Testing

"What majesty should be, what duty is,
Why day is day, night night, and time is time,
Were nothing but to waste night, day, and time.
Therefore, since brevity is the soul of wit,
"
-- Shakespeare, Hamlet
Act II, Scene II, Lines 87-90

I'll admit it, sometimes I have no freaking clue what I am doing.  Much like the internet dog meme, I feel completely out of my league.  You have to start somewhere and no clue is often the first stop on the journey to mastery.

"A journey of a thousand leagues started with what was under one footstep."
-- Tao Te Ching verse 64, translated by Jan J. L. Duyvendak

Property Testing allows one to run their code under test through it's paces.  Let us take a look at using Property Testing against FizzBuzz and see what we can learn.


We see that we have a fairly simple implementation of FizzBuzz.

public string Translate(int value)
{
var result = string.Empty;
if (value % 3 == 0) result += "Fizz";
if (value % 5 == 0) result += "Buzz";
return string.IsNullOrEmpty(result) ? value.ToString() : result;
}

For our first test case we use the Test Case property of NUnit to show what the results of the Translate on the FizzBuzzer would be for different inputs.  Note, I am showing the result here after many rounds of Red, Green, Refactor.  I cannot predict the future and as such I had two different test methods for 2 and 3 and ended up refactoring them to the "one" you see below, but I digress.

[TestCase(2, Result = "2")]
[TestCase(3, Result = "Fizz")]
[TestCase(5, Result = "Buzz")]
[TestCase(15, Result = "FizzBuzz")]
public string Given_Value_It_Must_Return_The_Given_Result(int value)
{
return _fizzBuzzer.Translate(value);
}

This is great, but what happens for other values?  How do we know if this really works?

[Test]
public void Given_A_Number_Not_Divisible_By_3_Or_5_It_Must_Return_That_Number()
{
var value =
from number in Any.OfType<int>()
where number%3 != 0 && number%5 != 0
select number;
Spec.For(value, v => _fizzBuzzer.Translate(v).Equals(v.ToString()))
.QuickCheckThrowOnFailure();
}

We use the Property Test above using fscheck to show that any number not divisible by 3 or 5 will return the ToString value of the number.  We do not have to check 15 since 3 * 5 =15 and therefore it is covered by the Fundamental Theory of Arithmetic.

private static Gen<int> DivisibleBy(int divisor)
{
var divisibleBy =
from number in Any.OfType<int>()
where number % divisor == 0
select number;
return divisibleBy;
}
[TestCase(3, "Fizz")]
[TestCase(5, "Buzz")]
[TestCase(15, "FizzBuzz")]
public void Given_A_Number_Divisible_By_Divisor_It_Must_Contain_Expected(
int divisor, string expected)
{
Spec.For(DivisibleBy(divisor), d => _fizzBuzzer.Translate(d).Contains(expected))
.QuickCheckThrowOnFailure();
}

Next we test that every number divisible by 3 contains the string "Fizz", likewise we do the same with 5 and "Buzz" and 15 with "FizzBuzz".  We check that they contain the string, so that if we get a value like 45, which is 3 * 15, for our divisible by 3 value we do not have a failing test because we got "FizzBuzz" back instead of just "Fizz", this is a very important thing to think about with Property Testing.  Note also, this is another case were refactoring played a big part in the final result.  I did not start off with a DivisibleBy function; no I found that the generate code for the 3 and 5 looked a lot a liked, so I combined them into the function you now see.

[Test]
public void Given_A_Number_It_Must_Return_Fizz_Buzz_FizzBuzz_Or_A_Number()
{
Spec.ForAny<int>(x => true)
.Classify(x => _fizzBuzzer.Translate(x).Equals("Fizz"), "Fizz")
.Classify(x => _fizzBuzzer.Translate(x).Equals("Buzz"), "Buzz")
.Classify(x => _fizzBuzzer.Translate(x).Equals("FizzBuzz"), "FizzBuzz")
.Classify(x => Regex.IsMatch(_fizzBuzzer.Translate(x), @"\d+"), "number")
.QuickCheckThrowOnFailure();
}

To show that the generator was in fact covering all four different possibilities I set up a "test" which was using fscheck's classification to show the break down of the different values which were coming out of Translate.

[Test]
public void Given_A_Number_Divisible_By_3_And_5_It_Must_Contain_Both_Fizz_And_Buzz()
{
Spec.For(DivisibleBy(3*5), d => string.IsNullOrEmpty(_fizzBuzzer.Translate(d)) == false)
.And(d => _fizzBuzzer.Translate(d).Contains("Fizz"))
.And(d => _fizzBuzzer.Translate(d).Contains("Buzz"))
.QuickCheckThrowOnFailure();
}

Last I set up a test case to show that if a value was divisible by both 3 and 5 it will contain both "Fizz" and "Buzz".  Now this test case was not needed since it was covered above, but I wanted to show how the And works.

There you have it FizzBuzz using Property Testing.  I found the examples in fscheck's GitHub repo very helpful.

Note, I used QuickCheckThrownOnFailure to cause the unit test to actually fail the test runner when the property is not true for some value.  This is very important to do if you are using something like NCrunch to run your tests.  If you have a property which fails for some value and do not use QuickCheckThrownOnFailure on your tests it will "pass" from the runner's point of view, but the result will give the value which falsifies it, this was not what I wanted so I had fscheck throw an exception when the property was falsified.

Sunday, June 29, 2014

Proving Traits

"A play there is, my lord, some ten words long,
Which is as ‘ brief ’ as I have known a play.
But by ten words, my lord, it is too long
"
-- Shakespeare, Midsummer Night's Dream

Martin Heidegger in his paper, The Origin of the Work of Art, gives us three different ways of defining thingness.

  1. bearer of traits and properties
  2. sense perceptions
  3. formed stuff

Traits is an interesting term in computer science, it is a collection of behaviors and their implementation which can be used to extend an object.  Most languages do not directly support the creation of stand-alone traits but traits are the essence of what makes up a programs value.

I am going to make a very bold statement here, I am going to say that BDD (Behavior Driven Development) is really about proving the traits of software.  Using the definition of traits given above we see that a trait is a collection of behaviors and how they have been implemented.  This sounds a lot like what we are proving out when we do BDD.

In BDD what are we doing?  We are proving that behavior X as it is implemented by code S does the following when given state G with stimulus W yielding state T.  In other words we are showing Given the following conditions, When we do the following against X in this Source code, Then the following result will occur.  This sounds a lot like proving the traits of the software to me.

"Words, words, words."
-- Shakespeare, Hamlet

Let us look at a example.


In the example above we see that a Starfleet Captain needs to be able to communicate with the FizzBuzzons and thus needs to have a translator.

She is given the following C# source code to preform the needed behavior of translating.

public string Translate(int value)
{
var result = string.Empty;
if (value % 3 == 0) result += "Fizz";
if (value % 5 == 0) result += "Buzz";
return string.IsNullOrEmpty(result) ? value.ToString() : result;
}

To prove to her that it works the engineers and communication specialist came up with the following specifications listing what happens in a Given state When the an input value is translated Then the value will have a certain output.

Scenario: 2 must translate to the string 2
Given a FizzBuzzer
And the value of '2'
When translate is invoked
Then the result should be '2'
Scenario: 3 must translate to the string Fizz
Given a FizzBuzzer
And the value of '3'
When translate is invoked
Then the result should be 'Fizz'
Scenario: 5 must translate to the string Buzz
Given a FizzBuzzer
And the value of '5'
When translate is invoked
Then the result should be 'Buzz'
Scenario: 15 must translate to the string FizzBuzz
Given a FizzBuzzer
And the value of '15'
When translate is invoked
Then the result should be 'FizzBuzz'

By testing around these specifications we can prove to our captain that the translator does hold the desired traits.

Does this slight different definition around BDD change anything?  No, but I hope it does widen the thought around it.

"If we shadows have offended
Think but this, and all is mended:
That you have but slumbered here
While these visions did appear.
"
-- Shakespeare, Midsummer Night's Dream