Tag Archive for javascript

Pallet Town: Giving Into Javascript Classes

Coder Radio listeners will know that I have some strong feelings on classes in Javascript and most of them are pretty negative. After some extensive time (measured in years) of exploring alternatives to pure Javascript such as CoffeeScript and Typescript, I ended up going back to pure Javascript but remained Typescript curious. That takes us to the present day. I find myself working on a very large, feature rich, and complex Javascript codebase that other people will eventually be working on with me. I’ve long railed that classical inheritance has no place in Javascript, but the reality of the situation is that it makes sense for some use cases and (a much more severe issue) most developers you’d hire out of school and sadly many more experience ones have no frame of reference outside of the classical OO as seen in languages like Java and C#.

Presented with this combination of issues, I naturally looked to include some Typescript classes in my code for some underlying data structures that the software is going to rely on. Unfortunately, I hit a pretty fast issue — require statements. My code base is based on Node.js and uses require heavily. In simple cases, that’s no problem in simple cases:

var Pokemon = require('pokemon') // Javascript

import Pokemon from 'pokemon' // Typescript

That’s not so bad, but things can get a little less elegant very fast. For instance, let’s say you’re using MongoDB and importing it via require:

var MongoClient = require('mongodb').MongoClient

There are of course ways to do this but none of them were elegant and simple enough for my tastes. As an aside, if your application uses MongoDB via the Mongoose driver, then you’re good to go with this Typescript statement:

import * as mongoose from 'mongoose'

My application, however, is using the Mongo driver directly and for some business specific reasons this was not an option, so I said ’so long to Typescript’ for this project and looked for another solution to my classical OO problem.

The solution I landed on was using the class functionality introduced in Javascript in ES6. Let’s take a look at a sample of what this might look like assuming that were are working on a Node.js based application that needs to pull in Mongo in the same way that my real world one does:

// importing Mongo
var MongoClient = require('mongodb').MongoClient;
var mongo_url = 'some_url_for_database_access';
// class declaration
class Pokemon {
	constructor(name, type, level) {
		this.name = name;
		this.type = type;
		this.level = level;
	}
	
	save(callback) {
		let pokemon = this;
		MongoClient.connect(mongo_url, function (err, db) {
			if (err) throw err;
			db.collection('pokemon').insertOne(JSON.stringify(pokemon), function (err, result) {
				if (err == null) callback();
			}); 
		}
	}
}
module.exports = Pokemon; // exporting for use elsewhere

That’s a pretty simple implementation but is enough to get a good idea of the basic structure of Javascript classes. One aspect that I am finding interesting about working with them is that it’s possible (and as far as I can see a good practice) to use them as sparingly as possible, hopefully avoiding the deep coupling between classes that tends to occur in large scale applications written in a classical OO style. So far, my thinking is that these types of classes are appropriate for base data structures that your application relies on, but the majority of your code should be written in a more functional style.

I hope this helps and if you want to reach out please find me on Twitter and if you’re interested in seeing something cool pretty soon check out The Mad Botter.

Hybrid Today, Progressive Web App Tomorrow

App (and I am using that term very loosely here) development has undergone a change. Most companies are eschewing high cost native development and for iOS and Android and going with hybrid solutions using tools like Xamarin or Ionic. This is a great way for organizations to lower their initial development and ongoing maintenance costs as well as get a useful app for their business needs. One area that many organizations are finding is that they still need desktop web applications and you don’t get the code sharing advantages between mobile and desktop platforms that you do between the two dominant mobile platforms – iOS and Android. Luckily, the march of development tools and frameworks has carried on and there’s a new solution – progressive web apps. These are web applications that live on the server but thanks to powerful JavaScript (or in some cases Typescript) can access native-like device capabilities. This, coupled with responsive development techniques and some adaptive CSS allows the app to scale in not only screen-size but also capabilities depending on the device. There are a number of frameworks that provide this, but my two favorites are Angular 4 and Polymer 2.

The Angular team now uses the tagline “one framework, mobile and desktop” and they mean it. Angular has come a long way from the original release of AngularJS and is now a full application development framework.  Currently, Angular is on version four and if you’ve used an older version of the framework you’re going to find major differences (especially in the area of routing) but the time invested into catching up is well worth it. Using Angular 4 you can now create a high-functioning application that runs on everything from your twenty-seven inch desktop screen all the way down to a mobile phone. I do find that there’s a bit more ceremony in the latest versions of Angular than in the first, but you could argue that’s an advantage, since it also makes the framework more flexible than its predecessor.

Polymer 2 is more focused on JavaScript components than Angular but is no less powerful. While the details of it works under the hood are different the end result is exactly the same — you end up with a powerful application that can scale for different screen sizes and devices.  If I had to make a comparison between Angular and Polymer 2, it would be that the Polymer team has made more of an effort to be “pure JavaScript.” I don’t love that criticism of Polymer for two reasons: 1) Angular is now written in Typescript and I (in my opinion) best consumed using Typescript and 2) some of the custom directives in Angular actually lead to less boilerplate than the more “pure JavaScript” alternatives in Polymer (especially around defining custom components), so I’d actually consider that a feature for Angular rather than a bug. Still, that doesn’t mean that Polymer is not a great choice for your progressive web app development needs.

There are of course other choices for developing progressive web apps but these two projects have the backing of Google and large communities around them, so they’re likely going to stand the test of time unlike the many <insert_noun.js>  JavaScript frameworks of the previous ten years.  The future looks bright for the progressive web app and by extension Angular and Polymer, given that the trend of businesses demanding more for less out of their developers and development partners is likely to continue.

If you liked this post, follow me on Twitter for more!

How I Missed Web Assembly

As pointed out by an intrepid Coder Radio listener, I totally missed the importance of Web Assembly when it was in its initial nascent phases a year or so go. Now that Web Assembly is going to become a standard endorsed by the W3C and has backing from at least two major browser vendors to date (Google and Mozilla), I’ve done a full 180 and am convinced it is the future of not only web development but probably a good deal of mobile and desktop development as well; my assumption is that tools like Ionic and Electron will be able to leverage the performance gains brought by web assembly as well.

Looking back my mistake was that I failed to parse out the signal from the noise in the wider JavaScript conversation circa 2014 and on. There was (and in many communities still is) a lot of angst about the short-comings in the JavaScript language and a lot of people making noise about using alternatives to it that would simply compile to it –  CoffeeScript and TypeScript for example. There was of course a thread in the background about Web Assembly becoming potentially a language agnostic solution to this problem, but because I was looking at it through the lens of alternative languages to JavaScript and at the time didn’t think and I still don’t think  that changing from JavaScript just because you want a different language but then compiling into JavaScript makes any sense at all. In other words, I took a breathe and shouted a hearty “get off my lawn!”

My curmudgeon-like tendencies aside, I still firmly standby the idea that just writing in something like CoffeeScript to compile into JavaScript just because you don’t some features or shortcomings of JavaScript is silly. What I missed was that this whole language brouhaha was just a minor prologue to the real story — Web Assembly. Moving to Web Assembly not only increases web application performance significantly but also (as more languages create compilers for it) gives those developers who prefer some language over JavaScript a much more reasonable choice; they can simply use the language of their choice and compile it directly to Web Assembly! I’m totally on-board with that. In fact, I’ve been working in Microsoft’s TypeScript and find it great, so if we actually make it (we probably will) to this Web Assembly world, then I’ll probably go Typ eScript for most greenfield projects going forward.

As in Eden, there’s a potential snake in our garden — Apple. Web Assembly being fully supported on mobile Safari for iOS is absolutely necessary to unleash the full potential and development efficiencies that I believe Web Assembly can over the next five year period bring.

Questions? Comments? Blood curdling nerd rage? Tweet me! Also, take advantage of my free strategy session for your next project!

The Javascript Problem

Earlier this week Microsoft unveiled its brand new web programming language Typescript. If you don’t know what Typescript is or what features the language has, please take a look at Anders Hejlsberg’s great introductory video. Also, take a look at the Typescript ‘playground’ that Microsoft has posted if you haven’t tried the language at all; it is similar to the interactive console that Ruby has had online for a while. The big question that keeps getting asked is why yet another web development language? The ugly truth is that there is a serious problem in the web development space: a good portion of the Javascript code out there and that is currently being written is terrible.

Some people blame Javascript itself. Others feel that it is a fine language and the real issue is the developers working with it. I  agree with the second statemet to a point. I do agree that a lot of the blame for the current state of affairs can be easily laid at the feet of a large portion of the web development community, but I don’t think that helps or is productive in addressing the issue of poor code quality on the web.

The truth is your average developer knows Java or some Java-like language like C#. That means classical inheritance. It also means that most developers have been trained to think in a object oriented way and for these devs object orientation means classical inheritance. Javascript’s prototypical inheritance model is as foreign to them as functional programming. So, what ends up happening is that these developers end up trying to force what they know on Javascript and things get messy.

To be fair, we’ve tried to address some of the uglier issues in a Javascript development by developing tools designed to add some more discipline to the workflow. Still, we can’t seem to agree on if these tools are even valuable or what ones to use. Should client side Javascript be unit tested? If so, is JSUnit the tool for the job? Ask that question on a forum of web developers and watch the sparks fly. All this division does is further confuse our poor transplanted Java dev. Also, none of these tools actually do anything to change the nature of the language nor do they re-train the dev.

Ah training! Education! That’ll fix all our problems… right? Wrong. Take a look at O’Reilly or any other tech publisher’s Javascript offerings. They are publishing books on developing with the language at a furious pace. Certainly, there are more than enough texts out there for aspiring web developers to learn the intricacies of the language. Unfortunately, that is not a realistic hope and doesn’t take into consideration the vast majority of software developers: Dark Matter Developers.

Let’s assume that getting all (or even a significant number of) developers to re-educate themselves for Javascript or even that they’d be willing to do so is unrealistic. A number of tools have already come out that allow us to write our code in a  classical object oriented language and have it compile down to Javascript such Script# (C#) or the Google Web Toolkit (Java). Unfortunately, there have been a few problems with that approach; chief among them is that you often have to know Javascript to debug the generated code.

Ok, I’ve posted a lot of what we can’t or shouldn’t do here, so let’s get proactive! We can replace Javascript with an object oriented language that follows classical inheritance. Blasphemy! I know this sounds crazy but it makes sense when you consider that the size of the web is growing at an exponential pace and our clients / customers are going to expect increasingly rich and sophisticated web-based experiences as the HTML5 trend continues to grow. The need for a replacement language that is friendlier to the wider development community becomes more pronounced when you consider the fact that there are not enough of us Javascript literate developers to handle the coming / current workload.

Thoughts? Comments? Blood boiling rage? I’m happy to hear all feedback on Google+, Twitter, or App.net.

JavaScript is Not Assembly!

There is a growing idea on the web that JavaScript is somehow the assembly language of web. This is a horrible analogy for a number of reasons: it shows a misunderstanding of what assembly language is, implies that JavaScript is not a human readable language, and it  suggests that JavaScript is a far lower level language than it is.

According to Wikipedia, “An assembly language is a low-level programming language for computers, microprocessors,microcontrollers, and other programmable devices in which each statement corresponds to a single machine language instruction.” That doesn’t sound like JavaScript to me. Let’s keep reading and see what else Wikipedia has to say about assembly: “ An assembly language is specific to a certain computer architecture, in contrast to most high-level programming languages, which may be more portable.” Therefore for JavaScript to be considered an assembly language wouldn’t it have to target a specific computer architecture (such as i386 or ARM). Taking this to its logical conclusion, that would mean that for the JS == assembly relationship to work, you would also have to think of different browsers and JavaScript runtimes as different architectures. If that sounds crazy to you, that’s because it is. The analogy is broken just based on the definitions and essence of what assembly and JavaScript are respectively.

JavaScript gets messy. There is no doubt about it. Due to years of abuse by sloppy “devs” (who probably were more closely related to what today would be called an “Interactive Designer”) who didn’t treat it as a proper programming language but rather a little hack to get some fancy animation on a web-page. What does that have to do with assembly? Well, assembly is known to be very hard for humans to read; yes, I am fully aware that there are a number of hardcore individuals who can read and write assembly, but on the whole they are the exception not the rule. Guess what! JavaScript isn’t inherently hard to read. All this complaining about it being a tangled mess of crap is not the fault of the language but the fault of the dev and trying to force some analogous relationship with assembly onto it does not give you some sort of excuse for writing unmaintainable and hacky code.

Did I mention that assembly is low level  “down to the metal” sort of language? Guess what JavaScript isn’t? Ding ding! Well, done! JavaScript is not low level. While your C++ code is compiled to assembly and ran on your iPhone’s lovely ARM processor, your JavaScript is run in a JavaScript engine such as V8 in your web browser. Looks like JavaScript is running at something of a higher level.

My purpose here is not to beat up on the JavaScript detractors. The language (like all languages) could use some work, but adding an unneeded layer of abstraction over it is not going to bring the change the language needs. Standards bodies are slow, but you can “be the change you want to see” (Gandhi). Instead of abandoning it for some questionable layer of abstraction, use the great features in JavaScript, ignore the bad, and write maintainable code. If we all did this we’d find that over time the web would be a better place to work and JavaScript would be a better language to work in.  Not sure what the good parts are? Check out JavaScript the Good Parts. Got some feedback for me? Find me on Twitter or Google+. Also, check out my show Coder Radio on Jupiter Broadcasting. It is a weekly show on the art and business of software development.