Immutable Javascript

There are very good reasons to use immutable objects in certain languages. In Javascript however I’m still kinda meh. What are immutable objects? Basically it means that you are always creating new objects or entire data structures instead of making individual changes to objects in the same data structure.

The biggest reason for immutable objects is that they’re thread safe. This may make sense in some languages but since javascript is single threaded this doesn’t really apply. And when you use web workers to take advantage of multi-threading you’re using a messaging interface that helps to keep you out of trouble with the state of your objects.

Other arguments for immutable objects are to avoid temporal coupling and defensive copying.  Temporal coupling is an anti-pattern in which two actions are bundled together into the same just because they happen to occur at the same time. However, you can just as easily avoid it with either mutable or immutable objects. I don’t get the ‘no defensive copying’ argument because with immutable objects you ARE creating a complete copy.

Facebook’s React is a popular view framework that’s the V in MV*. They also have a library for models called immutable.js.  For React it makes some sense to use immutable.js.  React uses the observer pattern to update the view on a change to it’s model. Whether you like React or not there is some simplicity in not having to write specific binds between the model and view.  And the expensive process of observing all objects isn’t impacted by replacing the entire model through immutable.js.  There can also be some marginal performance improvements with this particular stack. With other MV* libraries however, you already have a model with its own methods and way of binding the view to the model. I think immutable javascript makes some sense for React apps but only depending on the application. Sometimes native objects make more sense for React apps, not just for performance, but because you can use native arrays with a much more extensive list manipulation library like lodash.js

In conclusion I’m really not sold on immutable objects in javascript, except in certain React apps.

 

 

 

Cleaning up boilerplate backbone views

And you think you’re so clever and classless and free

— John Lennon

One common complaint developers have with Backbone is the proliferation of repetitive boilerplate code. How many Backbone apps have a view like this declared over and over?

var MyView = Backbone.View.extend({
el: ‘#someId’,

template: _.template($(“#myTemplate”).html()),

model: myModel,

render: function() {
this.$el.html( this.template( this.model.toJSON() ) );
this.stickit();
return this;
}
});
This isn’t a problem inherent with Backbone, but a problem with developers writing repetitive boilerplate code. One possible solution is to use one of the opinionated frameworks that extend Backbone like Marionette, Chaplin, or Thorax. These are perfectly acceptable solutions if you like how they do it. They aren’t always necessary though. Instead of extending all views from Backbone.View, do it once for a given model and extend all other views for that model from these view constructors.

var MySubView = MyView.extend({
el: ‘#someOtherId’,
template: _.template($(“#anotherTemplate”).html());
});

This way I only change the methods that need to be changed. Also note that I’m using backbone.stickit in my render. This will be in all my views for this but if I don’t have a binding method, it will be a noop. This is the kind of flexibility I get without having to rewrite a big ugly render method, unless of course I need to write a different render method.

var MySubView = MyView.extend({
el: ‘#someOtherId2’,
template: _.template($(“#anotherTemplate2”).html()),
render: function() {
this.$el.html( this.template( this.model.toJSON() ) );

var anotherView = new AnotherView().render();
var anotherView2 = new AnotherView2({
model: someOtherModel;
}).render();

return this;
}
});

This is how I would create a hierarchy of views, but for any of the terminal views like AnotherView(), I would extend this from MyView. This is the beauty of javascript’s prototypal inheritance. Objects inherit from other objects. Just like in classical inheritance I can add methods, but I can just as easily change them.

 

 

Compressing Angular Modules with Gulp

Modules are very important for large applications.  For these I typically use require.js and compress it with r.js. However, since Angular has it’s own module system I prefer to use it, and for the compression part I use gulp tasks.

<script src="../vendor/angular/angular.js"></script>
<script src="../vendor/angular/angular-ui-router.js"></script>


<!-- build:all -->

<script src="../app/app.js"></script>
<script src="../app/controllers/childState1.js"></script>
<script src="../app/controllers/childState2.js"></script>
<script src="../app/controllers/form.js"></script>

<!-- endbuild -->

 

var concat = require('gulp-concat');
var gulp = require('gulp');
var htmlreplace = require('gulp-html-replace');
var ngAnnotate = require('gulp-ng-annotate');
var rename = require('gulp-rename');
var runSequence = require('run-sequence');
var uglify = require('gulp-uglify');



gulp.task('compress-js', function() {
 gulp.src('./dist/debug/public/app/**/*.js')
 .pipe(ngAnnotate())
 .pipe(concat('modules.min.js'))
 .pipe(uglify())
 .pipe(gulp.dest('./dist/minified/public/app'));
});
 

gulp.task('replace-script-tags', function() {
 gulp.src('./dist/debug/public/app/application.html')
 .pipe(htmlreplace({
 'all': '../app/modules.min.js'
 }))
 .pipe(gulp.dest('./dist/minified/public/app'));
});

Simplifying vs Complicating Performance Optimization

Simplifying your code for performance can and should be done throughout development. Complicating your code for performance should only be done after profiling has been done and bottlenecks have been identified.

During the entire development process it’s good to constantly refactor.  Reducing all extra steps and other cruft in a programs logic can not only improve performance but it makes your code more readable and decreases file size.  Reducing it to it’s poetic essence isn’t what the Knuth was talking about when he said “Premature optimization is the root of all evil.”

Once the code is working and perfomance analysis is done (I use dynatrace), certain bottlenecks appear.  Optimizing these issues sometimes requires complicating your code in order for it to perform better.  Here are some examples from a nice post by Doug Avery.  Replacing jQuery with native javascript can take out extra executions in a heavily trafficked loop but at the cost of increasing your code and making it less readable.  That’s why it’s critical that you only do this complicating type of optimization after performance analysis has been done and bottlenecks identified.