Mainstay Monday: Inheritance

Jun 22, 2015

This is the first in a new series I am trying out on my blog. Every Monday I want to provide a post about some foundational element of programming and how it relates to Javascript development. What better place to start than inheritance?

Object inheritance is one of the one of the least understood foundation Javascript topics I can think of. Even if a developer is comfortable with prototypal behavior and instantiating prototypal objects, handling inheritance is a layer which is more obscured in the Javascript than classically designed, OO languages.

Let’s discuss the object prototype. To start with a simplified definition, an object prototype is a set of properties associated with an object that defines the foundation functionality an instance of the object will have. In other words, anything you put on an object prototype will define what that object will be when you perform a ‘new’ operation.

Let’s take a look:

//This is an object setup in ES5
function Fooer(){}

Fooer.prototype = {
    foo: function(value){
       return 'bar';
    }
};

var myFooer = new Fooer();

console.log(myFooer.foo()); // 'bar'

This is about as simple as it gets. We define a function attached to the prototype, let’s call it a method to keep parity with classical OO languages, and when we get a new instance, the method is attached to the object we get back. Once you are familiar and comfortable with this syntax, it’s easy to do and easy to understand. The pitfall we have here is it’s a little convoluted. ECMAScript 6 (ES6) introduces a new, more classical notation, though the underlying behavior is still the same as it ever was.

//ES6 classes look like this
class Fooer{
    foo(){
        return 'bar';
    }
}

let myFooer = new Fooer();

console.log(myFooer.foo); // 'bar'

The code is a little shorter and, hopefully a little more declarative of intent, but the end result is identical. Now, in classical languages, there is a concept of object hierarchy. OO languages provide a clear construct for how this is handled with a special keyword. Let’s call this inheritance keyword ‘extends.’ Let’s pretend our classical language uses this ‘extends’ keyword and create a child object with it.

class Greeter extends Fooer{
    greet(name){
        console.log('Hello, ' + name + '.');
    },

    fooGreet(){
        this.greet(this.foo());
    }
}

let myGreeter = new Greeter();

myGreeter.greet('Chris'); // log: Hello, Chris.

console.log(myGreeter.foo()); // log: bar

myGreeter.fooGreet(); // log: Hello, bar.

You’ll note that we just got the parent properties for free. Extra bonus, SURPRISE, that’s ES6 syntax. It’s nice and easy. Most of us are still working in ES5 and in ES5, the times are hard. Let’s have a look at what inheritance looks like when you don’t have all the handy dandy syntactic sugar.

function Greeter(){}

Greeter.prototype = Object.create(Fooer.prototype);

Greeter.prototype.greet = function(name){
    console.log('Hello, '  + name + '.');
}

Greeter.prototype.fooGreet = function(){
    this.greet(this.foo());
}

Greeter.prototype.constructor = Greeter;

var myGreeter = new Greeter();

myGreeter.greet('Chris'); // log: Hello, Chris.

console.log(myGreeter.foo()); // log: bar

myGreeter.fooGreet(); // log: Hello, bar.

This is a lot more verbose than our friendly ES6 syntax, but it’s pretty clear the result is the same. We end up with an object that performs a new operation and directly inherits properties from Fooer. This verbosity along with the hoops you have to jump through makes it pretty obvious why people don’t introduce object inheritance in a beginning discussion of Javascript.

Regardless of the obscurity, we can try this and see inheritance really works and it adheres to the kinds of expectations we would bring from languages like Java, C#, PHP, etc.

var testGreeter = new Greeter();

console.log(testGreeter instanceof Greeter); // true
console.log(testGreeter instanceof Fooer); // true

By adding object inheritance to our arsenal, we can look back to our computer science forefathers and apply the knowledge they shared in books like the Gang of Four Design Patterns book. Concepts like inheritable DTOs become usable in Node and in the browser and we can begin to normalize our coding practices and use sane conventions in our profession to help us focus on the task at hand: solving new problems.

On top of all of this, we can see deeper into what is really happening with prototypes. When we understand how prototypes handle object properties and provide a link to the parent object, we can better understand how to leverage the finer nuances of the language for a more powerful programming experience.

Blog Notes

For an abstraction layer to handle inheritance, please see my gist.

Don't Talk About My ObjectMother That Way

Jun 17, 2015

When last we met, we talked about setting up unit testing for Javascript. I’m sure anyone reading this blog is at least aware of the idea of software design patterns. There are all of these known challenges with canned solutions. If the solution isn’t ready out of the box, it is with just a little bit of tweaking. Something you might not be aware of is there are unit testing design patterns too.

Er… What?

I know, most people think of unit testing as either something they tolerate because it’s required or, at best, a list of tiny little functions that guarantee that a particular behavior matches the expected business requirement. Where is there room for design patterns?

Many patterns come in the form of best practices, but there is one that is at the top of my list of all time favorites. The ObjectMother pattern is a design pattern tailor made for unit testing. Technically you could use ObjectMother in your everyday programming as a factory or something like that, but today it’s all about testing.

Let’s start by looking at a unit test for two different functions that require data from the same contract. I’m just going to hand-wave past what the functions do, because it doesn’t really matter right now. Right? Right.

describe('dataModule', function(){

    describe('firstFunction', function(){

        var myTestData;

        beforeEach(function(){
            myTestData = {
                records: [ { required: true }, { required: true}, { required: false } ]
            };
        });

        it('should return the number of required records', function(){
            expect(dataModule.firstFunction(myTestData)).toBe(2);
        });

    });

    describe('secondFunction', function(){

        var myTestData;

        beforeEach(function(){
            myTestData = {
                records: [ { id: 1 }, { id: 2 }, { id: 3 } ]
            };
        });

        it('should return an array of record ids', function(){
            var result = dataModule.secondFunction(myTestData);
            expect(JSON.stringify(result)).toBe(JSON.stringify([ 1, 2, 3 ]);
        });
    }

});

That is a LOT of typing for two little tests. It’s especially bad since the two different objects are so similar. Now, we could combine the two object setup blocks into a single beforeEach at the top, but what if this same data object is necessary in another test in another file? What if, worse than that, there are several modules that might interact with this data, each capturing data for a particular purpose which could be unrelated to the data module we tested here?

The almighty DRY principle would tell us this is inherently flawed. There is a code smell and that smell is one of the big reasons I hear people hate writing unit tests. What if we could actually DRY out our unit tests in a sane, maintainable way?

Enter the ObjectMother pattern.

Here’s what the mother of this object might look like:

function testDataMother(){
    return {
        records: [
            { id: 1, required: true },
            { id: 2, required: true },
            { id: 3, required: false }
        ],
        otherProperty1: 'foo',
        otherProperty2: 'bar'
    };
}

With this defined, our test code becomes much simpler to write, read and maintain. If we use our new object mother, here’s what our tests become:

describe('dataModule', function(){

    var myTestData;

    beforeEach(function(){
        myTestData = testDataMother();
    });

    describe('firstFunction', function(){

        it('should return the number of required records', function(){
            expect(dataModule.firstFunction(myTestData)).toBe(2);
        });

    });

    describe('secondFunction', function(){

        it('should return an array of record ids', function(){
            var result = dataModule.secondFunction(myTestData);
            expect(JSON.stringify(result)).toBe(JSON.stringify([ 1, 2, 3 ]);
        });
    }

});

It’s like magic, right? We just eliminated 10 lines of code we were using in our original test file and now we are able to focus on the problem, testing our functions. What’s even better, we have now centralized our data example so any other tests can use it too and we only have to modify it in one place to expand our tests. If the contract were, heaven forbid, to change, we can change our data in our mother file to match the new contract and then identify any breakages, update functionality and guarantee function and data parity. This is a HUGE win.

For small sets of tests, and relatively simple data structures, this is perfectly acceptable. What happens when you have nested data structures and complex logic to interact with it? Now you have data interdependencies and our simple functions aren’t going to be sufficient.

This calls for other, well known, patterns. We can draw upon the Factory and Dependency Injection patterns to make this better. We can employ initializing functions and initial condition objects to define a more robust interface.

Since these requirements arose as I was working through unit testing scenarios in my day to day life, I created a library, DataMother.js. DataMother allows you to isolate layers of objects and register them with an injection system. At test time, you can use DataMother to handle your data requirements much like we did above which actually made unit testing with data so easy, I actually started looking forward to it.

Weird, right?

Anyway, whether you use the naive method outlined earlier or a more robust solution like DataMother.js, use the ObjectMother pattern in your testing and bring the joy to unit testing data-driven functions that you have in the rest of your programming life. Unit tests and data can be friends!

Blog Post Notes:

The ObjectMother pattern was first discussed (as far as I know) in 2006 by Martin Fowler.

The links below are assembled from the links in the post:

(Not) Another JS Testing How-To

Jun 10, 2015

There are lots of posts about how to write your first unit test in Jasmine or Mocha, and many of them draw directly from the Jasmine how to. Let’s pretend, for a moment, that you are a developer who is already familiar with unit testing and what you really, REALLY need is a way to actually get things started without having to read a whole host of how-tos, setup documentation etc, when all you really want to do is get to unit testing.

First, let’s get the Grunt versus Gulp conversation out of the way. I say neither! Though task runners can make CI much easier, this post is about getting a quick start into actually doing unit testing. By setting up a good, solid base configuration, moving to a task runner can be as simple as just applying the configuration you have with the runner you choose. Perhaps you like Tup…

Anyway, now that we have all that out of the way, let’s talk tooling:

When we are done, this is the toolset you will have for your testing needs:

  • Node and NPM
  • Jasmine
  • PhantomJS
  • Karma

The biggest hurdle you have to cover to get everything up and running is to get Node.js up and running. For most reading this article, all you have to do is visit the Node.js website and click install. You will get the right binary and you will be off and running.

Once Node.js is installed, it is all downhill. I created a Github project that you can use to quickly get started with unit testing on just about any platform. You can either download the release, or follow the directions below:

git clone https://github.com/cmstead/jsTestDemo.git

Once you’ve copied this repo one way or another, setup is really simple. You will need to install Karma and Phantomjs globally, so I created a handy one-time use script you can run. After the global installs are finished, you can run the project specific installer and you’ll be ready to rock and roll. Open a console wherever you cloned the repository and run the following commands:

#This does your one-time setup
npm run-script globalinstaller

#This is your project-specific setup
npm install

No fuss, no muss. You’re welcome. ; )

You’ll see lots of packages stream by in the console. Once everything installs, you’re ready to start testing. It’s not exactly exciting bedtime reading, but I definitely recommend looking at the Jasmine website. Their documentation is written as a set of unit tests for the framework, which is novel, but it makes things a little hard to figure out on first read.

Let’s have a look at a (barely) annotated first unit test:


describe('testObject', function () {

    var testObject;

    //test setup
    beforeEach(function () {
        testObject = {
            foo: 'bar',
            baz: 'quux'
        };
    });
	
    //test teardown
    afterEach(function () {
        testObject = null;
    });

    //A single unit test
    it('should be an object', function () {
        //The equivalence of an assertiion
        expect(typeof testObject).toBe('object');
    });
});

```

When you start writing unit tests for your code, be sure to review the Karma configuration file in the spec folder.  Most settings can be left exactly as they are, but the paths should be updated to match your project structure.  I've included the code below so you can see the lines which need to be updated:

```javascript
files: [
            //Uncomment the following line and change the directory
            //to match your project structure.
            //'../scripts/**/*.js', //change me
            './**/*.spec.js'
        ],

        preprocessors: {
            //Change this to match your project directory structure
            '../scripts/**/*.js': ['coverage'] //change me too
        }
```

Although this isn't the snappiest blog post I have written, I have gone through this process so many times I have created templates for different kinds of projects just to save time and simplify the process of setting up unit tests, linting, ES6 transpilation, code coverage, etc.

With so many different configuration options, limited documentation and roadblocks I have encountered as I have gotten systems set up, I wanted to put something together that might help save someone else a little pain and suffering. If you have feared unit testing in Javascript because of setup troubles, consider this your personalized invitation. Unit test your code and make the web a better place!

    

Browser-side Isomorphic Javascript

Jun 3, 2015

With the advent of Node, there has been discussion of isomorphic Javascript.  The general idea behind this is code written for server-side purposes can also be used for UI purposes. The problem with this notion is, it doesn’t account for browser UI/middleware considerations in the browser.

As client-side development progresses and software as a service (SaaS) and single-page applications (SPAs) become more common, UI developers continue to program based on user interactions with the view layer and the underlying logic gets woven into the UI code, littering data logic with DOM related code, which tightly couples the UI code to the data code, creating complicated, unmanageable software.

What ends up happening is code gets duplicated to serve the same purpose, and then the code gets out of sync. Bugs creep in and pretty soon the software starts getting cracks in the facade. Even frameworks that are intended to avoid this kind of behavior, like Angular, are built in a way that allows for divergent code.  Let’s have a look at a snipped of code that could diverge quite quickly, in Angular.


<!-- This is in the view somewhere -->
<input type="text" id="weird-id" ng-required="true" ng-pattern="^abc\d{3,5}$" />


//This is data validation somewhere before submission
function validateId(value){
    return value.match(/^abc\d{3,5}$/) !== null;
}

Obviously there was some cutting and pasting that went on here.

What happens when the requirements are changed? Will this developer remember that the regex needs to be changed in two locations? Will this developer even still be working for the same company?

Even if this is remembered once, it is almost guaranteed to be forgotten about. This is especially heinous because there are clearly two different concerns being served here. One place the UI is handling input validation so the user can get immediate feedback, the other is likely to be related to handling validation before data is sent to a service somewhere.

It is not obvious even from this simple example that DRY could be applied here. Of course it can, but the solution is not completely obvious. Since this is not a post about Angular validation, I will leave the Angular-specific details as an exercise for the reader. Instead, let’s take a look at a more general solution.

Obviously the script handling the validation is pretty general so we’re probably safe to start there. Let’s keep it. That means all we really need is validation for the UI. Let’s have a look at something that would give us the behavior we want:

function attachIdValidator(element){
    element.addEventListener('change', function(event){
        var inputValue = element.value,
            validValue = validateId(inputValue),
            elementHasError = element.classList.contains('error');

        if(!validValue && !elementHasError) {
            element.classList.add('error');
        } else if(validValue) {
            element.classList.remove('error');
        }
    });
}

Now our element has the same validation attached that our outgoing data will use to ensure everything is on the up and up. Honestly, though, this is a fine first pass, but you and I both know this isn’t the only validator you are going to use to handle your user inputs. Why don’t we do a little more cleanup and write something we can really get some mileage out of.

function setErrorState(element, validInput){
    if(!validInput && element.classList.contains('error'){
        element.classList.add('error');
    } else if(validInput){
        element.classList.remove('error');
    }
}

function attachValidator(element, validator){
    element.addEventListener('change', function(event){
        var inputValue = element.value,
            validValue = validator(inputValue);

        setErrorState(element, validValue);
    });
}

//Applying our new logic would look like this:
attachValidator(document.getElementById('weird-id'), validateId);

Now, that’s what I call DRY code. Now we have taken one piece of logic, isolated it and applied it in the places we need it. Sure it took a little extra code to get us there, but you can see the difference it makes. Now if someone comes along later and says “gosh, it would be great if the ID values could start with efg instead of abc,” anyone who is currently working with the code can go and update the validation logic and it will update the requirements everywhere.

What’s even better is, now we have a UI validator that we can apply any kind of validation logic and not need to continue writing and rewriting UI logic to handle all of that mess. Extra special bonus is this entire thing is written in vanilla Javascript, so it’s extra small, tight and as fast as we could make it.

When you do this in your code, go ahead and pat yourself on the back. You deserve it.

In the end, what people are really talking about when they say isomorphism, what they really mean is “don’t repeat yourself.” When that’s the goal, then isomorphism doesn’t have to be limited to client/server applications. Take the lesson and run with it. Make your code better and your users (and your boss) happier. Let’s use isomorphic code to make the world a better place.

Everyday Functional Programming in Javascript

May 27, 2015

I gave a talk at the beginning of the year about functional programming. Someone asked “can you do functional programming little by little or do you have to do it all, all the time?”

When I answered, I felt I didn’t give them the answer they deserved or that I could have given.  This is my answer. Yes, you can do a little or a lot. You can write functional code little by little and solve things without changing your life and your career.  You can write programs that aren’t academic or theoretical. You can write everyday functional code.

So what does everyday functional programming look like?  Unless you work somewhere that you write in Lisp, Clojure, ML, F#, Haskell, etc, then it doesn’t look anything like the high-brow academic tutorials you see most often.  You don’t talk in monads and exclusively pure functions.  It’s not an ivory tower. At best you are a warrior acolyte of the functional cloth.

State is a thing.

So, when you are working in functional languages, state is a difficult knot to untie. Since values are immutable and shared state is the work of something unholy and evil, handling things like state machines becomes a chore. Who wants to go to work and think “today is the day I have to tackle the beast. I hate today?”

Not. Me. Thanks.

Sometimes you really need state. You actually need to know what happened and what is coming.  Sometimes you want something that you can mutate and something that is transitory, but still in memory. Hi to all of you Haskellians, yes I know there are other ways of doing that kind of monkey business, but I just don’t wanna. It looks a little too much like work and a little too little like fun.

First class functions are for everyone.

Now that I got the state stuff out of the way that OO does just so well, let’s talk about what functional workflow looks like in my happy little world. Arguably the thing I feel differentiates functional programming from programming that isn’t is the beautiful higher order function.

I mean, it’s magic right? Higher order functions, I mean look at this:

    function add(a, b){ return a + b; }

    function addTheseNumbers(numberArray){
         return numberArray.reduce(add, 0);
    }

That’s what I am talking about. Functions that take functions as arguments. It’s all kinds of awesome, right?

Okay, in all seriousness, the real awesome comes when you start blending pure functions in with your stateful code and moving all of that stateless logic into something that makes more sense for what you are trying to accomplish. Let’s have a look at one of my all time favorite constructs. It’s what makes my world go ‘round: either.

Watch this.

    //What life was like before
    function doStuff(someData){
        var someProperty;

        if(!!someData){
            if(!!someData.someSubData){
                someProperty = someData.someSubData.someProperty;
            }
        } else {
            someProperty = 'default value';
        }
        //What the crap is this???
    }

    //What life is like now
    function doStuff(someData){
        var defaultData = {
                someSubData:{ someProperty: 'defaultValue }
            },
            someProperty = either(defaultData, someData).someProperty;
        //Hooray! Now we can set a default
    }

All of this because, honestly, who needs all the conditionals? Do you care about the conditional logic or do you just care about the data? Personally, I think conditional logic is the devil. I mean, honestly, the worst bugs and the most  difficult mess comes from all of these horrible, horrible conditionals. Let’s cut to the chase and just make it right.

Here’s something even more amazing, ready for this? ARE YOU READY? Yeah, you’re ready. ```javascript //I mean, it MIGHT be an array or it might just be null. Who knows, right? function doFunctionalStuff(myArrayMaybe){ return either([], myArrayMaybe).filter(somePredicate) .map(transformStuff) .reduce(reducerFunction); }

I mean, DUDE, you can skip all of the worrying. If something null happens, you just pretend it never existed and everything turns out just fine. With just one new function, all of a sudden you get  all of the functional goodness that Javascript has to offer.

What does either look like?
```javascript    function either(defaultValue, maybeValue){
        return !!maybeValue ? maybeValue : defaultValue;
    }

That’s it. It’s the gift that keeps on giving.

At the end of the day, what I am really getting at is this: everyday functional programming is all about cutting to the core of what you want to do and eliminating the conditions, unnecessary shared state and error prone code so you can keep your sanity. It’s not about all pure functions all the time. It’s not always about monads and currying. It’s about the little things that make a big difference so you can do your best work.