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?

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;

import foo from 'modules/foo';
import bar from 'modules/bar';

// inject dependencies



Please let me know what you think about it!

tisdag 21 oktober 2014

Programmer friendly web analytics with _tics.js

_tics.js a simple JavaScript helper library for writing web analytics client side code. It supports basic page tracking and also event tracking for form fields, buttons and links.

_tics.js is intended to give you a head start with web analytics and it supports the Google Universal Analytics JavaScript library out of the box. Included is a Google Analytics provider, written as a separate module. It can easily be replaced by a custom provider consuming your favorite web analytics tool. 

The source code is on GitHub.


Basic - The "it just works" scenario
Activate _tics.js by calling the page() function. Run the events() function if you want to track form fields.

Basic live example here (jsFiddle)

More features - The "couldn't you just do this?" scenario
The library includes three specialized functions. The functions are activated when elements are decorated with the attribute data-val-analyze-custom. The included functions are:
get the value of a field (getValue)
get the relative change within a field (getRelativeChange)
get the position of a clicked link in a list of banners or in a menu (getItemInSection, combined with the attributes data-section and data-item)

More features live example here (jsFiddle)

Customization -The "extra special for you" scenario
The getValue, getRelativeChange and getItemInSection functions are included in _tics.js. But you can also add your custom function by appending them to the library. Use your favorite library for traversing the DOM if you like.

If you want to override or hijack one of the existing functions, just call the add function and use the same name as one of the built in functions. You can also add any event that is not covered by the built in features.

Customization live example here (jsFiddle)

The source code is on GitHub. Let me know what you think about it!

fredag 19 september 2014

nordic.js reflections

nordic.js - like a two day Spa experience. Starting at the registration line, with fellow JavaScript geeks, on a foggy morning in Stockholm. The boat took us to the lovely place of Artipelag, welcoming all of us with soap bubbles. Lots of soap bubbles. Now that's how to start a conference! Good job, nordic.js folks. By lunch I actually had time to stroll by the board walk and the woods (yeah, trees & sh*t).

Suddenly, from nowhere, I heard weird sounds. Was someone singing? Was there a bird or something? A gnome? I don't know, but it inspired me to record a smart phone arty short film. No, I wont quit my day job. Promise.

What about the talks? Well... Douglas Crockford was there. That was worth every swedish kronor.

I wanted to call out: "- I Love You, Douglas Crockford!!!!!", but I'm swedish, so I laugh by exhaling air from my nose really fast.

There are some talks left today, but I want to thank the team of really creative people that arranged the nordic.js conference. You paid attention to details and the big picture, making this a nice experience. Next time I hope there will be more of live coding, passion and less code-on-powerpoint on stage. After all, we're all geeks that love code!

fredag 29 augusti 2014

Easier virtualization with Chocolatey & Vagrant - the minified version

Yesterday I talked about and used some Open Source tools with funny names. They are not only funny, but also useful in the everyday life of a software developer. I talked about how tools like Chocolatey and Vagrant can make virtualization (a whole lot) easier, and automated.

This video is a minified version of the talk (about 20 minutes) and it is in Swedish. You will find the configuration files and scripts used in the demo at my GitHub page right here.

Let me know if you have any questions or feedback about the talk!