The History and Future of Java Programming Language

As the internet’s renowned programming language, Java has had a profound impact on how people navigate the digital world. Much of what users expect in terms of performance from their devices that access the internet has been set by Java functionality. You don’t have to be a developer, however, to recognize its influence.

The story of Java goes back more than two decades and has evolved along with the digital transformation of the world. As consumer and business demands on scalability increases, Java is forced to grow and adapt in order to stay relevant. Stakeholders are approaching their work armed with a primer on Java’s history, current use, and future direction.

The History of Java: A Timeline

Early Development

Java is the brainchild of Java pioneer James Gosling, who traces Java’s core idea of, “Write Once, Run Anywhere” back to work he did in graduate school.

After spending time at IBM, Gosling joined Sun Microsystems in 1984. In 1991, Gosling partnered with Sun colleagues, Michael Sheridan and Patrick Naughton on Project Green, to develop new technology for programming next-generation smart appliances.

Gosling, Naughton, and Sheridan set out to develop the project based on certain rules. They were specifically tied to performance, security, and functionality. Those rules were that Java must be:

  1. Secure and robust
  2. High performance
  3. Portable and architecture-neutral, which means it can run on any combination of software and hardware
  4. Threaded, interpreted, and dynamic
  5. Object-oriented

Over time, the team added features and refinements that extended the heirloom of C++ and C, resulting in a new language called Oak, named after a tree outside Gosling’s office.

After efforts to use Oak for interactive television failed to materialize, the technology was re-targeted for the world wide web. The team also began working on a web browser as a demonstration platform.

Because of a trademark conflict, Oak was renamed, Java, and in 1995, Java 1.0a2, along with the browser, name HotJava, was released.

Developer Reception

Java was well-received by developers in the software community, in particular because it was created based on the “Write Once, Run Anywhere” (WORA) philosophy. This flexibility is rooted in Java’s Bytecode compilation capabilities, which bypass the potential barrier of different system infrastructure. Java was a unique programming language, because it essentially solved portability issues for the first time in the industry.

For a brief period of time, Java was available for open source use. Sun Microsystems made the switch in 2006 in an effort to prevent fragmentation in the market and to appeal to developers who worked primarily in open source platforms. This was short-lived, however, as Oracle reduced that effort and reverted to commercial licensing when it took over Sun Microsystems in 2010.

Java’s age and pervasiveness means most programmers have encountered it at one time or another, if not as a fulltime career. Given this large user base there are inevitable differences of opinion about whether Java is still relevant.

Developers seem to be exploring other options besides Java. According to the September 2016 TIOBE Index, the popularity of Java as a programming language is on a decline. However, it still reigns as the most widely-used language, surpassing .NET and maintaining their top-ranked position from previous years.

Strengths of Java

As a developer, you may already realize the advantages of using Java, which help explain why Java is one of the leading programming languages used in enterprise today:

  • Garbage Collection – Languages such as C and C++ require you to manually clear created objects, a stark contrast to Java’s built-in garbage collection.
  • Verbose, Static Language – Thanks to Java’s robust, inherent static nature, it’s easy to maintain and read. Java enables you to return multiple types of data and you can easily use it in a variety of enterprise-level applications.
  • Portability – Collaborative automation tools such as Apache Maven and open source are all Java-friendly. AppDynamics is no exception: understand the health of your JVM with key Java tuning and profiling metrics, including: response times, throughput, exception rate, garbage collection time, code deadlocks, and more.
  • Easy to Run, Easy to Write –  Write Java once, and you can run it almost anywhere at any time. This is the cornerstone strength of Java. That means that you can use it to easily create mobile applications or run on desktop applications that use different operating systems and servers, such as Linux or Windows
  • Adaptability – Java’s JVM tool is the basis for several languages. That is why you can use languages such as Groovy, Jython, and Scala with ease.

Weaknesses of Java

Even though Java has an array of strengths, this imminent programming language still has it’s challenges:

  • Not a Web Language – The amount of layers and tools, such as Struts, JPA, or JSP, that is needed to create web applications takes away from Java’s intentional design of ease of use. These additional frameworks have their own issues and are difficult to work within.
  • Release Frequency – With each change in the runtime, developers must get up to speed causing internal delays. This is a nuisance for businesses concerned with security, since Java updates may cause temporary disruption and instability.

The Next Evolution of Java

Java is not a legacy programming language, despite its long history. The robust use of Maven, the building tool for Java-based projects, debunks the theory that Java is outdated. Although there are a variety of deployment tools on the market, Apache Maven has by far been one of the largest automation tools developers use to deploy software applications.

With Oracle’s commitment to Java for the long haul, it’s not hard to see why Java will always be a part of programming languages for years to come and will remain as the choice programming language. 2017 will see the release of the eighth version of Java —  Java EE 8.

Despite its areas for improvement, and threat from rival programming languages like .NET, Java is here to stay. Oracle has plans for a new version release in the early part of 2017, with new supportive features that will strongly appeal to developers. Java’s multitude of strengths as a programming language means its use in the digital world will only solidify. A language that was inherently designed for easy use has proved itself as functional and secure over the course of more than two decades. Developers who appreciate technological changes can also rest assured the tried-and-true language of Java will likely always have a significant place in their toolset.

Learn More

Read more about Java Application Performance Monitoring.

Javascript: Beyond Just Web Apps

The age of computers is over. You are now living in the age of intelligent processing by just about everything else. Like vacuum tubes and tape drives, desktops and laptops are on their way to becoming odd relics of a distant age, if people remember them at all. That may sound a bit extreme, but the fact is that applications are not married to any technological substrate, not even the most advanced mobile devices. That is why smart developers have already turned their attention to using JavaScript for building out next-generation technology like drone controllers, big data management tools, and connectors for the Internet of Things (IoT).

The World After Web Apps

In Fabio Nelli’s “Beginning JavaScript Charts: With jqPlot, d3, and Highcharts,” he starts off by saying “JavaScript is experiencing a rebirth as a result of the new libraries developed precisely to take advantage of the innovation introduced by HTML5.” He is referring to the way JavaScript makes full use of the next-gen browsers with their new rendering engines. This rebirth is also true in the larger sense that JavaScript is being used to control a wide variety of innovative technologies, such as:

  • Drones – The Parrot AR drone quadcopters are recreational, but they point the way to the future. You can operate it with an app on your Android or iOS phone using Wi-Fi, and you can go further with Node.js. GitHub houses code repositories for controlling the camera or setting off a series of commands.

  • Data modeling – Most people you ask would describe Angular.js as a structural framework to enhance HTML for web apps. It specifies guidelines for directives, controllers, and services, but can also simplify data modeling in the way it binds JavaScript objects to properties. Look over this approach to building rich object models using Restangular for nested models.

  • Health care applications – The need for better data management is driving more healthcare organizations to look for full stack JavaScript developers. They want JavaScript specifically due to its facility with carving out original reports based on data modeling, data aggregation, data export and manipulating data in various ways.

  • Finance and statistics applications – By all accounts, R is the preferred language for statistics and financial applications these days, but there are several good reasons why some developers have decided to stick with JavaScript. It is easy to share code; it is easy to create output in an aesthetic format that’s simple to understand. Statistics blogger Matt Asher tested the time it took to create 10 million standard Normal variates in R vs. JS on Chrome. He found that “In Chrome, it took about half-a-second, same as in R (in Firefox it took about three times as long). Got that? No speed difference between R and JS running in Chrome.”

  • Self-driving cars – Programmable autonomous vehicles and connected cars are closely related developments. Many are already connected, but when there is nothing to do but ride along, connectivity will need to offer more value. According to Analysys Mason, nearly 90 percent of new cars will have embedded connectivity. By that point, there should be more than 10 million self-driving cars on the road as well. Fortunately, JavaScript already knows how to drive cars, based on millions of simulated events in driving games. Take a look at this AI car simulator that was built on the Unity 3D game engine using Node.js.

  • IoT devices – IoT is all about “connecting the unconnected.” It just makes sense to use the language with the most options for making those connections. JavaScript’s extensive connective tissue includes libraries, plugins, APIs and various other tools to connect random devices into the wider networks. There is a growing repository of npm modules for client-side, server-side and edge of network applications. This may be the primary reason why JavaScript developers cannot put it down.

The Versatility of JavaScript

Over two decades, JavaScript has been stockpiling utility libraries like Underscore.js or lodash that directly handle some of the most common programming issues, like map and sortedIndex.

JavaScript was built to handle event-driven applications that need to execute non-blocking code. For example, the Node.js event loop will execute code without having to wait for existing code to return a result. As tasks send their callbacks as notifications that they have completed processing, Node.js can respond as defined.

This is ideal when handling multiple IoT devices that are sending back their responses independently, or when activating multiple systems based on a single response.

Other Popular Language Options

JavaScript certainly isn’t the only game in town. Here are some other leading languages for each of these fields:

  • Drones – Consumer drones are getting more sophisticated, and Arduino is one of the easiest ways to control them. It is not a language so much as a series of commands for hardware, but that is sufficient for blinking lights and simple commands that people want drones to carry out.

  • Data modeling – Python comes in at number four in the top 10 programming languages, partly because it so useful for data modeling and with big data. In comparison, JavaScript comes in at eighth place. As big data gains wider use among a larger base of smaller firms, both languages are likely to climb higher.

  • Healthcare applications – SQL is the traditional choice for data management in health care, especially those still reliant on relational databases. On the interactive web side of this equation, coding skills with Java and ASP.NET remain in demand.

  • Finance and statistics applications – As mentioned above, R has become the darling of scientific statistical researchers and ambitious finance coders. The high stakes competitive financial world is a good place for R to show off its most powerful features. The newness of the language means that it is hard to tell whether interest will drop as fast as it rose.

  • Self-driving cars – Sebastian Thrun, who led the launch of Google’s self-driving car project, is promoting an online course on “Programming a Robotic Car,” which contains lessons on Python and C++ language components among related technologies. As many have pointed out, the field of AI is expanding so quickly that languages are not as important as underlying concepts like probabilistic inference, visual systems, robotics tracking, and localization.

  • IoT devices – Many IoT applications are being developed in languages other than JavaScript. There is a broad range of older languages like C++ to the latest tools like Parasail, a parallel processing language with object-oriented syntax.

Which Languages Are as Versatile as JavaScript?

Versatility is just one of JavaScript’s core competencies. Its open structure, as well as the support it receives from tens of thousands of active developers, is another. Two more are its event handling and data interoperability. Everyone seems to have their favorite language, but it is hard to argue with this JavaScript assessment by Tom Benneche, an instructor at the Startup Institute Chicago: “JavaScript is supported by every major browser and is the only web programming language built for both client-side and server-side. For some time, JavaScript was strictly a front-end language, but with the advent of Node.js and other similar platforms, it has become not just a viable back-end option, but a formidable one. Building a development team is much simpler because your entire technology stack can be built around one language.”

The JavaScript Future

JavaScript has a long future ahead as an extremely versatile language that has continually adapted to new technology. By 2020, it is likely that 1.4 million computing jobs will go unfilled due to lack of adequately qualified coders. When demand outstrips supply to that degree, people with the most versatile programming experience will command the greatest value on the market. The job market has already started to register massive increases in salaries for front-end web developers around the world. As innovative technologies like IoT take off, they will need more connective frameworks like JavaScript to bring them together.

With a devoted following, broad applicability and a supportive community, JavaScript is positioned to take advantage of whatever comes next. It is already pulled out ahead as one of the go-to languages in fields from data modeling to IoT. As long as the web is around, it is probable that JavaScript will be there to build web-facing applications. In the near future, you might want to use Apache server and Raspberry Pi for analyzing data gathered by sensors that run on Arduino. What would you use as a framework to hold it all together? JavaScript, of course.

Comparing the 4 Most Popular Client-Side JavaScript Frameworks

The world of JavaScript frameworks continues to evolve at a fever pitch. Early tools like Mootools continue to thrive while new players like AngularJS and EmberJS burst onto the scene and make significant inroads quickly. Even newer frameworks are appearing on the horizon. In this article, you’ll get an overview comparison of popular client-side frameworks – when they started, who developed them and what need they fill in the current computing environment.

What Is a Front-end Browser Framework?

A front-end browser framework is a framework or group of utilities that makes it easier and faster to produce JavaScript that is compatible with multiple browsers and devices. By completing a project in a framework, you can be reasonably sure that the code will work across a spectrum of platforms and browsers. Also, frameworks speed up development by providing preconfigured libraries, so you do not have to think about assembling your own. Ajax and other functionalities are already handled by the framework so you can concentrate on the logic of your application.

Frameworks can be especially helpful for large applications that require many interactions and lines of code. Different frameworks tend to be better at certain things than others. For example, AngularJS is ideal for declarative programming and extending HTML, while Backbone.js is useful if you are doing most of the implementation yourself.

Brief History of JavaScript Frameworks

As the need for cross-compatibility of web browsers grew and the desire to process page elements in the browser in real time became a bigger demand, JavaScript frameworks developed to smooth out the process and provide a standard set of methods, functions, and controls. Early popular JavaScript frameworks included Prototype, YUI, ExtJS, MooTools, and jQuery. These frameworks allow developers to create shortcuts to working with elements in the Document Object Model (DOM).

Later frameworks like AngularJS and EmberJS developed to meet the demands of the current computing environment: the rise of mobile devices and the challenges of single-page applications. In a single-page application, all of the code needed is included in a single-page load. This includes all of the CSS, HTML, and JavaScript. The page does not reload, and it requires dynamic interaction with the Web server.

Also, modern browsers that incorporate HTML 5 let you move the logic for the application and user interface from the server to the client. JavaScript frameworks reduce the amount of code you need to write. Some of the more popular frameworks today include AngularJS, EmberJS, ReactJS, and BackboneJS.

AngularJS

A client-side framework, AngularJS incorporates user interface data binding. The data binding is bidirectional: whenever the model changes, the view is automatically updated. In turn, the model updates if the view is changed. The HTML is compiled in the browser and is rendered in the live view on the fly.

This contrasts with the traditional HTML programming setup, where the model and controller talk to the server to create new views. With AngularJS, the model and controller are handled by the browser. In other words, you can deliver new pages to a user without interacting with the server.

Angular was created by Misko Hevery in 2009. It was developed to run an online storage service. In time, this original commercial intent was abandoned, and it was released as an open-source library.

Backed by Google, AngularJS is one of the most popular frameworks on the market. Although it was a big improvement over earlier frameworks, Angular made a decision that almost killed it. To have the most recent, powerful code, AngularJS 2.0 was designed in such a way that it was nearly impossible to reuse any code from the original version.

As you can imagine, this upset many developers. The Angular team ultimately came up with a creative solution by figuring out a way that code from both the 2.0 and 1.0 versions could be run at the same time. This innovation almost certainly prevented the framework from a major setback.

AngularJS strengths include a high-performance, easy-to-test, native GUI, robust libraries and server-side rendering. Weaknesses include poor documentation – although this is being aggressively improved – and challenges in finding resources. Angular is most productive when new projects are started with the latest 2.0 version.

EmberJS

EmberJS is an application framework that works with the model-view-controller arrangement. You can build highly scalable, single-page apps by utilizing Ember’s two-way data binding, templates that update automatically, rich object model, computed properties and router for handling application state.

EmberJS is positioned as a framework for big projects with lots of vision. For example, Ghost is a blogging platform that is taking on WordPress at its own game. Similarly, Discourse is a reimagining of online forums. Both projects are built with Ember. Other sites using Ember include Groupon, Nordstrom, Vine and Live Nation.

EmberJS began as a fork of a framework called SproutCore in late 2011. Yehuda Katz is the driving force behind Ember and has been an important member of the teams behind Ruby on Rails and JQuery. Unlike React and Angular, which have a large company behind them, Ember has chosen to work with a number of sponsors including Addepar, Yahoo!, LinkedIn and Bustle.

Ember’s strengths include high-performance, excellent documentation, server-side rendering, and tooling on the command line. Its weaknesses include a smaller community than other frameworks and its awkwardness when going outside its initial scope.

ReactJS

With ReactJS, data views are rendered automatically as HTML. This gives developers a system where data flows down, and subcomponents cannot alter enclosing modules. React is useful for creating single-page applications because it creates distinct separations between components on the page – the HTML is updated cleanly and efficiently when the data is changed.

Facebook developer Jordan Walke created React, and it was implemented there in 2011. Now open source, it is maintained by Facebook and a group of corporations and programmers. React can be found on sites such as Bleacher Report, SeatGeek, Feedly, Imgur, HelloSign, and Netflix. It is one of the top ten most “starred” JavaScript projects on GitHub as of May 2016, and one of Facebook’s premier open-source projects.

React is lightweight, and some don’t even consider it a full framework. It is ideal for rendering UI components and is often used with Flux, an application architecture used to create client-side web apps. This is different from the Model-View-Controller dynamic. It sends actions to the model layer from the view layer. It does not have the capability of talking to the server, adding dependencies or validating models.

React was built by Facebook to help them create more consistency in their user interface. It was an immediate hit because of its high performance and ability to render on the server. These are benefits both Ember and Angular are working hard to improve. React’s strengths include its simplicity, server-side rendering, native GUI and high performance. On the downside, it takes a little while to understand Flux.

BackboneJS

BackboneJS uses the model-view-presenter (MVP) design approach. Very lightweight, it relies on UnderscoreJS and jQuery for library elements. It is ideal for creating single-page web apps and synchronizing disparate elements of web applications that have clients. Backbone was built by Jeremy Ashkenas. A prolific developer, Ashkenas is well known for creating UnderscoreJS and CoffeeScript.

Backbone gives you many advantages. You can sync with a back-end easily. It has great support for RESTful APIs. You can map to an endpoint, and Backbone will access the API directly for operations. Even if the API is not RESTful, Backbone can handle it.

It is also good at maintaining clean code. Because it has clear coding conventions that are easy to follow, your whole team is more productive if they stick to the coding standards. The result is highly efficient, readable code. Also, because Backbone uses event-driven communication, you gain lots of control over every change in a view. Backbone events sit on top of DOM events, making it easy to tie views together and thereby providing excellent extensibility and versatility.

A wide variety of web apps have been created with Backbone. They include Airbnb, Foursquare, Hulu, and USAToday.com.

Powerful Tools

JavaScript frameworks are powerful tools for rapidly building web apps with full functionality. At the same time, no framework meets every use case or team application. Some developers refuse to use frameworks at all – they consider them too top heavy and too strict in their conventions, and they force developers to learn every new flavor-of-the-week framework all over again. Some are not regarded by some programmers to be frameworks. Rather, they consider them to be simply code libraries or a group of useful utilities.

Future of Frameworks

Whether they are considered full-bodied frameworks or not, AngularJS, EmberJS, ReactJS, and BackboneJS are in the middle of the white-hot changes taking place in today’s rapidly changing, high-speed, highly mobile world of computing. The variety of devices has exploded in recent years, and keeping up would be practically impossible without these frameworks to ease the burden.

Only a few short years ago, all you had to worry about was making a web page fit well in the browser displayed on an average monitor, making adjustments for archaic versions of IE that some still worked with. Now, the complexity is 100 times greater. Grab one of these frameworks to handle logistics so you can concentrate on features.

7 Ways ES2015 Can Improve Your JavaScript Programming

ES6 is a major update to the JavaScript language, the first since the adoption of ES5 in 2009. The features of ES6 are being incorporated into JavaScript engines around the web right now, and the changes are far reaching.

The new features in ES6 show how far JavaScript has come over the last two decades. Originally designed to define some functions and variables in order to build applications that could run in the browser, it continues to grow rapidly based on its flexibility and adaptability. ES6 contains new functionality that will move JavaScript to a whole new level of adoption and performance.

In this article, you will gain insight into the history of Javascript, how ECMA began to standardize its specification, the advantages of new ES6 features and some of the challenges the language faces in the future.

Evolution of JavaScript

ECMA, an industry association that began in the early 60s, is responsible for specifying the standards for JavaScript. Originally called the European Computer Manufacturers Association, it is now known as simply ECMA. JavaScript began life as a project named Mocha, which was created by Brendan Eich, who also co-founded the Mozilla Foundation. Mocha later became LiveScript and ultimately evolved into JavaScript.

JavaScript was a tremendous success as a scripting language for web pages on client programs. Netscape and Sun Microsystems released it officially in late 1995. A few months later, version 2.0 of Netscape Navigator came out on the market, including full JavaScript support. Microsoft shortly released their own version, avoiding trademark problems by calling it JScript, and bundled that into version 3.0 of Internet Explorer in the summer of 1996.

In late 1996, Netscape submitted JavaScript to ECMA International to set standardization specifications. ECMA-262, the first edition of the specification, was adopted in June 1997. Due to disagreements about standardization between Microsoft and Netscape, ECMA called their standard version of the language “ECMAScript.”

Six Major Releases of ECMA-262

Since then, there have been five more major releases of ECMA-262.

  • Second edition. The second edition in June 1998 consisted of mostly editorial changes.

  • Third edition. The third edition came out in December 1999, adding features such as regular expressions and formats for numeric output.

  • Fourth edition. The fourth edition was abandoned due to differences of opinion on the complexity of the language.

  • Fifth edition. Version five was released in December 2009. It added “strict mode,” which gave the specification better error checking. It also added support for JavaScript Object Notation (JSON) and other features.

  • Sixth edition. The sixth edition was approved by the summer of 2015. Commonly called ES6, the official name is ECMAScript 2015. Future releases will follow this format: “ECMAScript” followed by the release year. Hence, the next version will be ECMAScript 2016, and that pattern will continue.

The sixth edition adds essential syntax for creating complex applications. Other new components include binary data, generators and generator expressions similar to the Python language, error functions, proxies, for/or loops and collections.

The next edition is still at the beginning of its development. It is scheduled to include new features such as operator overloading, promises/concurrency, pattern matching and more.

Limitations of ES6

While ECMA members say ES6 is an effort to bring a simpler syntax back to JavaScript, there are still several challenges facing the language:

  • Difficult for outsiders to suggest changes. Some programming experts believe that the process of influencing changes in the standards is too complicated. Rob Eisenberg, who developed the Aurelia JavaScript framework, told InfoWorld that at one point he was trying to get a hook added to the specification for the JavaScript module loader. He told the magazine the standardization body does not have an efficient way of providing feedback, which limits the ability of outsiders to influence what is being considered.

  • Lack of 64-bit numeric type. Despite the continuing evolution of the language, some nagging technical problems remain. One sore spot is the continuing absence of 64-bit numeric type. Currently, it only supports doubles due to its support for floating-point operations.

7 Major ES6 Features

Despite these ongoing challenges, the new features inside ES6 are extensive and impressive. They include:

  1. Modules. Modules allow you to reuse parts of your application in other areas. Using new import and export keywords, you can load dependencies and manage them. While you could cobble together similar functionality in ES5 using external libraries such as CommonJS, modularity is so important for today’s large programs, it is a significant benefit that it was built in as a core feature in ES6.

  2. Promises. Errors arising from asynchronous operations can now be handled with promises. While you can handle the same situation with callbacks, promises are much more readable due to concise error handling and method chaining.

  3. Arrows. This function shorthand uses the syntax =>. While not a monumental addition, this simple improvement provides lexical scoping of the keyword “this.”

  4. Const. Const makes it easier to ensure your code is accurate. Const lets anyone scanning the code see any variables that should not be modified, and throws off an error if he or she are. This helps reduce bugs because values keep their meaning and prevent a team member from changing a variable inadvertently.

  5. Property Names. In the previous version, ES5, you could not use a variable right in an object literal. ES6 allows this with specific syntax.

  6. Template Literals. Allows changing variables into strings. Template strings show much promise as a useful feature, such as using a tag for auto-escaping SQL strings.

  7. “Sugar Syntax”. As mentioned previously, ES6 has made a concerted effort to simplify the syntax. A new class syntax is “syntactic sugar” because it makes the language simpler and more readable. It does not change how the system works but provides a cleaner syntax for developers who prefer it.

Other features include:

  • Block Level Scoping. Using the “let” keyword, ES6 lets you scope variables directly to blocks.

  • Generators. Functions that make iterators utilizing “function*” and the keyword “yield.”

  • Rest Parameters. Now you do not have to use arguments to access arguments for functions. You can access arrays that represent the remaining parameters.

  • Set. You can store a data values list inside a collection object.

  • Default Parameters. If you’ve ever wanted a function parameter that could be set default value, you are in luck, because ES6 has this functionality.

Classes is a feature of ES6 that has garnered a love/hate reaction from developers because it adds syntactic sugar on Javascript’s prototypical inheritance. It is meant to make Javascript more appealing to developers who may not have worked with a language that uses prototype chains. However, some developers complain classes lock you in and cover up inheritance, i.e. the original nature of JavaScript. A few JavaScript veterans feel the hard part about the language is constructors, not its prototypical inheritance.

Moreover, in truth, some components in ES6 are syntactic sugar. Classes are a good example as they use method signature notation to declare older coding methods with a shorter, more readable syntax. Programmers coming to JavaScript from class-based languages are usually glad they do not have to worry about strange inheritance mechanisms.

A Major Upgrade With Room To Grow

The reason JavaScript remains viable is it fits nicely in traditional web browsers while also playing well in new environments like Node.js. Despite its limitations, its flexibility allows it to thrive. ES6, or ECMAScript 2015, provides exciting new tools and functionality for developers to work faster, cleaner and more efficiently.

At the same time, ECMA needs to figure out a way for outside programmers to offer useful ideas and implement necessary features like 64-bit numeric type. If anything, ECMA needs to work faster. ES5 was adopted in 2009, and some industry watchers think it did not offer enough new features to be rolled out as a major upgrade. Indeed, some saw ES5 as nothing more than a warmed-over version of ES3. From that point of view, there haven’t been any significant advancements in the specification for many years.

If that picture is accurate, ECMA must adopt a faster approval process. They have to figure out how to incorporate new ideas rapidly, resolve political stalemates among stakeholders efficiently and make the syntax even friendlier to those new to the language. If they can meet these and other challenges effectively, JavaScript will remain a cornerstone of our mobile, always-on and hyper-connected world.

The Benefits of Migrating from JavaScript to TypeScript

Recently, we moved our Browser RUM agent from JavaScript to TypeScript. In my last post, I focused on walking through the steps of migrating from JavaScript, the challenges, and best practices we uncovered along the way.

This one will focus on more details of the benefits and one missing feature in TypeScript compiler we suggest to implement.

TypeScript’s main benefits:

  1. Class and Module Support
  2. Static Type-checking
  3. ES6 Feature Support
  4. Clear Library API Definition
  5. Build-in Support for JavaScript Packaging
  6. Syntax Similarity to Our Backend Languages (Java, Scala)
  7. Superset of JavaScript

Class and Module Support

Keywords like class, interface, extends and module are available in TypeScript.
You can define a class as

// class define in TypeScript
class VirtualPageTracker extends Tracker {
    private virtualPageName: string = '';
    constructor(name) {
        super(name);
    }

    getName(): void {
        return this.virtualPageName;
    }

    static getTrackerName(): string {
        return  'VirtualPageTracker';
    }
}

TypeScript compiler will transcompile it to

var __extends = (this && this.__extends) || function (d, b) {
    for (var p in b) if (b.hasOwnProperty(p)) d

= b

; function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); }; // class define in TypeScript var VirtualPageTracker = (function (_super) { __extends(VirtualPageTracker, _super); function VirtualPageTracker(name) { _super.call(this, name); this.virtualPageName = ''; } VirtualPageTracker.prototype.getName = function () { return this.virtualPageName; }; VirtualPageTracker.getTrackerName = function () { return 'VirtualPageTracker'; }; return VirtualPageTracker; })(Tracker);

Static Type-checking

TypeScript compiler will check the type (to surface more typing errors at compiling time)

var name: string;
name = 2; // type error, assign a number to a string type variable

function foo(value: number) {}
foo(''); // type error, use a number as a string type parameter

interface Bar {
    setName: (name: string) => void;
    getName: () => string;
}


var bar: Bar = {
    getName: function() {
        return 'myName';
    }
} // type error, setName function is missing in the object assigned to bar.

A practical example is if we use the wrong data type in the browser beacon, we now get compiling errors. Before migrating to Typescript, they could only be found by testing against the back-end.

ECMAScript 6 Feature Support

It is the current version of the ECMAScript Language Specification with more language features.
With TypeScript, you can start using many ES6 features although it may not be supported in your target browser. TypeScript compile can compile the ts files into “ES3”, “ES5” or “ES6”.

Some of the features are very handy like:

// for..of loops
var arr = ['a', 'b', 'c'];
for (let item of arr) {
    console.log(item);
}

It’s compiled to

// for..of loops
var arr = ['a', 'b', 'c'];
for (var _i = 0; _i < arr.length; _i++) {
    var item = arr[_i];
    console.log(item);
}

Refer to TypeScript ES6 Compatibility Table for more ES6 features you can use.

Clear API Definition

To let other TypeScript libraries use your library, you need to create a .d.ts file to declare all your public types and APIs of your library.
These definition files turned out to be clear and accurate references of your public APIs since they are always maintained and update-to-date because
you always need them if you write your tests in TypeScript too.

Refer to https://github.com/borisyankov/DefinitelyTyped for TypeScript definition files created for large amounts of JavaScript libraries.

Build-in Support for JavaScript Packaging

You can define one main entry ts file and refer all the ts files you need in the output js file.

Compiling the main entry ts file with the –out option, the compiler will concatenate all the directly or indirectly referred ts files into one js file in the order they are referred.

Thus, we can easily tailor our library into multiple versions.
For example, with the same code base, we are able to generate specific versions of browser agents for desktop and mobile respectively.
We just need to create one entry file for each version with different ts files referred in it.

Syntax Similarity to Our Backend Languages (Java, Scala)

We use Java and Scala at the back-end.
TypeScript’s similarity to these languages allows our developers can switch between front-end and back-end programming more smoothly.
Refer http://www.slideshare.net/razvanc/quick-typescript-vs-scala-sample for a quick syntax comparison between TypeScript and Scala.

Superset of JavaScript

As a superset of JavaScript, TypeScript has a smooth learning curve for JavaScript developers.
This means  you can adopt TypeScript in your existing JavaScript projects quickly in an less disruptive way than CoffeeScript or ClojureScript.

One Missing Feature Suggested

In addition to the benefit, we also found some missing features could be implemented.
One of them is to merge the same module into the same function rather than multiple functions.

module A {
    function foo() { }
}

module A {
    function bar() {
        foo();
    }
}

generates below code with compiling error “cannot find name ‘foo’”.

var A;
(function(A) {
    function foo() {}
})(A || (A = {}));
var A;
(function(A) {
    function bar() {
        foo();
    }
})(A || (A = {}));

foo function defined within the first anonymous function call for module A is not visible in the second anonymous function call, so you have to export it as:

module A {
    export function foo() {}
}

module A {
    function bar() {
        foo();
    }
}

generates below code without error:

var A;
(function(A) {
    function foo() {}
    A.foo = foo;
})(A || (A = {}));
var A;
(function(A) {
    function bar() {
        A.foo();
    }
})(A || (A = {}));

The problem here is now A.foo is not only visible to module A. Anyone can call it and modify it now.

There is no module level visible concept which should be similar to Java’s “package-private” when there is no modifier for Java classes or members.

This could be solved by generating:

module A {
    export function foo() {}
}

module A {
    function bar() {
        foo();
    }
}

to

var A;
(function (A) {
    function foo() { }
    A.foo = foo;
})(A || (A = {}));
var A;
(function (A) {
    function bar() {
        A.foo();
    }
})(A || (A = {}));

The problem of merging into one function is a potential name conflict between the same module in two files. But the compiler can report error in this case, and if two people are working independently on the same module in two files, it would be better to create two different sub modules. Merging into one function could be a feasible way support module level visibility.

As I write this article, I notice the /* @internal */ annotation in the ts compiler source code; it’s an experimental option released with typescript 1.5.0-alpha to strip the declarations marked as @internal.

It helps to only include the declarations without @internal (which serves as your external APIs) when generating the .d.ts file from your code. And if your consumer are using TypeScript too, this prevents it from using your internal members.

Generating the .d.ts file for:

module A {
    /* @internal */ export function internal() {}
    export function external() {}
}

by

tsc -d --stripInternal A.ts

will output

declare module A {
    function external(): void;
}

However, if your consumers uses JavaScript, they can still use the internal function.

Conclusion

By and large, it’s a pleasant and rewarding experience to move to TypeScript. Though it adds limitations on your JavaScript implementation, you can either find a good workaround or implement the benefits that outweigh it. Moreover, it’s an active open source project (about 200 commits to master in last month) with well documentation to help you start easily. And just in March this year, Google also announced they would replace AtScript with TypeScript. Angular 2 is now built with TypeScript too. So far, the move to TypeScript has proved beneficial.

8 Steps to Migrating from JavaScript to TypeScript

Recently, we’ve been moving our Browser RUM agent from JavaScript to TypeScript. Though it’s been a challenge, we enjoyed seeing how the change will benefit us and it’s been fun learning a new language in the process. Let me share a little of how we migrated to TypeScript, some of the difficulties that arose and how we tackled them.

Why TypeScript

Before moving to TypeScript, our Browser RUM agent had thousands lines of code, but was suppressed in to just two JavaScript files.

We felt obligated to refactor it before doing any real work, to make our life easier when adding additional features. Having experienced the pain of developing a large scale app in JavaScript, we decided to take a shot at their sibling languages that have better support for large-scale development.

After looking into languages such as TypeScript, CoffeeScript, and PureScript, we decided to go with TypeScript for a few reasons:

  1. Static Typing
  2. Module and Classes
  3. Superset of JavaScript, easier to learn for JavaScript developers
  4. Success story from our front-end team

8 Steps to Migrating to TypeScript

  1. Prepare Yourself

  1. Rename Files

We renamed all the js files to ts files and as TypeScript is just a superset of JavaScript, you can just start compiling your new ts files with the TypeScript compiler.

  1. Fix Compiling Errors

There were quite a few compiling errors due to the static type checking by the compiler. For instance, the compiler will complains about js code below:
Example One

var xdr = window.XDomainRequest;

Solution

// declare the specific property on our own
interface Window {
    XDomainRequest?: any;
}

Since “XDomainRequest” is an IE only property to send cross domain request, it’s not declared in the “lib.d.ts” file (it’s a file declaring the types of all the common JavaScript objects and APIs in the browser and it’s referenced by typescript compiler by default).
You will get “error TS2339: Property ‘XDomainRequest’ does not exist on type ‘Window’.”.
The solution is to extend the Window interface in “lib.d.ts” with an optional “XDomainRequest” property.

Example Two

function foo(a: number, b: number) {
    return;
}

foo(1);

Solution

// question mark the optional arg explicitly
function foo(a: number, b?: number) {
    return;
}

Optional function args need to be marked explicitly in typescript, or it gives “error TS2346: Supplied parameters do not match any signature of call target.”.
The solution is to explicitly use “?” to mark the parameter as optional.

Example Three

var myObj = {};
myObj.name = "myObj";

Solution

// use bracket to creat the new property
myObj['name'] = 'myObj';
// or define an interface for the myObj
interface MyObj {
    name?: string
}

var myObj: MyObj = {};
myObj.name = 'myObj';

When assign an empty object “{}” to a variable, typescript compiler infers the type of the variable to be empty object without any property.
So accessing “name” property gives “error TS2339: Property ‘name’ does not exist on type ‘{}'”.
The solution is to declare an interface with an optional “name” property for it.

It’s kind of fun to fix these errors and you learn about the language and how the compiler can help.

  1. Fix Test Cases

After successfully getting a JavaScript file from those ts files, we ran the tests against the new JavaScript files and fixed all the failures.

One example of the test failures caused by moving to TypeScript is the difference between these two ways of exporting a function:

export function foo() {}
export var foo = function() {}

Assuming your original JavaScript code is:

var A = {
    foo: function() {},
    bar: function() {foo();}
}

The test case shows:

var origFoo = A.foo;
var fooCalled = false;
A.foo = function(){fooCalled = true;};
A.bar();
assertTrue(fooCalled);
A.foo = origFoo;

If the TypeScript rewrite for the JavaScript is:

module A {
    export function foo() {}
    export function bar() {foo();}
}

The test case will fail. Can you tell why?

If you look at the generated JavaScript code, you will be able to see why.

// generated from export function foo() {}
var A;
(function (A) {
    function foo() { }
    A.foo = foo;
    function bar() { foo(); }
    A.bar = bar;
})(A || (A = {}));

In the test case, when the A.foo is replaced, you are just replacing the “foo” property of A but not the foo function, the bar function still calls the same foo function.

export var foo = function(){}

can help here.

TypeScript

module A {
    export var foo = function () { };
    export var bar = function () { foo(); };
}

generates

// generated from expot var foo = function() {}
var A;
(function (A) {
    A.foo = function () { };
    A.bar = function () { A.foo(); };
})(A || (A = {}));

Now we can replace the foo function called by A.bar.

  1. Refactor Code

TypeScript Modules and Classes help organize the code in a modularized and object-oriented way. Dependenies are referenced in the file header.

///<reference path=“moduleA.ts” />
///<reference path=“moduleB.ts” />
module ADRUM.moduleC.moduleD {
    ...
}

One thing I like when compiling a ts file is using the “–out” option to concatenate all the directly or indirectly referenced ts files, so I don’t need to use requirejs or browserify for the same purpose.

With TypeScript, we can define classes in a classical inheritance way rather than the prototypal inheritance way which is more familiar to Java and C++ programmers. However, you lose the flexibility JavaScript provides too.

For example, if you are seeking a way to hide a function in the class scope, save your time, it isn’t supported. The workaround is to define the function in the module and use it in the class.

TypeScript allows you to define modules and classes in an easy way and generates the idiomatic JavaScript for you. As a result, I feel like you may also have less opportunities to learn more advanced JavaScript knowledge than programming in pure JavaScript.

But just like moving from assembly to C/C++, by and large, it’s still a good thing.

We did not bother adding all the type information in the existing code, but we’ll need to do it when changing or adding code.

It is also worth moving the test cases to TypeScript, as the test cases could be auto updated when refactoring the code in the IDE.

  1. Fix Minification

Don’t be surprised if the minification is broken especially when you use Google Closure Compiler with advanced optimization.

Problem 1: Dead Code Mistakenly Removed

The advanced optimization has a “dead code removal” feature that removes the code which recognized as unused by the compiler.

Some early version closure compiler (i.e. version 20121212) mistakenly recognizes some code in TypeScript modules as unused and removes them. Fortunately, it’s been fixed in the latest version compiler.

Problem 2: Export Symbols in Modules

To tell the compiler not to rename the symbols in your code, you need to export the symbols by the quote notation. It means you need to export the API as shown below to allow the API name to stay constant even with the minified js file.

module A {
    export function fooAPI() { }
    A["fooAPI"] = fooAPI;
}

transpiled to:

var A;
(function (A) {
    function fooAPI() { }
    A.fooAPI = fooAPI;
    A["fooAPI"] = fooAPI;
})(A || (A = {}));

It’s a little bit tedious. Another option is to use the deprecated @expose annotation.

module A {
    /**
    * @expose
    */
    export function fooAPI() { }
}

This looks like it will removed in future, and hopefully you might be able to use @export when it’s removed. (Refer to the discussion at @expose annotation causes JSC_UNSAFE_NAMESPACE warning.)

Problem 3: Export Symbols in Interfaces

If you define a BeaconJsonData interface to be passed to other libraries, you’ll want to keep the key names.

interface BeaconJsonData {
    url: string,
    metrics?: any
}

@expose does not help as the interface definition transpile to nothing.

interface BeaconData {
    /**
    * @expose
    */
    url: string,
    /**
    * @expose
    */
    metrics?: any
}

You can reserve the key names by quote notation:

var beaconData: BeaconData = {
    'url': "www.example.com",
    'metrics': {}
};

But what if you want to assign the optional key later?

var beaconData: BeaconData = {
    'url': "www.example.com"
};

// ‘metrics’ will not be renamed but you lose the type checking by ts compiler
// because you can create any new properties with quote notation
beaconData["metrics"] = {…};
beaconData["metricsTypo"] = {}; // no compiling error

// ‘metrics’ will be renamed but dot notation is protected by type checking
beaconData.metrics = {…};
beaconData.metricsTypo = {…}; // compiling error

What we did is to expose the key name as
/** @expose */ export var metrics;
in the interface file to prevent the closure compiler from renaming it.

  1. Auto-Generate Google Closure Compiler Externs Files

For the Closure Compiler, if your js code calls external js library’s APIs, you need to declare these APIs in an externs file to tell the compiler not to rename the symbols of these APIs. Refer to Do Not Use Externs Instead of Exports!

We used to manually create the externs files and any time we use a new API, we have to manually update its externs file. After using TypeScript, we found that TypeScript .d.ts and the externs file have the similar information.

They both contain the external API declarations — .d.ts files just have more typing information — so we can try to get rid of one of them..

The first idea came into my mind is to check if the TypeScript compiler supports minification. As the ts compiler understand the .d.ts file, it won’t need the externs files. Unfortunately, it doesn’t support it, so we have to stay with the Google Closure Compiler.

Then, we thought the right thing is to generate the externs files from the .d.ts files. Thanks to the open source ts compiler, we use it to parse the .d.ts files and convert them to externs file (see my solution at https://goo.gl/l0o6qX).

Now, each time we add a new external API declaration in our .d.ts file, the API symbols automatically appears in the externs file when build our project.

  1. Wrap the ts code in one function

Ts compiler generates code for modules like below:

// typescript
module A {
    export var a: number;
}

module A.B {
    export var b: number;
}

// transpiled to javascript
var A;
(function (A) {
    A.a;
})(A || (A = {}));

var A;
(function (A) {
    var B;
    (function (B) {
        B.b;
    })(B = A.B || (A.B = {}));
})(A || (A = {}));

For each module, there is a variable created and a function called. The function creates properties in the module variable for exported symbols. However, sometimes you want to stop execution for some conditions such as your libraries need to be defined or it has been disabled, you need to wrap all the js code in a function by yourself, like:

(function(){
    if (global.ADRUM || global.ADRUM_DISABLED) {
        return;
    }

    // typescript generated javascript goes here

}(global);

 

My five favorite talks from OSCON

This week I went to Portland, Oregon for the O’Reilly Open Source Convention. OSCON is one of my favorite conferences because of the quality and diversity of the talks. Usually when I go to an event I am too busy presenting, working our booth, or meeting with customers and partners to fully enjoy the sessions. This year I resolved to not let that happen again and I managed to enjoy many great talks and learn quite a bit.

System management with Chef

Joshua Tiberman and James Casey gave a great workshop on getting started with Chef.

Adventures in Node

Faisal Abid presented on getting started with NodeJS and Express.

MongoDB on AWS

Charity Majors presented on the experience Parse had with scaling MongoDB on Amazon Web Services.

How Gigaspaces built their community with GitHub

This talk really resonated with me as we recently announced AppDynamics X which leverages GitHub for enabling our developer community.

[slideshare id=24638317&doc=oscon2013-community-130725234128-phpapp01]

The art of giving critiques

Emma Jane Westby presented on how to give and get actionable critiques. She did a great job explaining the difference between good and bad feedback and showed how communities can better collaborate.

[slideshare id=24663290&doc=wasitsomethingisaid-pdx-oscon-130726145653-phpapp02]

I have learned from going to many events that some of the best content comes from the time between the sessions. If you find yourself at a developer conference in the future make sure to spend time in the common areas and engage with the speakers and other attendees. See you next year at OSCON!