The Code Dump

A place a coder rants at...

Your First WatchKit Glance

| Comments

WatchKit is finally out, and of course I started playing with it right away.

I find it a bit awkward to get my first glance running, since I had to create a custom scheme, understand the watch is an “external display” and restart the app a couple of times. I whipped up a short (and crude) 2.5 minutes video showing just that, in case you wanna get started on the hacking as well!

Happy (WatchKit) coding!

AngularJS 1.3 Taste: Async Validators

| Comments

AngularJS 1.3 is finally released and brought a lot of very cool features. I decided to focus on one that, when you need it, will save you lots of time and hassle.

Prior to 1.3 custom validators were half-baked in Angular. There was no real concept of adding a validator to a field even though forms did have validity states etc. Add to that the case of having validators that take a while to run and you’re in a real jam.

Let’s look at an example. Every decent website sign up form that has a username field also has a validator that checks whether that username is available even before you try to submit the form. Here’s how awesome it would be to do that with the new 1.3 API:

1
2
3
4
5
6
7
8
9
10
11
12
13
<form name="myForm" ng-submit="submit()">
    <label>
        Username:
        <input type="text" ng-model="signup.username" required username-validator>
    </label>

    <label>
        Password:
        <input type="password" ng-model="signup.password" required>
    </label>

    <button type="submit" ng-disabled="myForm.$invalid">Sign Up</button>
</form>

You’ll notice that I added the username-validator directive to the username field. Now let’s see how that’s implemented:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
angular.module('myModule').directive('usernameValidator', function($http, $q) {
    return {
        require: 'ngModel',
        link: function(scope, element, attrs, ngModel) {
            ngModel.$asyncValidators.username = function(modelValue, viewValue) {
                return $http.post('/username-check', {username: viewValue}).then(
                    function(response) {
                        if (!response.data.validUsername) {
                            return $q.reject(response.data.errorMessage);
                        }
                        return true;
                    }
                );
            };
        }
    };
});

Basically it’s just a matter of adding an asynchronous validator on that field. That validator simply performs an HTTP request and according to the response sets the field as valid or not. The mechanism that enables this is plain promises: our validator returns a promise and the field’s validity will remain in “pending” state until the promise is resolved. If it resolves with an error, the field will be marked invalid, otherwise Angular assumes all is well.

But, a caveat we have left in the example above is that it let’s the user attempt to submit the form while we are still waiting for some pending validations to return. That’s because the submit button is only disabled while the form is invalid (myForm.$invalid). While there are pending validations and no invalid fields the form isn’t invalid (yet) and so the button isn’t disabled. The solution is to disable the button also while the form is pending:

1
<button type="submit" ng-disabled="myForm.$invalid || myForm.$pending">Sign Up</button>

And that’s all there’s to it. You can see a live example (with $timeout in order to fake the async operation) on this example here (I actually added in there an example fo rusing the new ngMessages directive).

Happy coding!

Don’t Use Yeoman’s Default Angular File Structure

| Comments

Yeoman is a very handy tool, and I’ve used its angular-generator to generate a basic structure for several new projects before. You should use it if you’d like to have it worry about all of your project’s build process (minification, uglifying, compiling SASS, etc.).

But, in my opinion the default file structure is almost negligent. If you go along with it to create your different controllers and directive you end up with something that looks like this:

app/
    scripts/
        controllers/
            main.js
            foo.js
            bar.js
        directives/
            baz.js
            lolz.js
        services/
            haha.js

Can you say “big ball of mud”?

This is bad, since when creating new entities in your project and arranging them, you shouldn’t put them together based on what Angular component they happen to be implemented with. No, we know this already. File structures should be a tool for grouping components logically. After all, when you need to make a change in the login module, do you want to go hunting for the right files under each directory, or open the “login” directory?

I believe you should strive to a structure that looks more like this:

app/
    scripts/
        login/
            login-page.js
            password-validator.js
        dashboard/
            cool-charts.js
            timeline.js

Do I have to stop using the generators for controllers, directives, etc.?

Yes.

I know, it’s not fun. But as far as I can tell, the generators (e.g. yo angular:controller login) don’t support a different file structure at the moment. It it something that’s planned according to the project’s site.

But it just boils down to a relatively simple template (in case you don’t want to type the boilerplate yourself when creating a new file) and adding a line to index.html, really not that big of a deal if it means I get proper file structure.

Happy coding!

It Depends

| Comments

“Should we use AngularJS, Ember or Backbone?”
“Should we go with Rails, Node or Java for out backend?”
“What is the right programming language to start with?”
“Do we need a mobile app?”
“Should we have Facebook login?”

You probably get these questions and their like all the time. The only right (first) answer to these questions is: It Depends.

I know, it feels like you’re saying you don’t really know, and sometimes people treat it as if you’re trying to be a smart-ass. But, really, it does depend, and giving an answer without considering the specific case is bordering negligence.

The reason we get paid The Big Bucks™ is because we know when a question deserves deeper thought and which considerations should come into play.
That’s the knowledge your clients, boss or colleagues might lack and is what your expertise should be.

Yeah, choosing Java for your server side is rare these days but what if the company is based in an area with lots of Java experts?

Yeah, Facebook login saves a lot of work sometimes, but sometimes having it would just make things really confusing, or even cause your customers to not want to use your product.

So, be proud in knowing when it’s the right call to say “it depends” and not just shoot an off-the-cuff answer. The people you work with will value you much more for knowing that everything has context.

CSS Tip: Elements with Height 100% - Fixed Amount

| Comments

A quick tip that I just find myself smiling whenever I use it successfully and feel dumb for not using it earlier:

Nowadays, it is very often that we want to layout an element to fill all of its parent’s height (or width) except for a fixed amount. For example, a view with a top header and body that should fill the rest.

Up until recently I used to solve this by using flexbox, where browser support allowed me.

But a few weeks ago a friend showed me this really really really really neat trick. I’ve known about CSS’s calc() for a while, but I didn’t know it could be used for this, and didn’t know it had such a wide support base:

1
2
3
4
5
<div class="container">
    <header>My awesome header</header>

    <article>My even more awesome content</article>
</div>
1
2
3
4
5
6
7
8
9
10
11
.container {
    height: 100vh;
}

.container header {
    height: 50px;
}

.container article {
    height: calc(100% - 50px);
}

You can see a simple example here.

Yup. That’s it! Calc away!

Prefer Code that Runs Once

| Comments

While working with clients I’ve noticed that a lot of startups that are in the “move fast” mentality seem to abuse the great tools we now have. In a world where you can have all your stack be in dynamic languages, and your storage totally schema-less (e.g. MongoDB) you may be tempted to postpone committing to changes in the data model for too long. Effectively, many companies don’t really have a data model. They have this blob of data.

A lot of us might feel the client side is more flexible and safer for making quick changes than the server or database are. For example, you may decide a certain field in your model that is currently just a string should instead be an object. Yet you’d rather do the quick win and not migrate all of your data. Instead you simply have your client run a transformation on the data it receives if it notices that it is using the old format.

Seems like an easy win, right? It means you only make changes in the client code, you don’t need to think too hard about running a migration on your backend, etc. And that’s actually what I might do first, when just trying to choose the right change to make.

But let’s take this a couple of months forward. You’re a tiny startup, with barely any real amount of data and still lots of changes to be made. Yet your code is starting to get bloated with conversions and hacks. Half of the data is getting transformed in the client to provide it with a consistent data model (or, worse, the different ifs etc. are scattered all over your code). Making changes means you have to understand this whole map of conversions and you have to maintain all this boilerplate code. And of course, if you ever decide to add, say, a native mobile app it can’t rely on your API and has to do all those transformations again. Fun, right?

Instead, you could go with writing code that runs just once. Don’t have transformations that happen whenever someone refreshes your site. Write your transformation (or… can I use the word “migrations” without scaring too many people nowadays?) and have them… you know… transform the data. Right there and then. That’s it. You just run it and then you can forget about that code. You don’t need to maintain it. You don’t need to debug it. It won’t slow up your UI’s startup time. There’s significantly less code to futz around with.

And the best part is that you get everything to be synced. All your clients, be they native apps, JavaScript rich apps, etc. use the same data model. That’s the same data your server has. It might even be the same data that you can then query on your database! No need to transform in your head what you see in the database and how that probably looks to your client after it did its business.

Code that runs once is easier to write and verify, can be effectively forgotten later, and gives use familiarity. Because our jobs are hard enough and we need all the time we have to try to solve real problems. You want to be able to move on from your previous schema mistakes, not to have to drag it around with you forever.

Can you find a chunk of code that can run one last time, today? Do it, make the world a better place.

Lessons from Building a Rocket Alarm App

3 weeks ago Hamas started firing more than a hundred rockets a day at Israel. After almost sleeping through the sirens one time, I decided that enough is enough and went looking for a way to write an app for it. The iPhone had a single app that would constantly alert with a delay (of usually several minutes) – we couldn’t fly with that.

Air raid sirens 101

If you’ve never had to live in rocket range and duck for shelter (like most of the western world) here’s how it basically works: all of a sudden you hear this lovely sound booming across the city and now you have to run for shelter within 15-90 seconds (depending on your distance from Gaza strip).

A lot of apartments in Israel have a safe room that you can run to, but older buildings don’t which means you usually go to the stairs, since they are considered safer than the rest of the building. You then spend 10 minutes with your neighbors (or strangers that ran inside from the street), waiting for the rockets to fall or be intercepted by the Iron Dome.

Problem is that these sirens are easy to miss if you’re taking a shower, a deep sleeper, in a place where there’s some noise or happen to be in a place where the sirens don’t reach that well.

With the help of a few talented friends, we had a working iPhone app in about 20ish work hours over the weekend. Since then the app has topped the Israeli App Store’s free chart and delivered tens of millions of notifications. Here’s a random collection of things I’ve learned along the way:

  • Not that hard to top the Israeli store: On its first day, the app had about ~4k installs (mostly in the Israeli store) and those were enough to get it to #10 on the free chart. 2.5 days later it had ~24k installs and ~100 5 star reviews, which brought it to be #1 on the Israeli store.

  • Going viral in bomb shelters: This is a bit stupid but I was utterly surprised to see the amount of installs keep going up. I posted once on Facebook. It seems like from there the app was shared across the Israeli tech people which got a nice amount of first installs. But the real masses of installs happened after every barrage on big cities. I’ve seen this and heard from other people: as we stand in the bomb shelters for minutes, usually with neighbors and total strangers, people see you get alerts on time and lament the crappy app they’ve been using.

  • Testing is weird: We had scenarios of “well, I’ll just wait for Hamas to bomb us again to make sure it works.” That’s kind of a weird scenario to be in. But hey, you could always count on Hamas to deliver, even during ceasefires!

  • An accessible mail form will be triggered a lot: The app has a “contact us” button that just opens up the native iOS mail compose view with my email address. The amount of empty emails I’ve received (due to people just pressing “send”, without writing anything, instead of “cancel”) is nearing a 1000 (and we currently have about 70k installs). Be prepared.

  • People mostly want to stay updated: In times like this it seems Israelis really want to stay updated about rocket launches. It’s a small country and you know someone at every city – you want to know when your friends are attacked. Even though you can point the app to only alert for your own city, over half of the users have set the app to alert them for “every alarm” (over a hundred a day). That also means that the app was not just used for “I have to run for cover” but also as a news source, which is why I got hundreds of emails asking to add other notification sounds, “less alarming alarms” if you will.

  • People actually read the P.S. of emails: I’ve handled hundreds of support emails and in most added something like this: “P.S. If you’re satisfied with the app it would really make us happy if you click here and rate us well”. A lot of people replied with “already did” or “of course, you deserve it” and we actually have about 0.5% of installs that rate us (with a 5 star rating). I don’t know what’s the average here, but it seems to me the P.S. works.

  • Push permission is a bit of a pain: A lot of people did not allow push notifications when the app prompted them and then complained about not getting alerts. It was very hard to instruct them via email how to get to the appropriate settings screen and what to set in it. There should be an easy way to prompt the user again even if it hasn’t been that long since the last time he said no. Also, do yourselves a favor and put in your email form a user identifier that’ll help you see if the user has allowed push and other things. It’s otherwise almost impossible to identify a single user out of tens of thousands.

  • Parse is pretty awesome: We’re sending out millions of push notifications a day for free and the integration was a breeze. We once noticed a delay in delivering notifications and the Parse team were quick to reply and sort out the problem. Really amazed me!

Here’s to hoping the app goes idle soon!

Generic HTTP Error Handling in AngularJS

| Comments

Lately during development at one of our clients, Ravello Systems, we decided we wanted better HTTP error handling.

Basically, our perfect solution would have generic handlers for errors, and most calls in the code will not have to do any special work for handling errors. This means that things like authentication problems, server unavailability issues, etc. will be handled in one place — like adding a generic “something went wrong” modal.

But, we also wanted to be able to easily override these default handlers so that specific places can do things like silently ignore errors of unimportant calls (e.g. background requests that aren’t user-facing), or display a special “try again later” context—aware message.

This is a case study of how we currently implemented this. I’m sharing this for others that might need it and in hopes to hear of alternative ways to accomplish it.

Our requirements

  • The generic error handling should happen automatically, and can’t be something a developer can forget to enable. That means things like adding a ‘.catch(genericHandler)’ to every call is out of the question.
  • When the less common case happens, meaning someone isn’t using the generic handler, it should be explicit.
  • It should work seamlessly with angular’s $http service so that no matter if we aren’t the ones making the calls ourselves, everything should still be handled.
  • It should allow us to easily handle grouped requests (i.e. requests that are handled by the caller in a single $q.all() call).

How the end result looks

If you’re making a call that just wants to use the generic handling code, it looks like this:

1
2
3
4
5
$http.get('some/url').then(
    function(response) {
        // Stuff here
    }
);

Seems familiar? That’s right, in most cases you don’t need to change your code at all.

And in cases you do want to handle errors yourself:

1
2
3
4
5
6
7
8
RequestsErrorHandler.specificallyHandled(
    function() {
        $q.all({foo: FooService.fetch(), bar: BarService.fetch()}).then(
            function() { /* Handle success */ },
            function() { /* Handle specific errors */ }
        );
    }
);

As you can see, it’s pretty straightforward. And the use of a function (which we would essentially consider a block in languages like Ruby) allows us to group multiple requests in the same error handler.

The implementation

Basically we tag every request that needs to be generically handled by adding a HTTP header to it. Then when requests fail due to errors an interceptor handles those that are tagged.

There are 3 parts:

A decorator for $http – This is the only way we came up with to tag requests inside our specificallyHandled function. Interceptors are run asynchronously and so can’t tell whether the request was made inside our specificallyHandled block or not. This decorator simply wraps all the $http functions to add a specific header in cases they should be generically handled.

Response interceptor – This intercepts all the failed responses and handles them in a generic way – but only if they have the magical HTTP header we add in the $http decorator.

RequestsErrorHandler – A service that turns on or off the generic handling according to when it is called.

The Code

Also available here.

Angular Performance 101: The Slides

| Comments

I gave a talk today at JS-IL called “Angular Performance 101”. Below are the slides. Unfortunately they are a bit hard to follow if you haven’t been to the talk. I hope to upload a version with audio if people will be interested.

Cheers!

AngularJS: Decisions, Decisions & My Preferred Choices

| Comments

Angular is the land of too much free choice. You are faced with decision after decision, over and over again. Choice is good, but sometimes too much choice can cause paralysis. Let’s take a look at some of these choice and what I usually go with:

Factory vs. Service

Chances are you saw these two common ways of creating injectable objects, factory and service, and couldn’t help but wonder “what the f@#$@ is the difference?”

Essentially, factory takes a function whose return value is the thing that would be injected. So if we have this:

1
2
3
angular.module('app').factory('MyThing', function() {
    return {id: 1, thing: 'stuff'};
});

And you inject it, you will be injected with the object {id: 1, thing: 'stuff'}.

service is almost identical, except that it expects you to provide it with a constructor function. It instantiates a new object using that function and that is what is injected:

1
2
3
4
5
6
7
8
angular.module('app').service('MyThing', function() {
    this.id = 1;
    this.thing = 'stuff';
});

angular.module('app').controller('MyCtrl', function(MyThing) {
    // Here MyThing is {id: 1, thing: 'stuff'}
});

Note: Every place that MyThing would be injected it would be same instance. In other words Angular will instantiate a single instance and reuse it across your app.

Which should you pick? In general, since the two are almost equivalent I like sticking to just one of these in a project, usually factory. It can do anything you can do with service and I personally don’t see a need to go through creating a constructor that’s just called once. I just return that instance and that’s it.

Value vs. Constant

Angular lets us quite easily add simple injections of plain values. For example, say you want to declare a constant like your REST URLs base path. You can do it with either module.value('restBase', '/api/v2') or module.constant('restBase', '/api/v2'). Really?

The difference is that while constants can be injected to module configuration functions (i.e. module.config()) values cannot. Also, you can intercept values with $provide and decorate them. These are two usages are pretty uncommon and are for more advanced cases, so don’t worry right now if you don’t know them.

Since they’re so similar I’d just stick with constants unless your are using it to store something that is not actually constant (i.e. an object that you change later on). But that’s basically a global variable, so you probably should never do that. So constants it is!

Directive vs. Nested Controllers

For some uses, directives and controllers can be used interchangeably. We all know that directives should be used for DOM access and controllers are usually used for top-level elements like pages and routing targets. What about all the rest?

I’ll just cut to the chase: Almost always the right choice, in my opinion, is to use a directive. Directives allow you to write code that is more decoupled and self-contained. Directives let you to explicitly state what they depend on, opposed to controllers that just inherit their parents’ scopes as-is. More on this next.

Same scope, new scope, isolated scope

Now that you’ve realized that you should almost always use directives comes the decision of scope. Should you just use the parent scope? Inherit it? Isolate completely?

Well, my heuristic is: Will creating an isolated scope mess things up? For example, if your directive might be used along other directives/controllers that would not expect the scope to be swapped. If so: prefer to inherit the scope if possible, use the parent scope only if you must.

In pretty much any other case I just use an isolated scope. They are the best thing since sliced bread. Isolated scopes are explicit (it is easy to see what they depend on), durable (they are less likely to break because of code changes somewhere else) and plainly the way to go. I’ve described their advantages in “Writing More Maintainable Directives”.