Tips and tricks with Jukito

After writing an enormous amount of tests for GWTP using Jukito, I ended up beating myself on many issues. Fortunately, many were common enough to have me noting them down.

This post will give you tips and tricks you can use with Jukito to make your life easier when testing things in GWTP. A few of the following tricks are also briefly shown in the previous posts of the series. I’ll try to give a little more detail for each of them. Continue reading “Tips and tricks with Jukito”

Testing client-server communication with REST-Dispatch

A lot of the tests that are written in GWTP applications focus on client-server communication. Fetching and saving data is what most web applications do nowadays.

You can use whatever library to accomplish this work, however, in this post I use REST-Dispatch and Resource Delegates, from gwtp-extensions. They come with nice testing utilities that I’ll show you. Continue reading “Testing client-server communication with REST-Dispatch”

Testing patterns in GWTP

This post is intended to be the next steps towards a TDD approach with GWTP. We’ll try to show you the patterns and workflow of writing a GWTP application in a TDD fashion. Continue reading “Testing patterns in GWTP”

Testing GWTP applications with Jukito – Introduction to Jukito

In this second post of the Testing GWTP applications with Jukito, we present : Jukito!

The purpose of this post is to show the basics of Jukito, and to show what are the advantages for you and for your project.

What is Jukito?

Jukito is a Java library that allows you to reduce the amount of code to write when testing code that is written using dependency injection. Typically, people use Mockito to mock their dependencies and it ends up being cumbersome. Jukito creates mocks for you for all the injected dependencies.

Here is an example made with Mockito and an example done with Jukito.

As you can see, the only differences with the two snippets, are:

  • With jukito you don’t have to call the class under test’s constructor
  • The annotation used to mock dependencies is @Inject instead of @Mock
  • The TestRunner annotation changed

At first, it doesn’t look like a big deal, but when the code base grows, things can get out of control. For example, imagine that we want to add a new dependency to the Endpoint class and inject it via constructor.

With Mockito, this kind of change will produce a compilation error. On the other hand, with Jukito, everything still compiles fine, since the call site doesn’t change.

OK, what now?

Jukito uses Google Guice and Mockito behind the scenes. However, even if you’re not using Guice, you can still use Jukito. The only requirement to use Jukito is to use Java’s standard annotation @Inject on your class’ constructor.

Everything that is possible in a Guice Module can also be done in a Jukito module.

Example

Let’s say you have an interface called UserInformationService. You could have a test that uses a fake implementation, another test that uses the real implementation and another test that uses a mock implementation. By default, Jukito injects Mockito mocks, but it is also possible to bind the interface to whatever implementation you want. To do so, we have to declare a Jukito module in the test class, and setup things there.

There is another cool use case for Jukito and Guice. A lot of Java code use factories. Guice has the ability to generate a factory implementation from an interface. We can either inject a mock factory or create a real factory with a binding in the Jukito module.

The first case would be to inject a mock factory as in the second gist, where we used Jukito.

We had to change the code a little bit here so that the factory would be managed by Guice. As you can see, the scope of the test is a little bit wider. The test verify that the endpoint returns the correct status code.

There is no best solution, it mostly depends on the level of integration you want your test to have. In the first, the response would be the one that you crafted yourself, whereas in the second, the response returned by theResponseFactory would be the same as in production.

Conclusion

In summary, Jukito is a library that does whatever is possible with Mockito and Guice. When writing big projects, it can really help scaling the code base and all its tests.

It is even more useful in a context like a GWTP application, where :

  • Almost all components use dependency injection
  • GWTP uses GIN (which is Guice for GWT)
  • Testing interactions is very natural. Therefore using mocks for testing and driving the design is also natural

Hopefully, this post gave just enough information to understand the upcoming examples about testing GWT components, like Presenters.

Testing GWTP applications with Jukito – Introduction to TDD

This is the first blog post of a series that will evolve into a step-by-step guide for testing GWTP applications using TDD.

The goal of this first post is to give the readers basic knowledge that will serve as the foundation for the rest of the series.

Prerequisites

In order to understand this post and apply the ideas that it contains, you should:

  • Know how to use JUnit
  • Understand the fundamentals of TDD [Red-Green-Refactor]

Post_Jukito_TestingTDD_v1-02

This post includes an overview of the following topics and also provides references for further details :

  • Classic vs Mockist TDD
  • Dependency Injection

Classic vs Mockist TDD

This section is not made to bash either type of TDD or to say that one is better than the other. It is meant to show the strengths and the weaknesses of each type and to show the context in which each of them is relevant. The two styles are not mutually exclusive, but rather complementary.

Classic TDD

This approach was first popularized by Kent Beck. The idea behind this kind of TDD is to test an algorithm multiple times by using different inputs and validating the outputs. Typically, this involves having tests on a class and hiding what’s happening in the background, i.e. hiding the direct dependencies of the class under test.

For example, if the class’ outputs are only dictated by its inputs, then a classic TDD test is easy to write. (e.g. to test a sorting algorithm, you just have to give it multiple inputs and have the corresponding expected outputs to verify it).

Unfortunately, not all situations are like that. Take for example an application that fetches data from an external source like a web API. Testing this involves more than checking outputs based on specific inputs. The actual output of the class will depend on its environment.

Mockist TDD

Mockist TDD – also called London School TDD – approach was popularized by Steve Freeman and Nat Pryce, and is focused on verifying the interactions of a class within its ecosystem. It is also a good tool for driving the design of an application.

One of the strengths of Mockist TDD is that it helps us organize the layers and the dependencies of an application. For example, many tests written using this kind of TDD will involve checking that a class delegates an action to the correct collaborator with the correct values. Other tests might consist in verifying that the tested class reacts correctly to its collaborators’ responses.

These kinds of tests help demonstrate that the communication doesn’t bypass layers in the application. It also helps ensuring that the Tell don’t ask principle is respected.

When testing GWTP applications, these concepts are very useful, because most testing will be interaction oriented.

Here’s a demonstration of J.B. Rainsberger developing an application using Mockist TDD.

Dependency Injection

Most of the time, when a class starts doing too much job, it is wise to split it up in smaller pieces. When testing a class, one of the best practices is to isolate it from the outside world (anything too complex, unpredictable or that doesn’t belong in the same level of abstraction).

Here’s a quote from James Shore that defines Dependency Injection :

“Dependency Injection” is a 25-dollar term for a 5-cent concept. That’s not to say that it’s a bad term… and it’s a good tool. But the top articles on Google focus on bells and whistles at the expense of the basic concept. I figured I should say something, well, simpler.

[…]

Dependency injection means giving an object its instance variables. Really. That’s it.

Basically, this lets us control the outside environment. For example, given a class “A" that makes an HTTP request to an API and uses the data to do some computation, the constructor of A would receive an instance of the class B that is responsible of making that HTTP request. Class A would only use the data provided by B.

In a testing context, one could pass an instance of B to A with controlled and predictable return values.

There are multiple ways of making objects behave in a controlled/predictable way. Such objects are usually called “test doubles”. In testing jargon, the different types of test doubles are:

  • Stub
  • Mock
  • Dummy
  • Fake

Martin Fowler has written a good reference on the different types of test doubles. Mark Seeman has also written an excellent article explaining when to use Mocks and Stubs.

In a Mockist TDD context, one would pass A‘s collaborators by constructor parameters and then test the behaviour of A when it interacts with them. Such behaviour can be verified using a mock object.

A Mock is an object that has expectations of interactions with other objects. It is used to verify that a call which was expected to happen really did happen.

Examples

The tools used for the examples are:

Classic TDD

As said before, classic TDD is easier to use in an algorithm context. Let’s take as an example the Leap Years Kata.

Write a function that returns true or false depending on whether its input integer is a leap year or not.

A leap year is defined as one that is divisible by 4, but is not otherwise divisible by 100 unless it is also divisible by 400.

For example, 2001 is a typical common year and 1996 is a typical leap year, whereas 1900 is an atypical common year and 2000 is an atypical leap year.

A typical code base written with classical TDD would end up with several test cases trying different inputs and expecting specific outputs.

Mockist TDD

It is hard to come up with simple examples that illustrate where mockist TDD really shines. We will try to do it with an example involving a Web API. Let’s imagine an endpoint that returns a username when it is given the user’s id.

Some people would arguably remove the first test because the behaviour it is verifying is also covered in the other tests. This is a matter of personal preference.

The design that emerges from these tests is directly linked to the use of mockist TDD, and by the objective of getting a piece of code that’s as easy as possible to test. This is where the collaborating classes (the factory and the user information service) came from.

What should I use?

There’s unfortunately no definitive answer. Both are good, just in different situations. It’s mostly a question of trade-offs and of preference. Here are a few points to consider:

Generally

  • Classic TDD is better suited for algorithm testing
  • Mockist TDD is better suited for to check interactions between components of a system
  • Mockist TDD will create many collaborating classes early in the process. Classic TDD will push the creation of collaborators to later in the process.
  • A code base written with mockist TDD is harder to refactor because a change in a collaborator’s API is likely to break a test.
    • Some people suggest looking into ATDD to help with this problem.
  • A code base written with classic TDD is easier to refactor; an implementation change doesn’t break tests
  • Mockist TDD leads to an end-to-end implementation easily when using a Walking Skeleton.

Conclusion

Classic TDD works better when testing algorithms and Mockist TDD when verifying interactions between the components of a system.

Using dependency injection typically reveals a class’ dependencies explicitly, and allows us to substitute them easily with objects having controlled and predictable behaviours (test doubles).

The purpose of this post was to introduce the fundamental ideas that will serve as building blocks for later articles in this series. Don’t worry, there will be more code and less theory in the future posts.

The next article will be an overview of Jukito, a library built on top of JUnit and Mockito. Knowing how to use Jukito is pretty important. Although it is not strictly necessary for testing GWTP applications, it will be used for the rest of the series, since it saves a lot of time.

Subscribe to our newsletter to be notified when the next post comes out!

Happy Testing!

Other good references

Dart Developer Summit Highlights – Day 2

Hi again Dartisans. Here’s the second post I promised you. For those of you who haven’t seen the first post, I made a summary of the Dart Developer Summit 2015.

Keynote: Ads

Ferhat Buyukkokten and Ted Sander highlight how Google’s Ads team uses Dart to build their web applications. This is a good demonstration of how Dart can interoperate with other existing systems. It’s also a nice confirmation that Google is dedicated to Dart for its new projects.

  • Updating a CRM system
    • Change the back-end in flight
  • Before Dart, there was frustration
    • Changes were slow and hard to implement
  • They really didn’t want to try languages without types at Google
  • Fast, even as JS
    • Dart is just as fast as handwritten js for several benchmarks
    • Sometimes faster and sometimes slower, but not by a lot
  • Batteries included
    • Great tooling
    • Package manager
  • Internal/External libraries were easy to use
  • dart-mockito is their mocking library – it just works
  • Large-scale applications with good performances
    • observatory helped diagnosing where the pain points were
    • low and stable memory usage
  • Communicate through different apps using a JavaScript event bus
    • AdWords is built with multiple apps – GWT, Dart, etc. and they talk to each other
  • Divide and conquer
    • Even if you could start of scratch, it’s still a good idea to keep your application in modules
  • Google Ads are committed to Dart
    commitment

Instill.io

Mathieu Lorber and François Saulnier from Instill.io explain how they managed to build their video creation web application with Dart as their front-end technology. Yet another good example of how Dart can be used with other technologies (in this case Java) for the back-end. They also explain in details how they transitioned from Angular.Dart to Polymer during their development. It’s interesting to see how they did it, because I personally did the opposite (moving from Polymer to Angular).

  • Why Dart?
    • All about productivity. They had a debate on whether they should start with technologies they know, after a long discussion they agreed that Dart presented all the advantages of the technologies they knew, and they decided to start with Dart.
  • Architecture
    • Dart front-end
    • Java back-end
      • CQRS + event-sourcing
    • Movie rendering layer
    • Publishing layer
    • Message queue
      architecture
  • The Java back-end can be painful when coming back from Dart
  • They use Angular.Dart for their application framework
    • It was hard in Angular.Dart 1.0 to create small isolated components
    • It was hard to programmatically add a component
  • They now use Polymer for their components instead of Angular
    • They can now reuse small components
    • They now use Polymer elements as DOM elements in their Angular application
    • Angular controllers are now stateful Polymer components
    • Routing is now a Polymer component too
  • What they miss from Angular.Dart
    • Injection and services
      • Dependency injection can be reused independently. They created an @Inject() annotation
    • The Scope
      • Communication between components
      • Internal change tracking
        • Polymer data-binding
      • Communication between non-related components
    • Routing
      • They didn’t really miss it, they introduced a notion of Places. However you can still use Angular.dart routing package independently.

Building Production Dart Apps with an Open Source Workflow

Devon Carew and Luke Church built DartPad, an IDE for Dart in the browser, as open source and with open source. In this session, they show you how to unit test, measure code coverage, trigger Continuous Integration, and deploy to the cloud, all with open-source tools and libraries. The most interesting part about the tools they presented here, is how they leverage the power of Google Cloud Platform with AppEngine, the Managed VMs and the Memcache.

  • How they built DartPad
  • Continuous integration for unit tests
    • Travis CI
    • Drone.io
    • AppVeyor (windows)
  • Functional Testing
    • Sauce Labs
    • test/web_integration.dart with WebDriver
  • Code coverage
    • Package dart_coveralls and coveralls service
      • Get notifications on specific threshold
  • Web hosting and scaling
    • They use AppEngine
    • UI Server serves static files & redirect
    • dart-services in AppEngine
  • Dart on AppEngine
    • The Dart app deployed on AppEngine routes to a Dart process in a Managed VM
    • The process in the ManagedVM uses the rpc package
    • Making it fast
      • Memcache
      • Keeping the VM warm
        • Reusing Dart VM
        • Uptime monitoring
  • Hosted metrics
    • Librato – hosted metrics and logging service
  • Uptime monitoring
    • Pingdom – update reports services
  • DartPad is now 1.0!

Panel with Dart Engineers

I decided not to put all questions and answers because some of them were a bit too specific, but here are my favorite ones, which I think will be of interest to more people.

  • Q: How does type annotation impact performances?
  • A: On the VM specifically, it doesn’t matter at all whether you type your variables or not. When the code is parsed (unless in checked mode), we throw the types away. The optimizations are based on collected types that you see at runtime, and it works well; they know exactly what are the potential subclasses that can be used.
  • Q: Is there any plans on doing code hot-swapping in Dart?
  • A: It would probably work well already in the VM, but there are plans to find good solutions to that in the following months.
  • Q: DartEditor vs Webstorm?
  • A: We’re moving away from DartEditor, and going with WebStorm. The other goal is to provide a good UX to people who are already familiar with other tools via plugins (Eclipse, Sublime, etc). For the “try-dart” experience that DartEditor was giving, we suggest going with DartPad now, where you can try things with low friction, share snippets and make things run. WebStorm is the primary focus.
  • Q: What’s the roadmap with Polymer.Dart?
  • A: We’re waiting for the Polymer team to stabilize. It’s coming pretty soon. When they reach Polymer 1.0, we’re going to provide Polymer.Dart 1.0. Second thing is with dev_compiler and jsinterop, you will be able to share your components/libraries with other developers (dart/js).
  • Q: What will happen if Fletch gets out of experimental?
  • A: We will ship it this year.
  • Q: Dart vs ES6? Does ES6 provide all what Dart does?
  • A: Dart still has an advantage. ES6 is still JavaScript, and you don’t fix all problems by adding classes. The types in Dart still make programs easier to read and easier to maintain.

Google Fiber and Dart

Jason Daly shows how they created the UI of Google Fiber with Dart, and how it integrates with other languages in their infrastructure. With all the other alternatives to Dart, he also explains why they still picked it, and what they got out of it. It’s a good example of how Dart can be used on embedded devices, not without good challenges.

  • How they created the UI with HTML5/CSS3 and Dart
  • They have Dart-VM-based services interacting with native code
  • Their new solution
    • They wanted to move lots of data on the cloud instead of on the boxes in households
  • Why Dart?
    • Looks and feels like many other languages
      • Classes, generics, strict type checking (when you want it), libraries and imports
    • Still has the dynamic and asynchronous features that web apps need
    • Not limited to browser and web apps
    • Development wins
      • Easier to pick up than JavaScript
      • Dartium makes prototyping easy
      • Allows on-the fly rendering of UI tweaks
  • Deployment wins
    • Deploy to a url for the UI
    • Server-side can be updated without deploying a new firmware image
  • Challenges
    • No pointing device (no mouse) — had to develop their own widgets
    • Limited physical resources
    • Dynamic fetching
    • Interfacing with the hardware
  • The browser cannot do everything
    • Interactions with the disk
  • DVR Service
    • Runs in the Dart VM on the Google Fiber Storage Box
    • Interacts with the TV UI running in Chromium on the TV Box
  • Dart works well on embedded hardware

Dart for the Internet of Things

Dennis Khvostionov of DGLogik shows their new IoT platform called DSA, and how they implemented it end-to-end with Dart. We can see their WYSIWYG IoC application editor (DGLux) built on top of their Open Source platform (DSA).

  • DGLogik
  • DGLux – Drag and drop WYSIWYG Visual Application Development
    • > 200k Dart LOC
    • > 1k deployments globally
  • Why Dart
    • Rapid developement
    • Rapid testing
    • Rapid fixing
  • dart2js has never been problem for them
  • DSA – Open Source Platform & Toolkit for IoT
  • A bunch of demos, should watch them.
  • He shows us a game called “performanceTest” that allows us to see the whole thing in action, it runs pretty smoothly!

Moving from Node.js to Dart

Faisal Abid tells how he ported the API of his native Android stock simulator game Market Wolf from Node.js to Dart. Since Node.js is so popular, many people probably asked themselves whether Dart or Node.js would be the best choice. Here Faisal explains why he went to Dart, and what’s been beneficial for him since then.

  • Why?
    • Tooling & debugging support for node.js is a pain
    • Node.js didn’t seem to be the right answer
    • Node and Dart are pretty similar
  • Differences
    • Different paradigm
    • Multiple cores
    • Node – multiple VMs needed
    • Dart – Isolates
  • Pros and cons to moving to Dart
    • Pros
      • Better profiling and debugging with Observatory
      • Syntax and language features
      • Organization of code is better and enforced
      • Support for major databases on pub.dartlang.org
    • Pro/Con
      • Shift in thinking
    • Con
      • Missing support for esoteric and very new database. But most protocols are JSON based, so it’s easy to port it
  • Finding alternatives to what he was using in Node.js
    • Express
      • Redstone
        • Actively developed by community
        • Very express-y
        • Good support for plugins/middlewares
      • Shelf
        • Written by Google
        • The base for Redstone
        • Minimal
        • Use middleware for routing
        • Redstone’s middlewares come from Shelf
        • Simple API
      • RPC
        • The newest
        • Enables you to write RPC style Dart API’s easily
        • Self documenting API
        • Uses annotations
        • Bit more verbose
        • Very clear API
        • Can generate client side libraries in Java, Python and others
    • Socket.io
      • Dart comes natively with WebSockets
  • Thinking in Dart
    • It’s easy to replicate Node.js, but you must think in Dart
    • Simplify architecture by using Isolates
  • Isolates are very low on memory footprint
    • He used to have 3 node.js VMs + 1 message broker, now he has 3 isolates @ 1.5MB of memory each
  • Deployment
    • Anything that supports Docker supports Dart
    • Codeship + AWS Beanstalk
  • Worth it?
    • Yes. No question about it
    • Dart language, language features, observatory, etc.
  • Missing anything from Node.js?
    • Absolutely not.
  • Amount of lines of code shrunk dramatically. Easier to debug, deploy, less dependencies to worry about.

moving-from-node

Dart for Mobile

Kasper Lund presents a demo of Fletch, an experimental runtime for Dart that makes it possible to implement highly concurrent programs in the Dart programming language. He shows how it can make native applications run on Android and iOS.

post_dart_conf_v2-06

  • Why do people want to use Dart on mobile?
    • Modern and light stack
    • Developer productivity
    • Code sharing across multiple client apps
      • Use same model but different UIs
  • Fletch — Dart runtime for mobile
    • Still early stage
    • Small and elegant runtime system
    • Supports on-the-fly program changes
    • Runs on iOS through interpretation
    • Light
      • Extremely fast startup (~2ms)
      • Low memory overhead (~200K binary size)
    • Interactive
      • Atomic program changes over wire protocol
    • Concurrent
      • Blocking an isolate is simple and cheap
      • Easily scales to 100k concurrent isolates
  • Fletch SDK
    • Command line
    • Breakpoints
    • Live code editing in your editor and apply changes with the command line
  • Roadmap
    • Q3 – Fletch SDK Beta
    • Q4 – Fletch SDK 1.0
    • Q4 – Dart for mobile 1.0
      • Will contain the toolkit for Presentation, Services and Runtime
  • Interop
    • Intermediate language declaring services in low level
    • Implement them in Dart
    • Fast messaging
      • Messages are transferred as binary
      • No expensive encoding/decoding
  • It’s not the fastest thing ever as it’s interpreting code, but it’s most of the time way enough for real things.

Sky: An Experiment Writing for Android with Dart

Eric Seidel presents Sky. Sky is an experimental, high-performance UI framework for mobile apps. Sky helps you create apps with beautiful user interfaces and high-quality interactive design that run smoothly at 120 Hz. This presentation contains multiple demos, and gives us a little sneak peek of the a functional programming style inspired by React that Sky uses. It will be fun to see how in the future Sky and Fletch will interact (if they will).

  • Sky Demo on Google Play
  • Android app all written with Dart (even the UI) Native
  • Best mobile experience
  • Looking for performance
    • 120Hz or bust
  • Platform agnostic
    • Android, iOS and more
  • Full Access
    • Fully priviledged applications
  • Fast development
    • Edit, Refresh, Profit
  • Continuous deployment, it’s always up-to-date
  • Rich & flexible layout & painting
  • Still early stage
  • Hello world live coding demo
  • Sky Framework
    • Written in Dart
    • Big bag of widgets (Material Design)
    • Entirely non-blocking API
    • Functional reactive style (Stateless components)
    • Opinionated part of Sky that knows on what kind of device the application is running on
    • Integrated tools
      • Chrome tracing
      • Observatory in the device (can connect remotely)

 

Dart Developer Summit Highlights – Day 1

Update: The highlights of the day 2 are out!

Hello Dartisans, I’ve had the chance to watch the Dart Summit live streams and I’ve been a good student. For all of you who don’t have time, or are just interested to remember what was said, I’ve taken notes during all the presentations.

Disclaimer: These are my personal notes, to the best of my comprehension. If you find anything wrong with them please let me know and I’ll update this post. Also, if you feel I missed some important information, let me know, I’ll update this.

So I’ve structured the highlights by talk, stating what I found the most interesting or thought was the most important. I’ve noted most of the information as bullet points.

This first post only contains notes about the first day of the summit. A second will come in the next days, with all my notes for Day 2.

For all of you who want to watch the whole talks, there’s now a Youtube Playlist available. Enjoy!

Keynote: Dart Today & Tomorrow

Dart co-founders Lars Bak and Kasper Lund who are Software Engineers at Google, tell us what’s coming in the next year for Dart and its ecosystem. I like how they’ve put emphasis on how Dart is there to stay for a long time, and how Google uses it.

  • IDE
    • WebStorm is now the new IDE of choice for Dart development.
  • Mobile
    • They showed 3 native mobile apps having a dart model and different UIs. (iOS and Android and also a dart console app.)
    • Fletch: A Dart runtime for iOS
      • Only adds ~200K to the size of your native app
      • Supports on-the-fly program changes
    • Parallel programming
      • People like the idea of isolates, but don’t like to use isolates
        • Features like Parallel.run() should come
      • Research directions
        • Synchronous operations
        • Zero-copy message passing
        • Lightweight isolates
    • Dart LTS
      • Google is already relying on Dart for many projects including: Google Ads, Google Fiber, Google Express, Google’s internal CRM app.
      • They are committed to building their next-gen web apps with Dart
      • Dart is for the long run.
    • Web Frameworks
      • Angular 2.0 will be the preferred web application framework for Dart
        • Smaller generated Javascript output
        • Faster execution (x3 faster than 1.0)
  • SDK Roadmap
    • May 2015 : Migration to GitHub
    • 1.11 – Retire DartEditor, and put in front WebStorm as IDE (and plugins)
    • 1.12 – Http2 + Google RPC
    • Q3 – Fletch (beta)
    • Q4 – Fletch (final)
    • Q4 – Dart Mobile Services
    • 2.0 – Dart Dev Compiler
  • Breaking Changes
    • Future SDK version should all be backward compatible. If a breaking change is introduced, they will provide a migration tool to migrate your code.

Async in Dart

Florian Loitsch, Software Engineer at Google presents Dart’s asynchronous features. He makes a very good introduction to async/await and its derivatives for Iterables. He also presents the package stack_trace to get more useful information from stack traces for asynchronous code.

  • Async/Await now work out of the box
    • Also works with dart2js web applications
  • Stack traces are noisy and contain not-so-useful information for the normal Dart developer
    • The package stack_trace makes it easier to get relevant information in stacktraces with async-await

Space-Frugal Reflection

Erik Ernst, Software Engineer at Google shows how using traditional reflection might not always be a good choice, especially for Web applications in Dart. He then brings on the table a solution to the problem of increasing code size: the new package Reflectable.

  • Traditionnal reflection in Dart is expensive
    •  For dart2js web applications, code size explodes because of tree-shaking
  • dart:mirrors
    • Compiler-integrated
    • Uses nice, compact reprensation
    • Control size with MirrorsUsed(…) annotation
    • Includes more code, not compositional
    • In practice, it is difficult to tune, large output
  • Reflectable
    • New package for reflection
    • Essentially the same interface
    • Without the size explosion
    • Still early stage
  • Traditional vs Reflectable
    • Traditionnal: mapping between original names and generated ones
    • Reflectable: write more code, but the generated code will be replaced with static code

Dart at 60FPS

Ross Smith and Arturs Vitols of Willowbrite tell us their story of how they made a mobile game with Dart. They present us what their biggest challenges were, and how they succeeded. I couldn’t resist buying the game to try it. Ends up being pretty fun! Get it here. I was also very impressed by their home made editor.

  • Challenges
    • run on old devices
    • < 20mb
    • performances
    • unique look & feel
  • How they did it
    • Vector images –> ask device to process instead of using disk space.
    • Midi sound –> ask device to process instead of using disk space.
    • Short refresh cycles with webgl.
  • They made an editor – very impressive.

Debugging and Profiling Dart Programs with Observatory

John McCutchan and Todd Turnidge, Software Engineers at Google give us an overview of the Observatory in Dart. This is probably my biggest surprise of the day. I didn’t know much about the Observatory, but wow, I’m surprised at how advanced it is, and at how much it can do. I’ve taken a lot of notes here, you really should watch the whole demo.

  • Hosted by the VM
    • Providing suite of program inspection and analysis tools.
  • New link in JS console
  • View class code
    • View code coverage
    • Find live instances of specific classes
    • Invoke/edit live code (classes/instances (add methods to instances/changes values))
  • Allocation profile
    • Per class allocation statistics
    • Per heap space garbage collection statistics
    • User controllable accumulator
  • CPU profile
    • Find spots in code that use a lot of CPU
  • Debugger
    • Command line debugger
      • Provides live debugging in observatory
    • Tab completion (functions, scripts)
    • Lets spy on variables (visually)
    • Lets you edit variable content
  • Multiuser
    • Multiple users can connect to the same observatory, just share the URL
  • Always available –> Runs on its own, and always collects
    • Easier to diagnose problems that happened in the past.
  • Profiler now understands functions inlining
  • Now provides metrics/graphs
  • Roadmap
    • Improved debugger
    • Timeline of important events
    • Allocation call sites (where do I allocate class Foo)
    • Display source code as live, hyperlinked view
  • Available wherever the VM is available.
    • Server/Command-line
    • Sky applications
    • Web applications in Dartium

Dart for the Web: State of the Union

Dan Grove and Kevin Moore, Software Engineers at Google tell us what the current state of Dart is, and in which direction the Dart team will go for the next year. This was probably the talk I wanted to watch the most because of the recent changes related to the Dart team’s objectives (with the VM not going in Chrome). There were great announcements during this talk.

  • Embrace the web instead of replace the web
  • Things have changed in the web (ES6)
  • Javascript everywhere
  • Changed the focus from integrating the VM in Chrome to embrace JS and target all other browsers
    • Development & deployment/production were too divergent
  • Dev compiler vs Production compiler
    • Dev compiler should contain settings for development/deployment to keep a fast refresh cycle for dev.
  • Dev Compiler
    • Its aims to include the following:
      • A static checker based on stricter-than-standard-Dart type rules.
      • A modular Dart-to-ES6 transpiler for Dart programs that statically check.
      • Under 1 second compile
      • Would produce small, readable, clean, efficient JS code.
  • Export your Dart library in JavaScript (SYODLAJ: Ship your own Dart Library as JavaScript)
    • Someone shouldn’t notice you’ve written your lib in Dart
  • They still want to ship Dartium for now, but are working in parallel on getting Dart Dev Compiler out.
  • Test package will be the future of testing in Dart
    • The test package uses stack_trace out of the box
    • Supports multiple platforms (vm, browsers, chrome, safari, dartium, content_shell, phantom-js)
  • Frameworks
    • Angular2 is now in Dev preview (It is still marked as alpha-21, but Angular Team consider it as Dev Preview) (website is now angular.io)
    • Should wait for Polymer to be stabilized
  • Webstorm IntelliJ is now the “De-facto” IDE.
  • Coming soon
Angular 2.0 is now in Developer Preview

Getting the Most Out of dart2js

Stephen Adams, Software Engineer at Google shows us how static analysis and type inference work in dart2js. He also gives tips to help dart2js producing smaller, faster JavaScript code. This should be watched by anyone who is confused (or are not sure) about how the type system works in Dart.

  • How dart2js currently works
    • Compile dart types to JS primitives where possible.
    • In checked mode, the types will be checked at runtime. Checked mode works like assertions on types. It asserts “is this a String or null” (for a String annotated variable)
    • In production mode, those assertions are turned off.
  • This talks explains how dart2js works in technical details (how type inference works for example)
  • Things to do in production, but are OK to use for testing
    • Avoid dart:mirrors, use code generation instead (e.g: smoke, reflectable, polymer)
    • Avoid noSuchMethod, otherwise it will produce slower and bigger Javascript (adding more two-level dispatch/more indirections)
      • If you use dart2js -v … you will see what those classes implementing noSuchMethod are.
    • Avoid o.runtimeType -> defeats type erasure optimization
  • What’s coming next?
    • Looking at ways to improve type analysis
    • Looking at ways to make better use of inferred types
    • Looking into making two level dispatch cheaper

Switching to Dart

John Ryan of Workiva explains how they switched to Dart in an existing big scale application. He presents us why they switched, what they got out of it and how they did it. This should convince people who think that Dart doesn’t scale well or that it doesn’t blend well with other technologies.

  • They switched from ActionScript
  • They tell their experience of porting an existing application to Dart
  • After switching
    • Faster ramp up time
    • Better dev experience
    • Less focus on tools
    • Code easier to share
  • Why they switched
    • Build large scale apps
    • JavaScript tools are difficult to compose
    • Dart is a complete solution
  • The old application
    • over 1 million lines of code
    • 2-8 mins to compile
  • How they switched
    • React components –> React Dart
    • Unit tests –> Jasmine Tests –> Guinness –> unittest
    • Convert the existing Javascript into a working application, and then write idiomatic Dart
  • The Dart VM
    • Debugging is fast, predictable
    • Switching branches is cheaper (with pub)
  • Checked code
  • REPL in Dartium
  • Continuous integration
    • Their docker file for it
      • Should be modified a bit for the new test package, but it has useful things, like a script to install content_shell
    • WebDriver for functional testing
      • WebDriver.dart – Looks pretty good with async/await
    • Tests are written in Dart

Migrating Trustwave’s Large Customer Portal to Dart

Eric Woerner, Director of Software Architecture at Trustwave tell us their story of migrating their customer portal to Dart. We learned what they discovered, what frameworks they use, and how they leverage the power of each of them. I was surprised at how they integrated Dart to an existing Flex application.

  • They tell their history of migrating Trustwave Portal to Dart (Flex to Dart)
  • They serialize data to and from existing Java back-end services
  • What they discovered
    • Increased productivity
    • RPC style calls with Dart
    • Application development with Angular and components in Polymer
      Dart and Flex interop
  • What they now use
    • Application framework: Angular Dart
      • Deferred loading
      • Routing
      • Views
    • UI Components: Polymer
    • What’s next?
      • Angular 2.0
      • Polymer 1.0

 

Gwt-Platform event best practices (revisited)

Not too long ago, I started using GWT and GWTP and found it pretty hard to understand its event system.

I still can’t find much recent information about it, so I am writing this post to hopefully help others. Disclaimer: There many ways to achieve what I do in this post, but this is the way I prefer.

All right! Let’s demonstrate how events and the event bus work by creating a CSI-Hacking Dashboard. You can get the code on GitHub.

 

We have ComputerPresenter, a HackerPresenter and a root Presenter that holds/creates other widgets. We also have a ComputerHackedEvent and ComputerHackedHandler. The event will be raised to signal that the computers got hacked, and the handler code will be executed after that.

Here’s the classic implementation of a GWT event. Our event will only carry the hacker’s name.

I usually declare my handler as a nested interface in the event declaration. That’s only a matter of personal preference though.

Next we have to raise the event. That will be done by our HackerPresenter. A really simple way of becoming a computer hacker, is by adding a button to the screen and pressing it, right CSI?

Here’s the code of the view and the presenter.

So we have a button, and when we click on it, it raises an event. There are a couple of ways to raise an event, but the one I usually use, is the static fire() method on the event. (I’ll talk about the other ways of firing an event later on.)

Now we have to handle the event somewhere. We want to know when the computers get hacked, so we’ll represent the computers with the ComputerPresenter. Its role will be to print in the console when it gets hacked, and by which hacker. Here’s the presenter code:

This way, when a hacker clicks on the “start hacking” button, all the computers that are listening to the event will print something. As you can see, the ComputerPresenter registers itself as a handler for the ComputerHackedEvent through the addRegisteredHandler method.

This is a convenience method provided by GWTP. Using this method instead of registering directly on the EventBus will make the event registration part of GWTP’s lifecycle and unbind the event handler when the presenter is unbound. That means that if the presenter is unbound and rebound, you’ll have to re-register event handlers. This is why the onBind method is a good place to register handlers.

Here’s the code of the root presenter:

We just create one hacker named Zer0C00L and 2 computers to hack. And now the view:

 

Nice! When I click on “Hack the planet!” I see the following result in the Javascript console:

I got hacked. (A) by Zer0C00L
I got hacked. (B) by Zer0C00L

I should start writing in l33tsp33k now.

Now what if you remove one of the ComputerWidgets from the DOM by calling removeFromSlot(SLOT_COMPUTERS, computerB); and still try to hack the planet?

If you read the output of the console you will see:

I got hacked. (A) by Zer0C00L
I got hacked. (B) by Zer0C00L

Wait… What? The handler for the computer B is still registered, the presenter wasn’t unbound, it was only removed from the DOM.

What if we want computer B to stop listening to the events when it’s not present in the DOM? Well that’s a job for addVisibleHandler. So instead of registering the handler using addRegisteredHandler we’ll use addVisibleHandler that will handle this for us. This way, when a presenter is considered “not visible” in GWTP’s lifecycle perspective (read: not visible as in “visible in the DOM”), the event will not reach the handler. The new output should now be:

I got hacked. (A) by Zer0C00L

There’s still a problem though. What if there were too many computers for a single hacker? I think at some point we’ll have to add someone to the team. Let’s do it!

You should see 2 buttons saying “Hack the planet!” and when you click them both, the output is:

I got hacked. (A) by Zer0C00L
I got hacked. (B) by Zer0C00L
I got hacked. (A) by AcidBurn
I got hacked. (B) by AcidBurn

All computers are reacting to every hacker, which is not what we want. This is happening because of the way we registered the handlers earlier. What we want is for the computers to react a specific hacker’s ComputerHackedEvent.

Since we can have a reference to the said hacker, that is pretty easy to accomplish. We have to delegate the handler registration to the concerned presenter. From the RootPresenter we’ll delegate the task, but first let’s create an interface :

We can then let ComputerPresenter implement it.

Note that instead of registerHandler() you can also use registerVisibleHandler().

And finally, when you click on both buttons, the output should be:

I got hacked. (A) by Zer0C00L
I got hacked. (B) by AcidBurn

All right! We’re ready to hack the planet! Are we?

Remember when I said I would talk about the ways of firing events? If you are new to GWT and GWTP, you might have noticed that there are multiple methods available to fire events and register handlers.

Confused yet? I can say I was after seeing this. If you dig down you can see that a presenter widget gets an event bus injected and delegates most of its job to it. The only difference is that GWTP manages the handler registrations with its lifecycle (i.e: when a presenter gets unbound, the registered handlers get cleared). Also, if you dig for the fireEvent method, you’ll see GWTP delegates to eventBus.fireEventFromSource(). You may want to call the original fireEvent() if you want to match the following case (taken from the javadoc) “Fires the event from no source. Only unfiltered handlers will receive it”. Honestly, I’ve never faced that situation.

Here’s my cheat sheet of events in GWTP:

– Do I need to fire an event globally on the event bus? (i.e: everything registered to the event will handle it)
Y: presenterWidget.addRegisteredHandler() + SomeEvent.fire()
N: Go next

– Do I need to filter the handlers by the visibility of the handler?
Y: presenterWidget.addVisibleHandler() + SomeEvent.fire()
N: Go next

– Do I need specific handlers to handle events from a specific source?
Y: Create an interface called HasXXXHandlers and make your handling presenter implement it. GWTP gives PresenterWidget the capability to register handlers via registerHandler() and registerVisibleHandler(). Finally, fire the event with SomeEvent.fire()
N: That’s it. I usually don’t need more options, so the decision tree ends here. If you have another situation that doesn’t fit, let me know!