After nosing through some Scala FP books I have been trying hard to write small and simple functions and then compose them together. This post will show an example of where this has taken some needleslly complex code into something terser and easier to understand.
Previously
When getting our feet wet with Scala we would more or less still write fairly traditional OO code with some nice functional goodies mixed in.
This is one of Scala’s great strengths and it creates a relatively low barrier of entry for OO programmers; but there is a wealth of cool stuff you can achieve with it without having to blow the dust off your copy of The Gang of Four.
In this scenario we are re-implementing an old piece of functionality, which is user registration validation. The old Scala code to be fair it’s completely fine. It’s unit testable, fairly easy to understand and gets the job done.
My colleague and I (also named Chris); when re-implementing this feature for a new shared service thought we could use our growing Scala & FP skills to make something a bit nicer; and to show off. I think it’s important not to rest on your laurels with Scala and really try new things out when possible. It’s not just Java without semicolons.
The Problem
You wish to apply a number of validation rules against something and have a list of error messages to return eventually to a client.
For the first iteration of code there was a class for validation which had one public method which took the item you wished to validate. Within the class were a number of private functions that took the item and checked to see if the item was valid and returned a sequence of errors.
The respective functions are all called at the public function and the sequences are mashed together into one sequence of errors.
The validation functions have two responsibilities, applying the business rule and then returning a collection of errors when appropiate. By coupling these responsibilities the functions become less re-usable.
Imagine if the private functions were public so you could unit test them. To unit test the sub functions which contain the actual business logic, you need to check for the error message returned, rather than whether the field passes the validation or not.
It doesn’t look enough like a regular expression, which is how you know you are winning at Scala :)
Our Approach
When reading most FP books, they usually emphasise the idea of creating small “pure” functions which you then compose together to achieve greater pieces of functionality.
The ultimate solution: The Chris Validation Pattern
As I said, the colleague I did this was also called Chris so it’s not an entirely egotistical name. Anyway …
By thinking in terms of functions as being “pure” and only having one purpose, the resulting code was created fairly organically.
The first goal was to make it so the validation functions only dealt with applying a rule and letting the caller know if it passed or not
This means that unit testing these functions becomes very easy and not dependant on the error messages. Now that they are decoupled from any domain specific error messages; you could see how they could be refactored into something more generic, such as “stringIsTooShort”.
The next task is coupling each function with an error message, which is obviously done by creating a map.
You then simply run all the functions against the value you are testing, filter out ones that didn’t pass and then take the right side of the Map; which results in your list of error messages.
passwordValidation.filter(_._1(input)).map(_._2)
Ok, so to a non-scala developer it may not be completely obvious what that line does; but if you read into it, you can see it’s only really performing two operations over a map.
Granted, this isn’t the most impressive piece of code but I think it illustrates well how by being really strict in the responsibility of your functions and decoupling things you can compose useful functionality elegantly.
Edit
Thanks to Dan for pointing out that you can use the values method of a map to retrieve the values rather than the wonky .map(_._2). I also found that filterKeys can make this code more readable too.
In our house we thought it would be fun for each of us to make a Christmas song.
I found it a lot of fun, it was nice to sit by myself, take my time and try and make something okish. Generally when working with other musicians, they have been better than me and I always felt I needed more time to figure stuff out.
Granted, the bass is really the only well done bit, as I dont play lead guitar, sing, piano or even sing. Despite all this, it does seem to come together!
In previous attempts to make songs I have generally always struggled to make lyrics, so I just made up a stupid depressing story and ran with it.
The “story” revolves around a woman, who’s life takes a turn for the worse because of austerity times. She ends up on the streets and gets hold of some drugs. In a sea of strange hallucinations she convinces herself that she is a star that needs to climb to the top of a Christmas tree.
Tragically, the Christmas tree she is climbing is The Shard and this ultimately leads to her demise.
Enjoy.
Edit - forgot lyrics & chords
Just in case you want to play along at home?
Verse 1
C F
And santa watched her fall
C F
Dropped right into the Thames
Am G
And no one, gives a toss
Am G
And no one, gives a toss
Verse 2
And the reindeers were confused
Because she couldn't fly-y-y
Santa has a gift for you
It's a can of special brew
Chorus
Dm C
She was climbing up The Shard
F G
She thought she was a star upon a tree
Dm C
And she crashed down hard
F G
While we had some christmas cake and tea
C
Homeless and boneless
F
Pennyless and helpless
x2
Verse 3
Pigeons pecking at her brains
Deck the halls with boughs of blood (falalalala)
Death came down your chimney
Death came down your chimney
I have been reading the book Javascript Patterns, which is fairly easy reading and I would recommend it if you wish to understand Javascript a little better.
This post will describe JS objects, which is something you’ll come across when you’re writing almost any kind of JS.
Objects in Javascript are essentially hash tables of key value pairs. The values can be almost anything; strings, functions, other objects, etc.
It is worth noting that these objects are mutable which can offer some cool features but obviously has it’s drawbacks. This is why understanding scope is very important because otherwise you can get some unexpected behaviour when your object gets changed by something at runtime.
Here’s a basic example of this mutability, where we define an empty object and then add a property.
var person = {};
person.name = "Chris James";
Object literals
Objects can be defined upfront like this with a JSON like syntax:
var person = {
name: "Chris James",
sayHello: function(){
console.log("Hi, my name is " + this.name);
}
};
person.sayHello()
Constructor functions
Although there are no classes in Javascript you can create constructor functions to make objects in a standardised way which makes sense for your application.
var Person = function(name) {
this.name = name;
this.sayHello = function() {
console.log("Hi, my name is " + this.name);
};
}
var chris = new Person("Chris James");
chris.sayHello();
New
Using new will implicitly return the this object that you create in the function. You dont need to do var this = {}; - that is also done for you.
In other words what happens is similar to the first example in this post where it makes a new empty object and then adds the properties defined in the function.
Most importantly, the newly created object will also inherit the prototype of the function you defined.
Prototypes?
Javascript uses prototypal inheritence. A prototype simply defines methods that an object referencing it can run.
When you try to run a method of an object, if it cannot find the method locally to the object it will then try to find it in the object’s prototype.
Like most things in Javascript, prototypes are mutable which can offer some interesting (and insane) power to a programmer. You could have a bunch of widgets on a web page and based on an event, such as a user action change the functionality of all of them by changing the definition of their prototype.
Returning to the Person constructor function before, I defined a function called sayHello. Every time this constructor function is called and an object is made, a copy of that function will be made inside that object. This is inefficient and should be refactored to use a prototype instead.
This will potentially make unit testing easier too as you can simply create a mock object which has the prototype you wish to test.
var Person = function(name) {
this.name = name;
}
var chris = new Person("Chris James");
chris.sayHello(); // will fail
//The following is defined after "chris" is made
Person.prototype.sayHello = function(){
console.log("Hi, my name is " + this.name);
};
//But chris will have access to it by virtue of it's prototype
chris.sayHello();
//Prototypes are mutable...
Person.prototype.sayHello = function(){
console.log("Hola, me llamo " + this.name);
};
chris.sayHello(); // Spanish!
Therefore, if you think your object will be created more than once and has methods you should definitely consider including the functionality in a prototype to save memory.
Dont forget new
Unfortunately forgetting new will not cause any obvious errors. What it will do is bind new to the application’s Global object, rather than the “new” this which would normally be implicitly returned. In a browser, this would be the window object; fail!
This behaviour is fixed in the strict mode of ECMAScript 5 but this is not always available so it’s better to be safe than sorry.
Coffeescript constructor functions
If you use Coffeescript’s class syntax, it will take care of prototyping methods for you:
class Person
constructor: (@name) ->
sayHello: -> console.log("Hello #{@name}")
chris = new Person("chris")
chris.sayHello()
Results in
var Person, chris;
Person = (function() {
function Person(name) {
this.name = name;
}
Person.prototype.sayHello = function() {
return console.log("Hello " + this.name);
};
return Person;
})();
chris = new Person("chris");
chris.sayHello();
However, as far as I can tell it wont protect you against not using new
Constructor functions vs Object literals
So it seems there are two ways to create objects but which should you use?
If you wish for an object to just contain data then you should use object literals. It is also acceptable to use object literals if you are sure that you wont make another “instance” of your object to have behaviours attached to it.
If you feel you will have more than one instance of your object and in particular if you wish to add behaviour and alter it accross all instances then create it using a constructor function.
If you want to get started with web development with Node.js then Express is a good place to start.
To get started have your node.js and express dependencies installed, then simply run the command “express” in a directory and it will set up everything you need to make a website.
Unfortunately, as far as I am aware there is no simple way to start an express project with my current flavour of the month language; Coffeescript (it defaults to Javascript).
It has a number of other parts built in, such as a unit and functional test setup, HTML5 bootstrap and autominifcation of client side resources.
One language to rule them all
For an innovation week at Springer I created a project using this setup and it was a lot of fun. Writing code in Node.js puts you in a slightly different mindset as it’s very much event driven. Not only that but writing both client and server side code in one language made it feel a lot easier.
Often programmers complain about context switching. Context switching is bad as programmers like to focus on problems and achieve a state of flow, which helps productivity, (we are such delicate little flowers).
Switching of context can happen for a number of reasons, such as working on multiple projects or in many cases switching from a server side language to Javascript.
Working just with Coffeescript certainly helped me maintain flow and I feel like I achieved quite a lot in the 5 days. Not only that but it was very enjoyable (and I won £100 of Amazon vouchers :D)
Having only one language to use for your client and server also offers other potential advantages, such as sharing code between the client and the server. Often code is repeated when validation is performed on the same data on both the client and the server, which isn’t very DRY.
Sharing code
In many cases sharing code that runs on your server isn’t going to be very useful to your client code. Saving to a file system on a server isn’t code you want polluting your client functionality. In the same way you wouldn’t want any DOM manipulation code on your server.
However, there is definite overlap and the most obvious ones would be your domain models, such as a User class. Even then, there will definitly be code for your User class which is specific for your server and client respectively.
So why not use object orientation to have your shared code in your “base” User class but then have specific domain and client abstractions inheriting on top? Coffeescript’s abatraction of OOP on top of Javascript makes this fairly easy.