Dart: a New Web Programming Experience

JavaScript has had a long-standing monopoly on client-side Web programming. It has a tremendously large user base, and countless libraries have been written in it. Surely it is the perfect language with no flaws at all! Unfortunately, that is simply not the case. JavaScript is not without its problems, and there exists a large number of libraries and "trans-pilers" that attempt to work around JavaScript's more quirky behaviors. JQuery, Coffeescript, Objective-J and RubyJS are examples of how people have been trying to make JavaScript better. However, a new contender is throwing its hat into the ring in a big way.

In comes Google Dart, a new JavaScript replacement language. Dart is a ground-up re-imagining of what JavaScript should be. It requires its own runtime environment (which Google makes available for free under the three-clause BSD license) and has its own syntax and libraries. Dart is an object-orientated language with a heavy Java-like feel, but it maintains many of the loved JavaScript paradigms like first-class functions.

So, why have I chosen to use Dart? Good question! I have chosen Dart because it is a clean break from JavaScript, and it has the object-orientated programming style I have come to know and love. Because I have a Java background, the learning curve didn't seem as steep with Dart as it does with JavaScript. Also, because Dart is so new, it gives me a chance to become an early adopter of the language and watch its evolution.

Installing Dart

Before you can program with Dart, you need to grab a copy from http://dartlang.org. I chose to install only the SDK; however, there is an option to grab the full Dart integrated development environment with the SDK included. Eclipse users will feel right at home with the IDE, because it is based on Eclipse components.

To install the SDK, I just unzipped the files and copied the whole directory to $HOME/bin. Then I modified my path variable to look in the folder I created:


PATH=$PATH:$HOME/bin/dart-sdk/bin 

Now I can run dart, dart2js and dartdoc from anywhere.

Language Features

The core Dart language is pretty straightforward. The basic data types available are var (stores any object), num (stores any number type), int, double, String, bool, List (arrays) and Map (associative array). All of these data types are declared in the dart:core library. dart:core is always available and does not need to be imported. Functions also can be considered a data type, because Dart treats them as first-class objects. You can assign functions to variables and pass them as parameters to other functions or write anonymous functions in-line.

For flow control, you have the "usual" if, else if, else, for, while and do-while loops, break, continue, switch and assert. Exceptions are handled through try-catch blocks.

Dart has a lot of support for object-oriented programming. Classes are defined with the class keyword. Every object is an instance of some class, and all classes descend from the Object type. Dart allows only for single inheritance. The extends keyword is used to inherit from a parent class other than Object. Abstract classes can be used to define an interface with some default implementation. They cannot be instantiated directly, but can make use of factory constructors to create the appearance of direct instantiation. Abstract classes are defined with the abstract modifier in front of the class declaration.

Standard Library

Dart ships with an impressive standard library. I use a few of the libraries and classes in my examples here, so it will be helpful to have an idea of what they can do ahead of time. I can't cover all of them, but I cover the ones I personally find most useful.

As I said earlier, dart:core defines all of the core data types that are available. That's not all though! dart:core also contains the regular expression classes that are an invaluable addition to any standard library. Dart uses the same regular expression syntax as JavaScript.

dart:io provides classes that let your program reach out to the world. The File and Directory classes can be used to interact with the local filesystem. The File class also will allow you to open input and output streams on the specific file. If you want to write cross-platform code and allow users to specify the path of a file native to their operating system, the Path class provides a really nice Path.fromNative(String path) constructor that will convert Windows and UNIX paths to their Dart counterparts. Also included in this library are the Socket and ServerSocket classes that can be used for traditional network communications. The HttpServer class allows you to program a Web server quickly. This is great if you want to add a custom rest API to your application. dart:io can be imported and used only on server-side applications, so don't try to use it in your browser apps!

dart:html contains all of the classes necessary to interact with a client browser's document object model. This library is required to write any client-side code that runs in a browser. The library defines two static methods: Element query(String selector) and List<Element> queryAll(String selector). These methods allow you to grab HTML5 elements from the browser's DOM using cascading-stylesheet selectors. (I show an example of this later.)

dart:math, dart:json and dart:crypto provide helpers that are hard to live without. dart:math provides all of the static math methods that programmers have come to expect. dart:json provides the JSON helper class. It has only three static methods: parse(String json), which returns a Map containing the parsed document; String stringify(Object object) and void printOn(Object object, StringBuffer output) can be used to serialize an object into JSON. Any object can be made serializable by implementing a toJson() method. dart:crypto has helpers for performing md5, sha1 and sha256 hashing. There also is a CryptoUtils class with methods for converting bytes to hex and bytes to base64.

Server-Side Programming

Let's jump into Dart by looking at some server-side programming:


import 'dart:io';

void main(){
  String fileName = './test.txt';
  File file = new File(fileName);

  var out = file.openOutputStream();
  out.writeString("Hello, Dart!\n");
  out.close();
}

Does it look pretty familiar? It's not much different from a Java program at this point. You start by importing the dart:io library. This gives you access to the File and OutputStream classes. Next, you declare a main method. Just like Java and C, main acts as the entry point for all programs. The File object is used to hold a reference to a single file on the filesystem. In order to write to this file, you open the file's output stream. This method will create the file if it does not exist or clears the contents of the file if it does. It returns an OutputStream object that then can be used to send data to the file. You write a single string and close the OutputStream.

To run this program, save it to a file called first.dart. Then use the Dart runtime environment provided with the SDK:


$ dart first.dart

When your program is done, you should see a file called test.txt in the same directory. Open it, and you will see your text.

What's interesting about Dart is that all I/O is event-based. This is much in the same style as Node.js. Every time you call a method that performs I/O, it is added to the event queue and the method returns immediately. Almost every single I/O method takes in a callback function or returns a Future object. The reason for this design choice is for scalability. Because Dart runs your code in a single thread, non-blocking asynchronous I/O calls are the only way to allow the software to scale to hundreds or even thousands of users.

Listing 1. wunder.dart


import 'dart:io';
import 'dart:uri';
import 'dart:json';

void main(){
  List jsonData = [];
  String apiKey = "";
  String zipcode = "";
  
  //Read the user supplied data form the options 
  //object
  try {
    apiKey = new Options().arguments[0];
    zipcode = new Options().arguments[1];
  } on RangeError {
    print("Please supply an API key and zipcode!");
    print("dart wunder.dart <apiKey> <zipCode>");
    exit(1);
  }

  //Build the URI we are going to request data from
  Uri uri = new Uri("http://api.wunderground.com/"
      "api/${apiKey}/conditions/q/${zipcode}.json");

  HttpClient client = new HttpClient();
  HttpClientConnection connection = 
                           client.getUrl(uri);
  connection.onResponse = 
                  (HttpClientResponse response) {
  
    //Our client has a response, open an input 
    //stream to read it
    InputStream stream = response.inputStream;
    stream.onData = () {
    
      //The input stream has data to read, 
      //read it and add it to our list
      jsonData.addAll(stream.read());
    };

    stream.onClosed = () {

      //response and print the location and temp.
      try {
        Map jsonDocument = 
         JSON.parse(new String.fromCharCodes(jsonData));
        if (jsonDocument["response"].containsKey("error")){
          throw jsonDocument["response"]["error"]["description"];
        }
        String temp = 
        ↪jsonDocument["current_observation"]["temperature_string"];
        String location = jsonDocument["current_observation"]
          ["display_location"]["full"];
        
        print('The temperature for $location is $temp');
      } catch(e) {
        print("Error: $e");
        exit(2);
      }
    };
  
    //Register the error handler for the InputStream
    stream.onError = () {
      print("Stream Failure!");
      exit(3);
    };
  };
  
  //Register the error handler for the HttpClientConnection
  connection.onError = (e){
    print("Http error (check api key)");
    print("$e");
    exit(4);
  };
}

In Listing 1, you can see this evented I/O style put to work with the HttpClientConnection object returned by the HttpClient.getUrl(Uri url) method. This object is working in the background waiting for a response from the HTTP server. In order to know when the response has been received, you must register an onResponse(HttpClientResponse response) callback method. I created an anonymous method to handle this. Also notice that toward the bottom of the program, I register an onError() callback as well. Don't worry; all of the callbacks are registered before the HTTP transaction begins.

______________________

Comments

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

This is really useful

lisaedward123's picture

This is really useful information. Thanks for sharing this article.
Java training in chennai

Android mobile development in chennai

android mobile development in chennai's picture

android mobile development in Chennai

Excellent in your post in all process you can explain in line by line clearly it is one one of the new way of thinking.

Panda SEO

jamesagrata's picture

High quality written content along with inbound links performed a essential component throughout ranking assessment and yes it seems Yahoo and google will do identical show up although initial let’s go through the different character which will render SEARCH ENGINE OPTIMISATION. pandalinkbuilders

This is really nice. Thanks

lisaedward's picture

This is really nice. Thanks for your information.
java training institute in Chennai

Reply to comment | Linux Journal

skip hire adelaide's picture

A work mate referred me to your site. Thanks for the details.

キネティックは自動巻き時計と同様にローターを内蔵し、腕の振

laulan's picture

キネティックは自動巻き時計と同様にローターを内蔵し、腕の振りによって発電を行う電池交換不要のクォーツ腕時計である。装着していない時には省電力のため針の動きが自動的に停止し、再び装着され振動が与えられるとそれをバーバリー腕時計感知して自動的に現在時刻に復帰するオートリレー機能を組み込んだ「キネティックオートリレー」、小の月だけでなくうるう年においても正しい日付を示すパーペチュアルカレンダーの「キネティックパーペチュアル」、手巻き充電にも対応し、パワーリザーブ表示機能を持つ「キネティック・ダイレクトドライブ」もある。

キネティックは自動巻き時計と同様にローターを内蔵し、腕の振

laulan's picture

キネティックは自動巻き時計と同様にローターを内蔵し、腕の振りによって発電を行う電池交換不要のクォーツ腕時計である。装着していない時には省電力のため針の動きが自動的に停止し、再び装着され振動が与えられるとそれをバーバリー腕時計感知して自動的に現在時刻に復帰するオートリレー機能を組み込んだ「キネティックオートリレー」、小の月だけでなくうるう年においても正しい日付を示すパーペチュアルカレンダーの「キネティックパーペチュアル」、手巻き充電にも対応し、パワーリザーブ表示機能を持つ「キネティック・ダイレクトドライブ」もある。

good & informative article

Anonymous's picture

I prefer CoffeeScript but after seeing the feature/function integration Dart represents, I've decided to give it a second look.

The more I use it the more I like the "batteries included" approach of the Dart project: Dart Editor, Dart VM, dart2js, pub (package manager), etc.

thanks for a very informative article re subject;

This is really nice. Thanks

lisa's picture

This is really nice. Thanks for your information.
Dot net course in Chennai

Preview comment | Linux Journal

best tire deal's picture

Hi there i am kavin, its my first time to commenting anywhere, when i read
this piece of writing i thought i could
also create comment due to this brilliant piece of writing.

Yes

Clairevoyance's picture

Oui je suis d'accord et merci pour ce bon code php. Pour ma part, j'utilise un code php pour le cache du serveur. Cela me permet de booster mon site de voyance sérieuse et d'offrir gratuitement ce service de voyance gratuitement à tous mes visiteurs.

So when they found it hard to

Anis's picture

So when they found it hard to optimize Javascript some more they invented new language. Great, exactly like if college students write their own questions and answer them instead of teachers questions that are too hard to answer.

Updated examples

jslocum's picture

Things go away and things get

Marjorie Lanphear's picture

Things go away and things get backdated. JavaScript is no longer as great thing as past time. We used to invest prime time on this!

  • Quite some australian gamblers are getting unwell and tired of pubs and land based mostly on line betting site and they are normally getting the changeover to online pokies. You can find a lot of strengths to online wager site.

Very interesting topic will

zeennate's picture

Very interesting topic will bookmark your site to check if you write more about in the future.
voyance gratuite

Google is Evil

Anonymous's picture

As a computer scientist, I'm laughing. Google's Go and now Dart? Why don't you read between the lines of a $25 billion global corporation? Microsoft is a $50 billion global corporation. Today's Google == Evil news: "Google Abandons Open Standards for Instant Messaging". Yesterday, it was more evil news from Google. Wake up you clueless idiots!

Your issue of google talk is

Anonymous's picture

Your issue of google talk is a real issue:
From EFF:
https://www.eff.org/deeplinks/2013/05/google-abandons-open-standards-ins...

privacy conscious users who want to use Off-the-Record encryption where possible, but to keep messages out of their Gmail accounts in any case, are out of luck. And if they wish to continue chatting with their friends on Google chat, they can't even take their business elsewhere.

provide Google with information about the content of their messages, or even when and from where they have logged in.

Comment: the google talk change, looks to be a mandate to compily with federal rules for tracablity.

Reply to comment | Linux Journal

capsiplex news's picture

Do you have a spam issue on this site; I also am a blogger, and I was wondering your situation; we have created some nice methods and we are looking to
exchange techniques with other folks, please shoot me an email if interested.

Dart is BSD License Go is

Anonymous's picture

Dart is BSD License

Go is licensed under the Creative Commons Attribution 3.0 License, and code is licensed under a BSD license

How come as CS scientist you can not us the web to find such thing out.

Oh ya, your a troll, lol

Cloud apps NEED Dart

Jim Birch's picture

AFAICS the push to sophisticated browser-to-cloud applications will necessitate a shift from javascript. JS is great for a a bit of chunky screen animation and a bit of background I/O but I can't see that it is really up to running the big browser applications of the future. It's too messy in too many ways to develop something with a capacity like Photoshop. And this is where Google Docs etc are headed.

I'm not sure

Curtis's picture

I like it that it's a typed language unlike PHP. I question Google's motives, however.

typed language ???

Anonymous's picture

Who need TYPED language at these days, @ WEB & today's resources ?!?

This looks very cool, is Dart

Steeve McCauley's picture

This looks very cool, is Dart embedded in chrome?

Blossom switches from JavaScript to Dart

Thomas Schranz's picture

I've written an article on our decision to switch from JavaScript to Dart. You can read it here
http://www.ramen.io/post/46936028144/we-are-switching-to-dart-why

We hope better than Java

evoanuncios's picture

We hope that Dart will be better than Java..

Thanks

Dart is like Java in browser.

Anonymous's picture

Dart is like Java in browser. Awful.

Dart in the browser

tracker1's picture

Dart is much more like CoffeeScript in the browser... It is a language, and an optional runtime is cross-compile to JavaScript, which is then run in the browser. The biggest wart is that debugging becomes very cumbersome and difficult. Other than that, I don't mind that it exists. There's also TypeScript if you're wanting an extension that cross-compiles to JS. For the record, I'm fine with JS, my style of programming tends to avoid a lot of the warts.

Moving away from class-based thinking, and more about module and functional patterns and passing state objects tends to work better anyhow. YMMV of course, but I happen to like JS as-is. That said, I don't fault anyone wanting to try something new/different.

--
Michael J. Ryan - http://tracker1.info/

Good to know idiocy is

Anonymous's picture

Good to know idiocy is thriving with a comment like that.

Idiocy resorts to name

Anonymous's picture

Idiocy resorts to name calling instead of giving a legitimate critic.

how so? please

eMBee's picture

how so?
please elaborate.

greetings, eMBee.

Reply to comment | Linux Journal

http://www.tablettegraphique123.net/'s picture

Your style is really unique compared to other people I have read stuff from.
Many thanks for posting when you've got the opportunity, Guess I'll just
bookmark this page.

White Paper
Linux Management with Red Hat Satellite: Measuring Business Impact and ROI

Linux has become a key foundation for supporting today's rapidly growing IT environments. Linux is being used to deploy business applications and databases, trading on its reputation as a low-cost operating environment. For many IT organizations, Linux is a mainstay for deploying Web servers and has evolved from handling basic file, print, and utility workloads to running mission-critical applications and databases, physically, virtually, and in the cloud. As Linux grows in importance in terms of value to the business, managing Linux environments to high standards of service quality — availability, security, and performance — becomes an essential requirement for business success.

Learn More

Sponsored by Red Hat

White Paper
Private PaaS for the Agile Enterprise

If you already use virtualized infrastructure, you are well on your way to leveraging the power of the cloud. Virtualization offers the promise of limitless resources, but how do you manage that scalability when your DevOps team doesn’t scale? In today’s hypercompetitive markets, fast results can make a difference between leading the pack vs. obsolescence. Organizations need more benefits from cloud computing than just raw resources. They need agility, flexibility, convenience, ROI, and control.

Stackato private Platform-as-a-Service technology from ActiveState extends your private cloud infrastructure by creating a private PaaS to provide on-demand availability, flexibility, control, and ultimately, faster time-to-market for your enterprise.

Learn More

Sponsored by ActiveState