Better Android Intents with Dart & Henson

Buster Keaton — The Battling Butler
  • The intent creation is not robust (at all), there is no check on the keys or values attached to the extra bundle.

An ounce of prevention is worth a pound of cure.

Problematic ways

A possible solution to those concerns is the Intent Factory pattern. It mainly consists in a factory class which encapsulates methods for every kind of Intent that an application needs. For our example, this might be the Intent Factory:

  • It infringes the Meyer’s open/closed principle. It will never get closed, we will always add new methods for each new activity.
  • The target component is the one which knows about the parameters, it should be the one containing the logic.
  • Optional parameters handling. Should we have a bunch of different methods for the same component? Just one method and send default values?
  • It can quickly become tempting for developers to couple methods of the intent factory, one calling others.. and this will become a big ball of mud.


Dart 2 & Henson

Dart is an Open Source library for Android. It binds activity fields to intent extras, in the same way Butter Knife does between activity fields and views in XML layouts. Applying it to our example Activity, it evolves into:

  • The DSL is defined in one place, inside the component. If it is updated, any issue is found at compile time.
  • The Meyer’s open/closed principle is not violated. Indeed we have nothing to write, everything is generated for us
  • Optional parameters can be easily provided, since the builder design pattern is used.
  • And it comes with auto-completion!

Conclusion

Henson creates a small DSL to build intents to your activities and services in a robust way, making it impossible to miss a required extra and flexible enough to add optional arguments as needed. And the best of it, there is no need to write a single line of code, just use Dart 2 and Henson. 😊

Groupon Engineering

Tech blog from Groupon Engineers

Daniel Molinero Reguera

Written by

Software engineer, Science geek

Groupon Engineering

Tech blog from Groupon Engineers