Dart Is Not the Language You Think It Is

A terse language without ceremony

When Dart was originally launched, many developers mistook it for some sort of Java clone. In truth, Dart is inspired by a range of languages such as Smalltalk, Strongtalk, Erlang, C#, and JavaScript. Get past the semicolons and curly braces, and you’ll see a terse language without ceremony. Dart has evolved into its own, and here are some of my favorite language features.

Dart is a source code VM

The Dart VM reads and executes source code, which means there is no compile step between edit and run. As with other popular scripting languages, it’s very quick to iterate with Dart. The Dart VM runs on the command line and servers, and can be embedded into browsers. Just point the VM at Dart source code and you’re up and running!

Dart is optionally typed

Dart understands that sometimes you just don’t feel like appeasing a ceremonial type checker. Dart’s inclusion of an optional type system means you can use type annotations when you want, or use dynamic when that’s easier.

For example, you can explore a new idea without having to first think about type hierarchies. Just experiment and use var for your types. Once the idea is tested and you’re comfortable with the design, you can add type annotations.

Here is a comparison between code that uses type annotations, and code that uses var for dynamic. Both of these code snippets have the same runtime semantics:

With type annotations:

Or, without type annotations:

Type annotations are great for the “surface area” of the code (such as method and function signatures), and the tools are getting good enough for you to consider using var inside methods and functions.

Dart supports collection literals

It’s easy to declare lists and maps with Dart. For example, here is a simple list:

And here is a simple map:

Dart is purely object oriented

Dart’s language is clear: everything is an object. It is easy to explain how everything works without having to deal with primitives as a special case. Even calling + on two numbers is modeled as a method call. Numbers, booleans, and even null are all objects.

Dart supports top-level functions and variables

Not everything must live inside of a class. Dart’s libraries can contain top-level functions and variables. You can write whole programs without ever using a class.

Here is a simple Dart library:

Using this library is easy:

Dart’s main function is terse

No more public-static-void-main-String[]-args just to start a program! Dart’s simple top-level main() function is all you need.

Here is an example:

All Dart programs start at the main() function.

Dart lets you put any number of public classes into a file

Organize your project’s files and contents the way you want to. You are not forced to name the file the same as the class, and you aren’t forced to place only one public class in a file. Go ahead, put two classes into one file. Whatever works for you!

Dart has closures and lexically scoped functions

Create functions that can naturally access variables in their enclosing scope, without having to write verbose anonymous inner classes.

Here is an example of a closure in action. The makeAdder function returns a function that closes around makeAdder‘s parameter.

You can use simplify makeAdder by returning an anonymous function:

Dart has mixins

No need to pollute the inheritance hierarchy with utility classes. Use Dart’s mixins to slide in functionality that is clearly not an is-a relationship.

Classes that extend object, don’t have constructors, and don’t call super can be a mixin. Here is an example:

Dart has operator overriding

You can add operators to your class. Here is an example:

Dart has string interpolation

It’s very easy to build a string from variables or expressions. Here is an example of implementing toString() and including the x and y fields in the output.

Dart has noSuchMethod

A class can implement noSuchMethod to handle methods that don’t explicitly exist on the class.

In the following example, the LoggingProxy logs all method calls before they are delegated. The code uses mirrors for run-time reflection and delegation, and noSuchMethod to capture the calls.

You can use the above code like this:

Summary

Dart is a pragmatic language designed for adoption, and its familiar syntax and productive features make it easy to learn. Dart compiles to JavaScript and runs across the modern web, and it scales from tens of lines to one million lines of code. With its stable language and core libraries, you can use it today. Visit dartlang.org for more info and download the open-source SDK. See you at FluentConf!

Editor’s note: If you’d like to see more from Seth, check out his interview with Simon St. Laurent. For more information on Dart, see What is Dart? by Kathy Walrath and Seth Ladd.

Related

Sign up for the O'Reilly Programming Newsletter to get weekly insight from industry insiders.
topic: Programming
  • kusmi

    I’m so happy it’s not called FART… ;-)

    • sethladd

      Me too, wouldn’t that be silly! :)

    • kaisellgren

      Since the character D is next to F, I have accidentally typed Fart a few times, but luckily I always read before I post :)

  • wtf

    So it is a verbose shitty clone of Ruby?

    • sethladd

      I’m a fan of Ruby, but there are quite a few differences between Ruby and Dart. Ruby is highly dynamic and encourages a metaprogramming style. Dart isn’t as dynamic (you can’t add methods to a class at runtime, for example). Dart is easier to optimize due to its more structured design.

      Ruby doesn’t have any type annotations, whereas Dart has optional static types. These come in really handy when developing larger systems. The type annotations help you refactor, navigate code, and get early warnings. I love Ruby, but we had a hard time scaling our Ruby code bases. Type annotations should help scale up your apps.

      By “verbose” I assume you mean Dart uses semicolons and curly braces? That was a pragmatic choice, as JavaScript, Java, C#, C++, ObjectiveC, and other very popular languages use semicolons and curly braces. We wanted Dart to be easy to learn, so we stuck with a common “look and feel” for the language.

      • Thomas Dybdahl Ahle

        Are Dart semicolons optional, like in JavaScript?

        • Ahmet A. Akın

          No.

      • thedracle

        So, Ruby 1.8 was a great deal more dynamic. You could reach into methods and deconstruct them into an AST, that you could then walk, modify, and patch over.

        Since 1.9, it has given up some of its truly powerful meta programming capabilities, in exchange for more pragmatic (and often used) features. I do wonder why Dart wouldn’t implement, as you describe, the ability to add functions to classes at runtime– since this is a fairly intrinsic feature to prototype based programming languages like JavaScript.

        With Ruby, there are some type inference systems, and I’ve seen systems maybe 5+ years ago on Ruby 1.8 where people used the above (Ruby2Ruby) to infer the usage of types within a method, and to then walk the type system to determine based on the usage what the types in that current state of the system were, and then patch over the method with type a type checking function.

        This could then be marshaled to the disk, and loaded in as a barrier to prevent type misuse for a particular library, or API.

    • wtfwtf

      And where did you get that idea? Dart
      - can work directly in browser.
      - VM is perhaps two orders of magnitude faster than Ruby
      - syntax does not look like Ruby at all
      - directly compiles to Javascript

      • morphemass

        “two orders of magnitude”?

        That would put it on par with C++ in many instances then?

        • Abe

          No, but on par (perhaps) with Java.Still pretty impressive. Performance is far superior to Ruby and Python.

          • icebraining

            Technically, Ruby and Python can’t be compared, since they have multiple implementations. For example, PyPy is already significantly faster than CPython in many cases.

          • Ahmet A. Akın

            My guess is, Dart VM will be faster than all Ruby and Python implementations.

          • wpostma

            Python is CPython. Pypy is a fast toy.

      • bmarkovic

        “can work directly in browser”

        Means will most likely work directly in Chrome and (perhaps) Opera. Must be compiled to JavaScript for others. This will sure make debugging lots of fun.

        • ryan

          Source maps baby!

  • André Abreu

    I Love Dart language, and I really want so see the vm implemented in chrome!
    I hope to see Dart webapps on mobile just like Java did for Desktop.
    Thanks sethladd :)

  • NobodySpecial

    Typescript is a better. Too bad all of web-3.0 google fawn boys hate it on principle.

    • DOKKA

      How is Typescript any better? Typescript is just a superset of javascript. You better be trolling

  • Watanabe Daisuke

    Pro tip:

    If using dart2js, you can reduce the file size of the output javascript by conditionally importing only the classes you need from a package.

    e.g. import ‘dart:html’ show ButtonInputElement;

    • sethladd

      dart2js also performs general tree shaking. If you don’t use the function or class, it’s not pulled into the compiled output.

  • Eric

    So what ideas did it get from Erlang exactly? I see nothing the even remotely resembles it.

    • sethladd

      Good question. I ran out of space in the article, but Dart has a system called isolates. Dart can spawn a function or a source file into an “isolated memory heap” and run this isolate concurrently with other isolates. You pass messages between isolates, and no state is shared between isolates. Isolates are sorta-kinda like Erlang’s actors, in the sense that they are a unit of concurrency, isolation, and the message passing paradigm is similar.

  • Dave

    Dart looks really cool, but not sure if I’d stake my career on it only to find out that Google decides to bitbucket it along with everything else.

    • sethladd

      Dart is being used by important internal projects at Google. That’s a good sign of commitment.

      • bloub

        Like xmpp?

  • http://owaislone.org/ Owais Lone

    I don’t like this,

    import library.data;

    func_from_library();

    This is bad, one of the things I hate about JS. Everything should be properly namespaced. I would have preferred something like this

    import library.dart;

    library.func_from_library();

    • sethladd

      You have control over prefixes. You, the user, get to decide if you want to prefix names that come in from a library.

      ex:

      import ‘lib.dart’ as foo;

      foo.func_from_library();

      • http://owaislone.org/ Owais Lone

        That is interesting but it raises another concern. Looks like dart allows a lot of flexibility in the way you write code, which can lead to a lot of ugly code all over the internet. I think enforcing good practices is a task the language itself should take care of but at least it does support namespacing. People who want to use them can use them which is awesome.

      • lucian1900

        That still looks like the wrong default to me. It should only explode into the current namespace if explicitly asked to.

  • Andrew

    Seth,

    Thanks for highlighting many of the great features in Dart. Do you have any thoughts on what Dart is missing or what it’s largest pitfalls are?

    • sethladd

      Hi Andrew,

      I’m looking forward to some language constructs to make async programming easier. Dart’s Future and Stream classes definitely help, but I’m hoping we can do more over time.

      One pitfall is our Mirrors reflection isn’t 100% available in dart2js yet. However, the engineers are working hard to get feature parity across the VM and dart2js, so I expect that soon.

      Hope that helps,
      Seth

  • le_dude

    Dart is awesome for web development, if you’re still not convinced it’s probably because you haven’t tried it; by trying I mean going further than the hello world example and actually developing a web app with Dart, (yes even a small one).

  • FrankyBoy1234

    90% of the stuff … ok, reads like C#

  • zzz

    Why wasn’t this titled “how dart differs from java”? I would have just saved 3 minutes of my life.

  • Zog

    Is server side development possible with Dart?

  • Black Jack Shellac

    Not a big fan of operator overloading, but I’m otherwise interested in playing with this language. And yeah, it would be fantastic to see something like this competing with javascript in the browser. not a big fan of javascript’s quirks.

    • Ahmet A. Akın

      Operator overloading is reasonable and useful in Dart in my Java perspective, comparing to the madness in C++.

  • Simon St.Laurent

    If folks would like to see more of Seth, I did an interview with him about Dart. It’s from last year, but I think it still holds up pretty well. http://programming.oreilly.com/2012/05/javascript-dart.html

  • Tod-asdahjvbxyz

    Man, “source code VM” sure sounds more sophisticated than “interpreter”.

  • A Lee Wade

    Great article, Seth. I’m very excited about Dart and TypeScript. In many respects, they’re as different as night and day, but I think they will both drive future versions of ECMAScript.

    I do have two questions: when we see the Dart VM in Chrome, not just Dartium or possibly Chromium?

    Also, given Google’s support for asm.js (“…during I/O, Google [stated] in the past few weeks, since asm.js was introduced, Chrome had gotten 2.4 times faster at running asm.js-optimized code.” _source lost_), when will Dart “compile” to asm.js?

    • sethladd

      I don’t think Dart will compile to asm.js. Asm.js is great if your problem can be reduced to:

      * arithmetic operations;
      * loads and stores into ArrayBufferView, all views sharing a single ArrayBuffer;
      * calls to functions that take numbers as arguments and return number as the result, possible function targets are limited so you can’t, for example, create a closure and pass it somewhere.

      The Dart VM is a full-fledged VM with garbage collection, isolates, a JIT, and more. It’s not a good fit for asm.js as we know it today.

      • thedracle

        Just to play Devil’s advocate, how specifically is a garbage collector, or a JIT compiler not reducible to ASM.JS?

  • skript-kiddie 101

    Umm.. no mention of semantic analysis or code security?

    Is there any?

    • thedracle

      Do you mean semantic analysis for purposes of code optimization? I’m sure there’s plenty of that going on in the Dart VM.

      What do you mean by Code Security?

  • Brian Oh

    What’s the best thing about Dart? Performance, Editor, Elegance, Client-Side, Server-Side, Productivity, Libraries? It’s hard to choose (IMHO). What other language has all of those features? What’s to knock? “;”? There are pros and cons. I’m fairly agnostic on that one, but overall I favor it (;). What’s to improve? A few things, but it hasn’t reached 1 yet. I’m definitely no expert, but I’m working on it. Thanks go to the developers for creating something brilliant IMHO.

  • Carl

    This article is good marketing.

    for example it doesn’t show what happens when the optional type is a complex generic. then it is as ugly as jaava. wished they had adopted a trailing type style for an optionally typed language.
    BTW: function types?
    Otionally typed means for dart . incomplete typed.

  • http://calliopesounds.blogspot.com/ Andrew Gilmartin

    I would like to better understand the reason for Dart. That is, what programming and engineering problems is it solving at the language level that can’t be done in other languages at the library level (other than for aesthetics (which I do understand the importance of))? Is there a document or documents that capture this?

    • ryan

      My guess is not much. The attractiveness of Dart is structure and tooling. “Compiling” to JS seem quite reasonable and is the current trend of JS’s future. Everybody hates javascript. People who say they love it..are lying.. they hate it too. Douglas Crockford hates Javascript.

  • Klank

    I admit, I find Dart very compelling coming from a C++/C# background. But after getting burned by MS over Silverlight, I’m not sure I’m willing to trust in the promises of “commitment” of another sole-proprietor framework.