Last Tuesday I started a book club with my friends Samir Talwar and Pedro Moreira Santos (both of them working at Codurance). The book we've choseen is "The book of F#", because we want to learn F#.

After reading the first three chapters we decided to make the FizzBuzz kata to start practicing. In this article I'm going to explain you how we solved the kata trying to explain all the F# syntax we use. So, let's start!

First of all let's install NUnit as our testing framework. In future articles we are going to take a look to other testing frameworks and libraries, but right now NUnit is a good choice.

install-package NUnit

No F# magic, just NuGet.

Let's write our first F# line of code:

https://gist.github.com/vgaltes/8900b49681c56d0c792b

In this line we have declared a new module. In F#, unless you have only one single file in your project, every file must begin with a namespace or module definition. Both are ways we have to organize our code. The main difference is that inside a module you can define other modules, type definitions, values and functions but inside a namespace only modules and type definitions.

Now we need to include NUnit in the project. To reference a package in F# (a using in C#) we use the open keyword:

https://gist.github.com/vgaltes/c1ae19b0ab531ca3ba69

As we are working in a module, we can directly write the first test:

https://gist.github.com/vgaltes/58750e89636880cda7b8

In the line 1 of this gist we can see how we use an attribute in F#, in this case the Test attribute from NUnit.

In the line 2 we are defining a new function, in this case a function without any parameter. To do that, we use the let binding to identify the function. We are not going to see any example in this article, but it's worth mentioning that let bindings are immutable.

The next interesting thing is how we name the function. In F# we can use any type of string to identify a value or a function, we just need to change what we use to wrap it. In this case we are using a quoted identifier to use a string with blank spaces, just enclosing it in backtick characters (``).

Instead of using brackets to define the body of a function in F# we use an equal after the parameter definition and we indent the body. It's no important how many whitespaces we use as long as we are consistent in the indentation level we use.

And finally, in the line 3, we are making the assertion of our test. In this case we are asserting that "1" is equals than the result of calling a function called fizzBuzz with the number 1 as a parameter. In F# we don't use parenthesis to pass parameters to a function.

Not bad for three lines of code. But this code don't compile. We need to declare the fizzBuzz function in order to be able to run the tests. Let's do it:

https://gist.github.com/vgaltes/00a56221ddaa38423688

Here we are defining a function with one argument that returns an empty string. In F#, unless we are defining a function with more that one argument and with type annotations in the arguments (we'll see type annotations later), we don't need to use parenthesis to declare a function.

In F# all expressions (and therefore all functions) returns a value, so the last expression of a function is the return value. So, in this case, the expression "" is the return value of our function.

If we now run the test, the test will fail. To make this test pass, you just only have to return "1"

https://gist.github.com/vgaltes/96c45ef56e8d2008dab9

As you can imagine, the second test will be just as the first test but changing 1 with 2. Let's see how we have to implement the function to pass it:

https://gist.github.com/vgaltes/10bd928d5d1224c8540d

Here you can see our first flow control expression, in this case an if. In F# ifs are defined with the expression if...then...else. To compare to values we use the single equal operator.

In the third test we are going to test that the fizzBuzz function returns "Fizz" when the parameter is a 3. Let's see the changes we must do in the function:

https://gist.github.com/vgaltes/6816297abd63b6f60e4f

In this case we've introduced an elif (a shortcut for else if) to specify the second condition.

After the next test ("4" = fizzBuzz 4) we have enough duplication to do a little refactor. The result of the refactor can be something like this:

https://gist.github.com/vgaltes/62018983f630c98a26b8

As you can see we can use the standard .Net ToString function here.

The next important bit is after writing tests for 6 and 9. The code of the fizzBuzz function could be something like this:

https://gist.github.com/vgaltes/cbd9ba33f5039ffb2c4e

If you follow the rule of three, it's time to refactor. Our firs refactor could be something like this:

https://gist.github.com/vgaltes/39d4f39e3dab86555200

We are using the exists function from the List module. This function takes a predicate (a function) as a first argument and the list of elements as the second one. We are checking that the input is one of the elements of the list.

We can rewrite this piece of code in a more compact way taking advantage of currying. You can read more information about currying in this post.

https://gist.github.com/vgaltes/310108e02557af31750e

With the use of the parenthesis, we are converting the = operator into a function. So, when the List.exists supplies the current list item to our predicate, we can apply the function to compare it with the input parameter.

If we continue working we will end up with something like this:

https://gist.github.com/vgaltes/651a0c64d5f4aa04b511

Now it's time to apply a typical functional feature: pattern matching. Pattern matching is F# primary branching mechanism. So, we can remove these nested ifs with a pattern matching. Pattern matching is a quite big concept (we'll explore it deeply in the future) but here we are going to apply some concepts. Let's start with the simplest refactor we can do:

https://gist.github.com/vgaltes/edafb6efc55273543a1d

Here we are matching a tuple. The underscore character (_) is the Wildcard pattern that match any value and doesn't bind it to anything.

Finally we are going to apply a couple of refactorings more to reach our final implementation:

https://gist.github.com/vgaltes/b9dc646c7a403606af46

The first refactor we made is take advantage of the NUnit's test cases to simplify the test code and remove duplication.

The second refactor is to organize the code in different modules (nested modules), one for the production code and other for the test code. In F#, the order of the modules is important because F# code is evaluated from top to bottom. So, if we need to reference module Prod from module Tests, we need to declare it before.

And that's all. I hope you liked this little F# introduction. I'll keep the blog updated with the new things we'll be learning.

 

What object references this in JavaScript is always a tricky question. Let me try to explain you how the value of this is determined.

The value of this is based on the context in which the function is being called. Let's consider this piece of code:

<script>
 
var hello = 'Hello from the outer space';
var aObject = {
	hello : 'Hello from the earth'
}
 
var sayHello = function(){
	console.log(this.hello);
}
 
aObject.sayHello = sayHello;
 
aObject.sayHello();
sayHello();
 
</script>

The output of this code is this:

[caption id="attachment_244" align="alignnone" width="1024"]First example First example[/caption]

As you can see, in the first line we are calling the sayHello function inside the object, so this is referencing aObject. In the second line, we are calling the sayHello function of the global scope.

Nested functions

Things get a little more complicated when you have nested functions. Imagine this piece of code:

<script>
 
var aObject = {
	aFunction: function(){
		console.log(this);
		var anotherFunction = function(){
			console.log(this);
			var yetAnotherFunction = function(){
				console.log(this);
			}();
		}();
	}
}
 
aObject.aFunction();
 
</script>

The output of this code is:

[caption id="attachment_245" align="alignnone" width="1024"]Nested functions Nested functions[/caption]

As you can see, only the first call this refers to the object. On the other calls, this refers to the head object. This will be fixed soon, but in the meantime you should workaround this problem storing this in a variable:

<script>
 
var aObject = {
	aFunction: function(){
		console.log(this);
		var that = this;
		var anotherFunction = function(){
			console.log(that);
			var yetAnotherFunction = function(){
				console.log(that);
			}();
		}();
	}
}
 
aObject.aFunction();
 
</script>

 

Constructors

When you invoke a function with the new keyword this refers to the instance.

Imagine this piece of code:

<script>
 
var Elf = function(name){
	this.name = name;
}
 
var aegnor = new Elf('Aegnor');
 
console.log(agnor.name);
 
</script>

The output will be:

Be careful because if you don't use the new keyword, this will refer to the context in which Country is invoked. So, if we remove the keyword new of the previous example, the output will be undefined.

The same logic applies if you add a function to the object prototype. If you new an instance of this function and you call the added function which uses this, this will refer to the instance.

Using call or apply

You can overwrite the value of this using apply() or call(). When using these functions you specify which object will be used as this. Let's see an example:

 

<script>
 
var monica = {};

var setLocation = function(location){
    this.location = location;
}

setLocation.apply(monica, ['London']);

console.log(monica);
 
</script>

The output is:

[caption id="attachment_248" align="alignnone" width="725"]Using apply Using apply[/caption]

 

As you can see, determine the value of this is a little bit tricky but not so complicated.

Last Wednesday was my last day in the project I worked on the last six months. I've spent a great time working there, learning a lot of things and improving as a professional.

One of the members of the team, Mark, has the role of technical architect. If you have an agile mindset when you listen the word architect is not unusual that a look of disgust appears on your face. Concepts as Big Upfront Design appears on your mind and you start sweating.

But Mark is a great architect. His duties in the team are:

  • He goes to the pre-planning, UX/UI meetings.
  • He goes to technical meetings with other companies involved in the project.
  • He starts thinking in the technical solution of every feature, but he always discuss it with the team and never imposes his vision.
  • He's accessible to resolve any question the team (development and non development people) has.
  • He reviews some of the commits we make.
  • And he writes code!

I think that the architecture responsibility should be shared among the team. Actually, I think that it was in my team. But if your team doesn't have an uniform technical capability it's not bad to have someone who makes the first step.

What do you think? Do you have architects in your team? What are their duties?

When we write unit tests we usually try to apply our great object oriented knowledge, so we try to apply the well known DRY principle (Don't Repeat Yourself). One visible consequence of this effort is that the test code is considerably shorter than the previous version. A less visible consequence, but much more important, is that is harder to understand what the hell the test is trying to do.

For that reason, when writing tests, I'm more inclined to apply a non so well know principle called DAMP (Descriptive And Maintainable Procedures). When I write a test I try to think in myself in the future reading the test: will I be able to understand the test? Will I find the arrange phase of the test and understand what's happening there? Will I be able to understand easily why the test is failing (or passing)?

There are two main consequences of trying to apply DRY when writing a test. The first one is that we tend to write base classes where we put some kind of common code: variable initialization, mock setup (suitable for ALL tests), SUT creation... The second one is that we tend to write (with the help of the unit tests frameworks) setup methods with some common code too.

The result is that to be able to understand a test, I have to go up and down the file or, even worse, I have to go to a base class and see what's going on there.

There's no magic recipe to solve that. Some advice that may help you:

  • Evaluate if your class under test is doing too many things.
  • Don't use for/if/while in your test code (do more tests if necessary).
  • Inline the test setup
  • Use Test Data Builders to initialize your objects.
  • When possible, mock everything that is not your class under test.

Happy testing!

Last week I've worked in a tiny library to test if you have configured all the dependencies in your code in the IoC container. I borrowed the idea from this post from Juan María Hernández. The idea is simple, but it can save you some time of debugging.

Install the library is quite straightforward: just install the NuGet package you need depending on the container you are using:

install-package IoCTesting.StructureMap
install-package IoCTesting.Unity

To be able to use the library you need to have a method that returns the container. If you use StructureMap, you must have something like this:

public IContainer CreateContainer()
{
    return new Container(x =>
    {
        x.For<IFoo>().Use<Foo>();
        x.For<IBar>().Use<Bar>();
        x.For<IBaz>().Use<Baz>();
    });
}

The method could be static. The library will scan the assembly looking for this method and will call it to have the container initialized. After that, it will scan your assembly looking for classes that have a constructor with abstract classes or interfaces as parameters, and it will query the container to see if there's some registration for that type.

So, for example you can have a call like this:

var structureMapTesting = new IoCTestingStructureMap();
var errors = structureMapTesting.CheckDependencies(RegisteringAssemblyPath, RegisteringMethodName, TestingAssemblyPath, NamespaceToScan);

As you can see the library takes four parameters:

  • The full path of the assembly where the registration is performed.
  • The qualified name of the class that performs the registration.
  • The assembly you want to scan
  • The root namespace you want to scan. Types that its namespace doesn't start with it won't be scanned.

And returns an IEnumerable<string> with all the classes or interfaces not registered. Only supports constructor injection, not property injection.

And that's all. I hope it can be useful for you. If you have some issue or comment, please do it in the project page.