In my current project we had a hard deadline: we had to go to public beta on August and finish the transition of all users to the new system by the end of August. When we knew those dates our first reaction was this one:

Deadinle!

Depending on the environment you work the reaction to these news are usually some combination of a lot of pressure from management, working a lot of hours, drop the quality of your code, hysteria, etc.

To be honest, we had some of that, but the main reaction was the right one: scope management. If you have a deadline and assuming that hiring new people won’t ease your life, your last chance to success is to manage the scope of your project. Decide what is really really really important, what the users can’t live without and implement that. And nothing more. We conducted some workshops to do this work (the whole team, not only the product owner and business analyst) and the result was a reasonable product backlog to develop.

Apart from that, the team increased its commitment with the code quality. We increased the time doing pair programming, we did some mob programming for some difficult issues, we did lots of code reviews.

I’m not going to lie you and say that we were pleased to have such a hard deadline, but I think some of the consequences of having it have been really positive for the final product. Is far better to have an incomplete product that your users can use and give feedback than a super fancy product that nobody use.

A couple of weeks ago I saw these tweets (in Spanish):

As I respect enormously Modesto and Xabi’s opinion and I trust on the skills of a Carlos Ble’s apprentice, I decided to do the kata at home. And as I keep trying to learn F#, that would be the chosen language.

I recommend you to do the kata, is a very interesting one. In case you want to do it, please stop reading now and come back when you have finished it, as I’m going to explain how I solved it.

Spoiler alert

The kata starts pretty simple: you have to model a combat system between two characters of a RPG game. First you start with simple rules and in every iteration you add a slightly more complex one. At the end of the 4th iteration I ended up with a code like this:

As you can see, I have a list of rules that should be applied when attacking and a list of rules that should be applied when healing. I have a function to traverse a list of rules and apply them, and the rules are quite small and focused in one thing. I was quite happy with the design (remember, I’m learning Functional Programming, I can be totally wrong :) )

The real fun starts in the last iteration. In this iteration a new element of the game is introduced: a Thing. A Thing is an element that has health but nothing else. It can’t heal anyone, it doesn’t belong to any faction and it can’t attack. Is just something that everybody can attack.

Looks like a simple change but introduces quite a bit of complexity in the design. I decided to use a discriminated union to model a Player, so that a player can be either a Character of a Thing.

My first attempt to change the logic of the module was focused in two things: - Simplify the logic of the different rules, so that they just only need as a parameters the information they will use. - Put the logic around being a Thing or a Character in the main function

This solution ended up with a function like this:

Full code

As you can see, the code is a bit messy. It’s true that the rules now are a bit simpler and only receive as a parameter what they need, but on the other hand we have now three different types of rules that must be traversed in the main function.

So I decided to refactor my solution a bit. What I tried to accomplish was: - Move the logic around being a Thing or a Character to the rules. Now a rule is the responsible of knowing what to do in each case. - Simplify the logic of the main function. Now, it just differentiate about an Attack and a Heal, calls the same function to traverse the list of rules (different in each case), and applies the result in a different way.

Here’s the code of the main function:

And here’s the code of a couple of rules:

I prefer this approximation. I don’t have a nested pattern matching in the main function. I only have a list of rules for each case and the rules know what to do in each case. My concerns are: - What will happen if the types of players grow? Is there any way to generalise the types (i.e. a player that could be attacked, healed, etc)? - What will happen in the number of parameters of the rules grow? Is a smell that the design is not good enough? Should I introduce a parameter object (well, in F# maybe is a parameter record type :P )?

I’d love to hear your thoughts about the design :)

In the last days I stumbled upon some articles about how to improve, be more productive, etc. Usually you can separate this kind of articles in two categories: - the articles that talk about non work-related activities you must do if you want to increase your productivity. Eat the right food, sleep the right amount of time, do exercise, etc. - the articles that talk about work-related activities. Go to meetups, read, do pet projects, etc.

As many activities (if not all) we do as a human beings, the success of a technique always depend on many factors, being us the most important one. The things that work for me maybe don’t work for you.

Both kind of articles talks about valuable things that you should definitively do but taking them as the only source of truth can lead you to a difficult position. Let me explain my feelings with a couple of examples.

Until one month ago I was working in Coventry (I live in London) from 9 to 17. That means that I had to wake up at 6:15 and be back at home at 18:45, just in time to give my son a bath, have dinner and put my son to sleep. As I’m not a super-human I need to sleep at least 7 hours (to me the right amount of hours to sleep is 8 ), so basically I had one hour to do “other things”. Yes, I could have made a thorough study plan, but I also like to do strange things like talking to my wife, watch Game of Thrones, read a fiction book or play a videogame.

The hours in the train!! You should take advantage of the hour of train you have from London to Coventry!!

That’s what the Yoda inside me shouted from time to time. I tried to listen to him and actually I could read quite a lot on the train and do some coding. But it’s something you can’t do (or at least I can’t) on a daily basis. Sometimes in the mornings (and in the afternoons too) you need to sleep because you’re so tired, or you need to talk with your workmate, or whatever. Let’s say that you can use 4 of the 8 hours you spend on the train every week. Not too much but more than 0.

Obviously going to meetups, hackathons and so on was quite difficult.

One month ago we agreed that we can work at the train, so we just need to be from 9 to 15:20 in the office. That made a big change. Now I get home at 17:15 and I have time to pick up my son at the nursery. You don’t know how happy I am to do that.

Now you can do a lot of things in the afternoon! You have two hours more! Let’s make lots of pet projects and read thousands of books.

No I can’t. And I can’t because I don’t want to. I want to use those hours to be with my kid and my wife. I prefer to pretend to be Sant Jordi and the Dragon than reading the last rant about micro-services. I want to do some exercise a couple of days a week, and to go to some meetups from time to time.

What’s my point with this article? I think that every decision that you make in your life has some trade-offs and you have to think always if you want to accept them. And that those trade-offs are much bigger when you have a family. You can’t just decide that you’re going to focus in your career and leave all the other things apart. You have to try to do some of the things of both categories, focusing more on some things now and in other things later. I agree in what both categories of articles are explaining: it’s good to go to meetups, read books, do pet projects, go to hackathons, etc. And It’s also good (and probably more important) to eat well, do exercise, spend time with your family, sleep, do meditation and so on.

But you can’t just do the things of one category, and you can’t do all of them. Accept that and choose. And probably review and think what you choose every week. Fix some things you want to do (family, some sort of exercise) and decide what you want to do with the rest of your time.

Is for that reason that every day I value more remote work. I think that (in general) it allows you a greater flexibility and it removes commuting from your life, which is always great.

Introduction

A couple of weeks ago my friend Ian Russell explained the decorator pattern at work. For those who don’t know exactly how it works, the decorator pattern allows us to add behavior to an individual object without affecting the behavior of other objects of that class (Wikipedia).

The object oriented solution

There are a couple of typical implementations of the pattern in C#. The “lightweight” version is “just” to create decorators implementing the same interface of the decorated class, and passing the decorated object in the constructor of the decorator. So we need, at least, to create a new interface (maybe not needed anywhere else) and implement a different class for each decorator. Another option is to create an abstract class defining the decorator (that implements the same interface than the decorated object) and subclass it to create the different decorators. As you can imagine, a lot of boilerplate there.

The functional way

Let’s see how we can implement that using a functional language as F#.

Let’s start defining the object that we’re going to decorate:

let consoleWriter message =
    printfn "Console writer -> %s" message

Is a simple function that prints a message. Let’s decorate that function with a function that logs the message:

let loggingWriter logger writer message =
    logger message
    writer message

The function is like a mix between the class receiving a logger and a writter as a constructor parameters and the function to write the message itself in the object oriented implementation.

Now we need to write the logger. As usual, it will be a function:

let consoleLogger message =
    printfn "Console logger -> %s" message

And now, let’s create a decorator to add a simple validation:

let emptyStringValidator writer message = 
    if System.String.IsNullOrWhiteSpace message then
        printfn "Validation error"
    else
        writer message 

One more time, instead of having a class that receives the writer as a constructor paramenter and have a function to write the message, we just have a function that receives the function and the message.

Now it’s time to glue all this functions together. We are going to take advantage of partial application to define a function that uses all the previously defined functions:

let decoratedWriter = emptyStringValidator (loggingWriter consoleLogger consoleWriter)

If we take a look at the function signature we can see that it is:

string -> unit

So, it’s a function that takes a string (in this case the message) and returns unit (because we are using printfn). Using partial application we have composed a couple of functions: the first one, the one between parenthesis, is a writer (in this case a logginWriter) that takes the consoleLogger and the consoleWriter as a parmeters, and have a free parameter (the message). So, its a function that gets a string and returns unit, that is the function type that the emptyStringValidator is expecting as its first parameter. So, we can pass this function to the emptyStringValidator and we’ll get the function that we want, that takes a string as a parameter and return unit.

If we call this function with a string, we get the following result:

decoratedWriter "Hello world!"
> Console logger -> Hello world!
  Console writer -> Hello world!

And if we call it using an empty string we get the follogins result:

decoratedWriter ""
> Validation error

Summary

We have seen how much more elegant our code results when using a functional language. In the object oriented code, we have a lot of code that is not really adding any value (interfaces, abstract classes, constructors…). In the functional code, we just have functions and we use a well know feature of the language as it is partial application to compose the function that we really want. You can find the code on Github

In the previous article we saw how to send forms using Suave.Experimental as view engine. In this article we’re going to use Suave.DotLiquid as view engine. We’ll see how we’re going to be able to reuse most of the work done previously.

Suave.DotLiquid

DotLiquid is a port of the Ruby template engine Liquid. Suave is able to use this library thanks to the pakage Suave.DotLiquid. So, the first thing we need to do is install these packages in our project.

Reusing code

We’re going to change only the view part of our application, so we dont need to define any new ViewModel or anything.

The view

To use DotLiquid we need to create temlates as html files. Inside this templates we are able to write constructs that we’ll be replace by text. In this simply example we’re not going to use anything more sophisticated than this, but you can refer to the original documentation to see what you can do.

So, the view should look like this:

<html>
    <head>
        <title>Forms with DotLiquid</title>
    </head>
    <body>
        <div>Create</div>
        <form method="POST">
            <fieldset>
                <div class="editor-label">Name</div>
                <div class="editor-field">
                    <input name="Name"type="text"required=""/>
                </div>
                <div class="editor-label">Surname</div>
                <div class="editor-field">
                    <input name="Surname"type="text"required=""/>
                </div>
            </fieldset>
            <input type="submit"value="Create human"/>
        </form>
    </body>
</html>

In this is standard HTML. Let’s take a look at the view that will display the Human model to see DotLiquid in action.

Forms with DotLiquid
Show
Name:
Surname:

As you can see, we are accessing the properties Name and Surname of the model, in this case the Human type defined in the previous article.

The application

The changes we need to do in our App.fsx are really small.

Firts, let’s define the folder where DotLiquid will search for the templates.

DotLiquid.setTemplatesDir (__SOURCE_DIRECTORY__ + "./Templates")

And now let’s define the new WebPart we’re going to use.

let dotliquidHuman =
    choose [
        GET >=>  DotLiquid.page ("CreateHuman.html") ()
        POST >=> bindReq (bindForm Forms.human) (fun form -> DotLiquid.page ("ShowHuman.html") form ) BAD_REQUEST
    ]

As you can see, is very similar to the Experimental one, but we change a little bit how we call the view engine. In this case, we use the function DotLiquid.page, passing as arguments the name of the template and the model to use (unit in the first case, and form in the second case).

And that’s all, we don’t need to make more changes to make it work.

Summary

We have seen how easy is changing our view engine when working with Forms. We’ve seen a very little introduction to DotLiquid, a nice template engine we can use with Suave. You can get the full solution here