måndag 23 februari 2015

Yeah, we got classes now (ES6). You happy, pappy?

Since the beginning of time, JavaScript has been the class less society. Everyone had a function there. With ECMAScript 6, classes have now been added. Ah, man.

Wait, wait, wait! I actually like it. I believe the class keyword is good thing to JavaScript, mmkay?

There is quite a few frameworks out there that already have introduced classes (or class like solutions) to the language: Dojo, Prototype, CoffeScript, TypeScript ... They all have their own way of doing it. ECMAScript introduces a common way of how to write a class, and that itself is great. How can classes be useful in JavaScript?

I think it can simplify the structure of code, we can write functionality that is only accessible within a class. But then again, we have modules now. A module can export an object and keep code private. Why use classes?

Well, I think the benefit of writing a JavaScript class is inheritance (using the extends keyword). Inheritance can of course also be accomplished by creating literal objects extending other objects, simply by adding properties and methods to it. But the functional inheritance style looks kind of awkward sometimes. Writing a class that extends another class will probably make more sense. Especially for programmers used to write code in c#, java, Ruby or any other object oriented language.

However, I don't think consuming a class the traditional way is a good idea in JavaScript. I think it is an anti-pattern. Creating instances of classes using the new keyword spread out all over the code base? Don't do it! 


In sucks in c#, it sucks doing it in JavaScript too. Dependency Injection and IoC containers solve the "newing up classes problem" in c#. How about JavaScript?

Here's a suggestion.

Create your classes in ES6 modules. Export an already created instance (if you want a singleton like functionality), or export a "make" method that returns a new instance of the class.

By doing that, the consumer doesn't have to worry about if the code within the module is a class or an object literal.

An example:

// the foo module, exported as a singleton
class foo {
     constructor() {
          // constructor code here
     }

     myMethod () {
          // method body code here
     }
}

export default new foo();


// the foo module, exporting a "make instance" method
class foo {
     constructor() {
          // constructor code here
     }

     myMethod () {
          // method body code here
     }
}

let makeFoo = () => new foo();

export default makeFoo;



Using the first example, the consumer will get a baked and ready instance of the foo class. The second example will give the consumer the ability to get different instances, by calling the make function. The actual structure (currently a class) of the module is hidden, and not a part of the API.

What do you think about this? Let me know!






" - Happy, Pappy?"





söndag 22 februari 2015

Is the ES6 import feature an anti-pattern?

The new version of JavaScript is currently occupying my mind. I really like the ECMAScript 6 features, and the fact that we can write code using new stuff like arrow functions, scoped variables and native modules today (by using transpilers) is quite awesome.

There is especially one of the ES6 features that I've been thinking about: importing of modules. Modules will change the way we think about JavaScript for the web. Importing a module is so easy with ES6 and the syntax is very nice, readable and clean. How do I unit test such a module?


-----------
Update: I have experimented with an alternative to the examples in this blog. Have a look at it and please share your thoughts and feedback on the different approaches to unit testing modules:
Test friendly JavaScript modules - without Dependency Injection
-----------

The import statement uses a relative url to perform the module lookup. So, can I somehow configure a "base test suite url" to load fake modules that my module under test is dependent of? Would that require me to write a lot of stubs (files)? Is it even possible, without writing a custom module loader? That's the things I have had on my mind, for a couple of days now.


See, these days I mostly think about code and don't actually write code that much. How come? I am currently enjoying life as a swedish dad on paternity leave. The days with the one year old are great. We read books, build with blocks and laugh a lot. I love it.

When he is sleeping, I catch up on coding by reading blogs (mostly one of the great posts on ES6 by Dr. Axel Rauschmayer) or watching a video tutorial (I recommend the ES6 course on Pluralsight, by Scott Allen and Joe Eames). I am learning new things, slowly, but scheduled and at a steady pace.

Tonight, just when I had finished reading a Pippi Longstocking bedtime story to our four year old son (the big brother), the background process of the brain suddenly sent me a message: keep it simple. Use dependency injection. Dave, you know this already. I think the new syntax and the new ways of writing has blinded me, made me forget about concepts I normally use when writing c# or old school JavaScript (pre ES6).

How about writing modules with dependencies injected, by exposing something like an "init" function, instead of directly importing them? That would make them testable. Something like this:


// foo.js
let message = 'My name is foo';

var foo = {
    getFoo() {
        return message;
    }
};

export default foo;


// bar.js - dependent on foo.js 
let message = '';

var bar = {
    init(obj) {
        let foo = obj.getFoo();
        message = `${foo}bar, and I am foonky`;
    },
    getBar() {
        return message;
    }
};

export default bar;


//app.js
import foo from 'modules/foo';
import bar from 'modules/bar';

// inject dependencies
bar.init(foo);

console.log(bar.getBar());


 

Please let me know what you think about it!

-----------
Update: I have experimented with an alternative to the examples in this blog. Have a look at it and please share your thoughts and feedback on the different approaches to unit testing modules:
Test friendly JavaScript modules - without Dependency Injection

-----------