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.

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!

Three Tech Wishes for 2017

Happy 2017! As we put 2016 in the rearview mirror, we’re all taking a look at the outlook for 2017 as I did here but I wanted to take a more personal angle here and explore what I desperately want to see from the tech community. This list is by no means exhaustive and for the sake of time (and online attention spans) I’m limiting it to my top three.

Google Account Management: Dealing with multiple Google accounts is an unfortunate and annoying fact of life for me both as a regular user and as a developer. In this year alone I’ve probably written thousands of lines of code for myself and for clients to deal with this problem by basically scraping calendar events between two or Google accounts. The business case for this problem is pretty simple. Company A gets a contract to do some work but they don’t have the resources in house, so they subcontract part (or all) of the job to Company B, but Company A doesn’t want the client to figure out that Company B exists and is actually doing the work, so they give all the Company B people Company A Google accounts. My event scraping solution is sloppy and fraught with all sorts of little issues. Google should find a way to implement some sort “vanity account” system that let’s the actual email addresses be masked between multiple domains, so that the customer sees what Company A wants them to, but Company B doesn’t have the overhead of dealing with yet another GMAIL account.

Reactive Programming Hype: A lot has been made of Reactive Programming in 2016. While there is definitely some fire to the smoke, things are getting way too hyped and frankly I’m seeing Jr developers pitching reactive programming on freelance gigs as some sort of silver bullet that will solve all the problems you have have and even ones you don’t know you have yet. This is scary! Sure there has always been hype around “new” (sneer quotes because Reactive Programming is only new from a ‘certain point of view’) technologies and methodologies but this hype train around all things with the word or root ‘react’ in them has the kinetic energy of ten hydrogen bombs. I’ve gotten too many projects in this year from prospective clients that were over-engineered in one of these reactive libraries by some Jr dev who just got a little too excited on the Kool-Aide sales pitch and the story is sadly all the same – the client was happy with what he was told but what he got was a steaming pile of hard to reason about spaghetti code and ultimately a rewrite. For 2017 let’s just pull the cord a little on the hype train, OK?

Docker Direction: Despite some fairly significant pain in upgrading between Docker versions and other more minor issues, I am still a serious believer in Docker as the premier containerization solution. Coder Radio listeners will remember that even as a callow youth I was on the Docker train right from the beginning but my faith has been somewhat shaken and I’d like some clearer communications regarding where the technology is going, who they feel their ideal target users are, and where Docker the company sees its role beginning and ending — in other words where will they and where won’t they compete with vendors who are selling / implementing Docker.

Those are my three (I hope fairly doable) wishes for 2017, but before I go…. I also want to note what I didn’t mention here that I have in my end of year / new year posts for the last years – App Store monetization and more specifically a sign from Apple on where they see that going. We got our answer in 2016 – subscriptions. While that will work for a number of apps and is working fine for my Backpoints (iOS & Android), it does not satisfy all the needs of independent developers and likely will not create the high-value ecosystem of professional paid (paid defined as taking money in any non-donation way) software that the iOS App Store originally enjoyed. When I think about Apple and their answer to the monetization issues on the App Store, I am remained of that great quote from Dan Brown’s Angels and Demons: “God answers all prayers, but sometimes his answer is ‘no’.”

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.