PSA: Hard Won Tips For Cordova/Phonegap

The last couple of months I’ve been diving deep into a project built with Cordova/Phonegap and React.js. Of those two I think React has been the bigger revelation to me, but today’s topic is a couple of tips for Cordova that were hard won.

Causes of ‘deviceready has not fired after 5 seconds’ message

In the console you may see the message deviceready has not fired after 5 seconds along with one or more other messages about channels not firing. This is a particularly difficult error to troubleshoot because there are several possible causes. Basically anytime Cordova fails to start properly this error will display after a 5 second timeout.

The problem is often related to a plugin, because plugins are loaded before the deviceready event is announced. So the first thing to do is to identify the plugin that is causing the problem. Three methods;

  • look at the other messages that are logged, they may identify which plugin didn’t load.
  • remove plugins one by one until deviceready event does fire.
  • create a new empty Cordova project and add plugins into it one at a time until it fails.

If you are able to identify a plugin that is at fault then look to see if there are any updates that may fix the problem. If not you can file an issue against the plugin or contact the maintainers for support. If nothing else you’ll have narrowed your search terms to look for a solution.

However, if it is one of the plugins that is failing, it might not necessarily be an error with that plugin. So try removing your application javascript and only including the cordova.js script to confirm that the plugin fails in an empty app.

In my case a boilerplate project I was using was overriding the global object window.prompt. This is a problem because Cordova actually uses window.prompt as a backup method for bridging between javascript and native API.

So why would window.prompt be overridden if it’s so necessary? I’m guessing because until recently Cordova didn’t have the Browser platform. Instead you could use phonegap serve or cordova serve to run a webserver that serves /www/assets. But this will cause a prompt to appear in the browser, several thousand of them in fact.

Which leads me to my next bit of knowledge…

Serve Platform Browser Instead of Serving www/assets

Cordova recently introduced a Browser platform which is meant to support development by allowing the app to be run in a web browser on the developers desktop workstation (instead of a WebView on the device). Core plugins are being updated to support this platform and third party plugins are being encouraged to do the same.

Now, I’ve not figured out all the differences between phonegap serve and cordova serve, but I think phonegap serve is meant to serve pages to the Phonegap Developer App that is installed on a device. So it serves the Android platform when the app is installed on an Android device. This is pretty nifty, but I’m more comfortable in a web browser for some development modes. It doesn’t appear to offer any way to serve the Browser platform to a web browser.

However, cordova serve does serve the Browser platform. Run cordova serve then browse to Replace the port with the port indicated by cordova.

If your plugins support the Browser platform then your app should play nice with a web browser. If not, well then you’ll probably have to add some conditional code into your app for alternate behavior in the browser where the plugin isn’t available.

Code Quality Matters: Success

I’ve had a bit more time recently to reflect on the importance of Quality Code since I first defined it. If you don’t recall, my definition of Quality Code is this;

Quality code is code that can be changed, as needed.

In the introduction to that post I mentioned that I’ve experienced debate about whether or not code quality is important. I think it is and today I’ll give just one reason why.

Success is important.

Success is important isn’t it? It’s a bit nebulous though, so let’s be clear. I’m talking about real professional and raw commercial success. Making money. Gaining customers and revenue. For most of us that’s what it’s all about ultimately. If you’re a hobbyist then only your personal enjoyment defines success. Professionals have to compete.

You’ll be out of a job if you write bad code, sooner or later.

Many development teams hire on a trial basis. I’ve seen a few new hires that weren’t offered a full time position after their initial contract was up. The code they wrote just wasn’t good enough. It caused more work for the remainder of the team. It had hidden bugs that increased the burden on the maintenance team. It couldn’t be reused without refactoring it. Peer reviews took much longer because there were so many changes needed. Sometimes pair programming was necessary just to get anything done.

Sometimes even good programmers write bad code though. An approaching deadline is immutable and so are the requirements. Cutting corners is the only recourse, but that leads to bad code. It works, but it can’t be changed as needed. When it hits a critical mass…

Projects can fail.

It becomes too hard for the project to change to meet changing needs of the stakeholders. Or the project is too unstable. Customers are unhappy. Something has to be done to fix this. Sometimes that means starting over from scratch. You might not get a second chance to fix your mistakes. That’s just the nature of business. Would you choose any differently? Would you entrust a critical rebuild to the same team that made it necessary?

Here’s the kick on the way out though, it won’t be just you and your teammates. It might be the support staff your project supported. Administrators, testers, the project manager. As a developer you may have recruiters calling you that same day. Is the same true for the people you worked with?

Organizations can fail.

Even if the project isn’t ever scrapped, it can still be a failure. When that happens the organization itself can fail. Customers leave quietly. Sales drop. Staff reductions are necessary to stay in business at all. Soon the project is in maintenance mode, there aren’t enough resources to do anything but keep it alive. Ultimately the company goes out of business or is sold off by the owners.

Bad code can ruin a business, your career, and the careers of people you work with. The stakes are high in the professional world and the challenge is all the harder because many stakeholders don’t know they care about code quality. They do care about getting things done when and how it’s needed. Only Quality Code can enable developers to meet that standard. The responsibility for it is ours.

Event Sourcing

Yesterday an article was posted on Wired about code quality. The first part of the article is a fantastic and accessible explanation about what happens to applications when the underlying code is poor quality. If you wonder why code quality is important, read that and see if you’d like that to be a description of a program you rely on.

The article then goes on to recommend a solution, Event Sourcing, to the problem of code which has become an incomprehensible tangle of dependencies.

First though, I must say, there is no one best way to write code. There are many wrong ways to do it. The right solution is the one that meets the needs of the users and stakeholders and is flexible enough to be changed as those needs change.

Event Sourcing, as I understand it, consists of three main principles.

  1. Announce events as they happen.
  2. Store the events.
  3. State is a result of applying events in order.

An event driven architecture, also sometimes called Pub-Sub (publication-subscriber), is a proven way of breaking dependency between parts of a system. Operations that don’t require a response (there are many more of these than you might imagine) are announced instead of being processed immediately. Listener(s) passively receive notification of the event and the details of the event which they then process.

Not only does this make performance appear better to the end user, but it also allows discrete parts of the system to work together without knowing anything about each other.

Storing the events after they’ve been processed isn’t unusual either, at least for a period of time for auditing purposes. Debugging an event driven architecture isn’t as simple as debugging an imperative program.

The interesting part of this design is that state isn’t stored, only the events. When state is needed it’s assembled by replaying all of the events back in order. Not having any experience implementing this design, I’ll withhold judgement (and recommendation), but I do wonder about performance as the amount of data increases. Every design has it’s strengths and weaknesses.

Most of the benefit of breaking dependencies in this design come from the use of events, not from the use of events as a storage of application state.

What is Quality Code?

Code quality is a topic of a surprising amount of debate in my experience. Most of that debate has been amongst colleagues about the minutiae of coding standards and whether or not a certain solution is better or worse than an alternative. What’s most surprising though is the debates about whether or not code quality is worth the effort or even if it is important at all.

Before we can address that though, we’ll need to agree on just what quality code is. I’ve heard lots of opinions about it over the years, here’s a few of them.

Quality code works like it should.

I have a lot of problems with this definition, but mostly it’s just that this is the absolute lowest possible bar for judging code. We can do better, can’t we? Also, how code is supposed to work is often a matter of opinion and not well defined in some requirement document.

Quality code is readable and understandable.

This used to be my definition of quality code. I was obsessed with formatting of code. It’s true that any given piece of code is more often read than written, however it’s also more often executed than read. Writing code to be read tends to push a code base towards longer chunks of procedural and imperative statements. These aren’t the best choice for every problem and can lead to code duplication and dependencies in the case of large and complex applications.

Quality code is commented.

Oh yeah, I used to love comments too. Comments often lie though. Comments may mislead and are out of date. You can’t ever really trust comments.

It’s far better to write readable code than to comment it. Give a bit of code a name by encapsulating it in a method (method names can lie too, that’s called a side-effect, but it’s much less likely).

Quality code is protected with automated tests.

This is the working definition that Robert Martin uses in his influential book “Clean Code”. I highly recommend it, however this definition didn’t sit well with me then and it doesn’t now. His argument is that without tests, quality code will decay over time. Tests protect it, document it, and allow safe and confident improvement of the code. Tests are important, but they don’t magically improve the quality of code by themselves. At their worst tests can have all the negative effects of comments.

Still, read the book. There are a ton of great insights into how to achieve clean code.

After years of thought, I’ve arrived at my own definition. It’s rather broad and says nothing at all about what quality code looks like or how it’s achieved. This is a benefit because it allows us to evaluate many styles and techniques for improving code and not be bound rigidly as the industry evolves.

Quality code is code that can be changed, as needed.

First, recognize that all code must change. The needs of stakeholders and users change; the application must change to meet those needs.

As an illustration, imagine a deal with the devil; The devil offers an application that perfectly meets all of your needs. In the fine print, however, is a clause that stipulates that the application may never be changed to do anything other than what it does right now. I suspect there are many who would take that deal, and none that wouldn’t live to regret it.

Secondly, the code must be able to be changed “as needed”. Code that cannot be changed when it needs to be changed is not quality code. Business is competitive. Windows of opportunity are a thing. If your code isn’t flexible enough to change in time to take advantage of your opportunity, it isn’t good enough.

Code that cannot be changed to do what is needed is not quality code. If the stakeholders have to compromise what they want because of the difficulty of changing the code, then that code isn’t good enough.

Jonathan Strange and Mr. Norell: Magic and Programming

I just finished reading “Jonathan Strange and Mr. Norrell” (for the second time). It’s a really great book and it’s often described as Jane Austen meet’s Tolkien. If you like just one side of that equation you should still give it a chance as I found that it’s a strong enough book to overcome any distaste you have for fantasy or Victorian drama, so long as you like the other.

There are countless (better) reviews than I could give though, rather I wanted to write about one particular aspect of the book that was very interesting to me personally. I was struck with the similarities between the way that spell casting is described in the book and certain aspects of programming. I’ll do my best to avoid spoilers.

Particularly difficult or complicated spells are sometimes scripted, which is to say that they are literally written down on scraps of paper before being used. There are several scripting languages in popular use today. The most widespread and familiar to the reader probably being Javascript which is primarily used by web-browsers to enact all sorts of dynamic behavior on a web page.

Sometimes they are read from a book in the library of one of the magicians. In programming we often use code from libraries for the exact same reason as magicians in the book. Chiefly, we don’t need to take the time and to discover how to do something and secondly, we can avoid making mistakes by using code that has already proven to work.

When spells are not scripted beforehand it’s usually appears to be because the magic itself is either very simple or else there is simply no time to script a spell. This sort of seems like entering commands directly into a console. Maybe I’m stretching a bit on this analogy, but I didn’t want to leave you with the impression that all spells are scripted.

Spells have variables, which is another way of saying that spells are reusable, not single use. They don’t seem to accept arguments in the way that functions do. Rather I think they act more like closures (again commonly found in javascript) where the function is declared with a certain set of variables which it holds onto and use when it’s executed. Additionally spells, may also be embedded within other spells.

Spells can also be used as more than a simple script that is executed immediately and completed and then ends. Sometimes a spell brings into being a magical state in an object that can be interacted with. The best example of this is a spell that occurs multiple times in the book for finding a person. A silver bowl is filled with water and the magician utters a spell and then draws four lines on the surface of the water, dividing it into quadrants. He names each quadrant an area of the world to search in for the person. For example, England, Scotland, Wales, and Other. A blue dot appears in whatever named quadrant where the person is to be found. The magician then taps that quadrant which then zooms to fill the entire surface area and begins again to divide and name regions within the surface of the bowl. The magician does not need to restate the spell each time, rather he’s interacting in an iterative way with an object that has a magical state. It remembers the name of the person he’s searching for. I suppose there are a number of ways this could be implemented by a programmer, but I thought immediately of objects.

Lastly, spells have bugs and unintended consequences. Sometimes they last longer than they should, sometimes the effect of the spell effects unintended people or areas. Sometimes it doesn’t work at all and the magician doesn’t know why.

I’m sure there are more similarities, but these are the most obvious ones to me. I highly recommend the book for programmers (who tend to like fantasy and magic). Until it wears off my job will feel a bit more magical.