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:

1
2
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:

1
2
3
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:

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

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

1
2
3
4
5
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:

1
let decoratedWriter = emptyStringValidator (loggingWriter consoleLogger consoleWriter)

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

1
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:

1
2
3
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:

1
2
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:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
<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.

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

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

1
2
3
4
5
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

Sending data to a web server is a very common task when developing a website. From registering a new user to filling some personal details in a web commerce application, we usually have to deal with filling a form and send its data to the web server. In this series of articles, we are going to see how to send data using different view engines.

Suave.Experimental

Experimental is a component available via NuGet that allows us to write the views using F# code. We are not going to discuss if that’s a good thing or not, we are just going to show how to work with forms.

We are not going to explain how to setup a basic Suave application. Plese refer to their website to do it.

Defining the form

Let’s start creating a new file called Form.fs with the following code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
module FSharpForms.Forms

open Suave.Form

type Human = {
    Name : string
    Surname : string
}

let human : Form<Human> = 
    Form ([ TextProp ((fun f -> <@ f.Name @>), [])
            TextProp ((fun f -> <@ f.Surname @>), [])
            ],
        [])

In this file we are defining the type that we want to be filled by the user, in this case a Human with a Name and a Surname. We are defining a Form of that Human as well, specifying the type of the properties, in this case strings both of them. The empty list that you can see at the end of the definition of each field is a list properties (maxLength, min, max, etc). In this basic text, we don’t need any property. The final empty list is a list of ServerSideValidation which is basically a tuple composed by a function that returns an string and a message.

The view

Let’s define the view right now. Let’s start defining the module and open the necessary modules.

1
2
3
4
5
6
7
module FSharpForms.Views

open System

open Suave.Html
open Suave.Form
open FSharpForms.Forms

It’s time to define the view. We should write a code like this.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
let createHuman = 
    html [
        head [
            title "Forms with Experimental"
        ]

        body [           
            div [text "Create"]            
            
            tag "form" ["method", "POST"] (flatten 
                [
                    tag "fieldset" [] (flatten 
                        [
                            divAttr ["class", "editor-label"] [
                                text "Name"
                            ]
                            divAttr ["class", "editor-field"] [
                                input (fun f -> <@ f.Name @>) [] Forms.human
                            ]
                            
                            divAttr ["class", "editor-label"] [
                                text "Surname"
                            ]
                            divAttr ["class", "editor-field"] [
                                input (fun f -> <@ f.Surname @>) [] Forms.human
                            ]
                        ])
                        
                    inputAttr ["type", "submit"; "value", "Create human"]                
                ])
        ]
    ]
    |> xmlToString

As you can see we use helper functions to write the html tags. Almost all the tags are part of the Suave.Html module. The only one that belongs to Suave.Form is input. Input takes a quotation expression as its first parameter to know which field of the Form is linked to. As last parameter, it takes the form.

We should return an string, so we use xmlToString at the end.

The application

Is time to go to our Suave application and make all this code work. Let’s start defining the WebPart that we are going to use

1
2
3
4
5
let experimentalHuman =
    choose [
        GET >=>  OK (Views.createHuman)
        POST >=> bindReq (bindForm Forms.human) (fun form -> OK ( Views.showHuman form) ) BAD_REQUEST
    ]

It’s a quite simple WebPart. We’re using choose to differentiate between a GET and a POST (we are using the same Url for both actions). In the GET route, we are returning our recently created view. The most interesting part comes in the POST route, where we are binding the information of the POST request to an instance of the Forms.Human type. To display the results we are using the following view:

1
2
3
4
5
6
7
8
9
10
11
12
13
let showHuman human = 
    html [
        head [
            title "Forms with Experimental"
        ]

        body [           
            div [text "Show"]
            div [text (sprintf "Name: %s" human.Name)]
            div [text (sprintf "Name: %s" human.Surname)]
    ]
    ]
    |> xmlToString

As you can see, we only need to access the fields of the Forms.Human type.

Summary

We have seen an introduction to Forms in Suave. In following articles we’ll see how to do the same with other view engines. You can get the full solution here

As Scott Wlaschin points out in his excellent article function composition it’s not the same as using the pipeline operator.

The definition of the pipeline operator is this one:

1
let (|>) x f = f x

So, take the thing on the left hand side of the operator and use it as the last parameter on the function in the right hand side.

On the other hand, we have this definition for the forward composition operator (»)

1
let (>>) f g x = g ( f(x) )

That means, take the parameter and pass it to the function on the left hand side of the operator, and then apply the function on the right hand side of the operator to the result.

For example, if we have this couple of functions:

1
2
let add1 a = a + 1
let mult2 a = a * 2

We can define the composite function as

1
let addAndSum = add1 >> mult2

And therefore, when we do

1
2
let res = addAnSum 3
> val res : int = 8

As you can see, we are applying the first function (add1) to 3 and then apply the second function to the result ( ( 3 + 1 ) * 2 = 8 )

Preparing my talk at FSharp eXchange, Visual Studio Powertools warn me about replacing a pipeline by a function composition. The code (simplified version) is this one.

1
2
3
let tuples = [|("a", [|1|]);("b", [|1;2|]);("c", [|1;2;3|]);("d", [|1;2;3;4|])|]
tuples
|> Array.sortByDescending(fun m -> snd m |> Array.length)

Let’s decompose this code to see what is it doing. The previous code is equivalent to the following one:

1
2
tuples
|> Array.sortByDescending(fun m -> Array.length(snd m))

Looking at the part in the right hand side of the arrow we can see that this is equivalent to the definition of composition we’ve seen previously, being Array.length equivalent to g and snd equivalent to f. That means that we can change the previously code by this one:

1
2
tuples
|> Array.sortByDescending(snd >> Array.length)

As you can see, the final code is much more elegant and succint, and easier to read when you understand what is it doing.