Get Started with Profiling Ember.js – Ember.js SF Meetup

I recently was up in SF giving a talk related to performance for the ember developer.

Some things I should cover in a following talk:
– Deep Dive on Ember perf for internals
– Strategies for deferring rendering
– Handling Glimmer updates efficiently
– How to paint less
– how to composite less
– how not to block your UI

12 Years Later – What I’ve learned so far about software development

Somewhere within 20 feet, It’s a safe bet to assume there’s a cell phone nearby. That device, with all of its memory, CPU registers, and pixels, is roughly 100 times as powerful as what men and women used to send humanity to rocketing toward a small rock a hundred thousand miles in the upward direction.

I look back on NASA’s accomplishments, and what comes to mind are the milestones that made that final step for mankind possible. The Gemini, Mercury, and Apollo missions that came before them each solved a major problem through experimentation that space flight was possible.

It’s hard to imagine now that people had no idea what would happen when you put a human being in space. Would their head simply explode, and if so, what kind of momentum would an eyeball have at absolute zero? This was a question that was no doubt asked by a bunch of incredibly smart people trying to plan out how we’d be able to safely send someone into a miniscule window between being flung back to earth in a ball of fire or into an infinite abyss. Could you imagine an off-by-one error in the math, or an unhandled exception? When was the last time your programs had those problems?

If you’re a modern day software developer, you’re either reading this between fixing those kinds of issues, or writing tests so those errors stay fixed. For now.

The terrible truth is no matter who you are or what sort of systems you engineer, be they web pages or embedded software, you often tread the water between catastrophic failure or lucky circumstance.

If you’ve worked on any software project with more than 10 individual developers, I’m almost certain that there have been moments where you’ve contemplated just throwing it all out and starting over again.

Why is this so common, I wonder? It’s not like the individuals are bad programmers. In the past 12 years I’ve met some incredible programmers who’ve been able to teach me things that I’d never have thought of. They’ve expanded my view on systems design and how they are approached and constructed in both paper and personal contexts. I respect them greatly. The fact remains, though, that more often than not a system tends toward a giant ball of mud given enough time.

Brian Foote and Joseph Yoder, in the paper “Big Ball of Mud” assert that it’s when a combination of pressure, risk aversion, inexperience, complexity, rate of change, and scale of a project all increase, so too does the big ball of mud.

The evidence for this — to me anyway — is that there are a lot of inexperienced developers out there in very senior positions in our trade.

Some of that is no doubt due to the culture of the web and its construction crew being such a new industry. Unfortunately, I don’t know how well it’s maturing. It can feel like it’s people in suspenders and thick rimmed glasses banging unmentionable things into terminals and posting on usenet. We’ve just traded out the terminal for a MacBook and usenet for Twitter and Facebook.

I don’t have all the answers. I’m not the worlds best programmer and frankly, there’s an infinity of things I could be more knowledgable of. I am average in a galaxy of incalculable talent.

I want to make things better, though, and I think it starts by emulating the behavior of an organization that I admire.

1-p8SbiwIhY84xEU97YaGxyAThis image brought to you by preventable catastrophe, budget overruns, political wrangling, infighting, incalculable complexity, and against its best effort, humanity.

Billions of dollars, decades of planning, inventive engineering, and prototyping. Detailed, painstaking micrometer measurements and manufacturing precision, and at the end of it all the Hubble team shipped a broken system.

When the Hubble first turned on, one of the solar arrays that provided half the power for the array didn’t unroll. This forced the majority of the system completely inoperable. Something around the size of a city bus would be junk, and its in space.

The astronauts on the shuttle who launched Hubble ended up preparing for an EVA — a spacewalk — to manually unroll the solar array. After afew harrowing minutes, brushing with complete system failure in production, they found a way to patch the mechanism governing the solar array and forced it to unroll properly.

I’ve never read an exact accounting of the error that caused this, but from what I’ve watched and read, it seemed like a bunch of programmers huddled in a conference room mapped out the system looking for commands that they could use to ‘override’ the original method. Sound familiar?

This was mostly a warm-up act for what came when they started getting the first images back from Hubble. Nothing was in focus. Every picture they saw had a corona effect on any light source, which for a telescope, is crippling.

The difference that 0.000001th of an inch makes.

The underlying defect was a problem in the main optic of the telescope, the giant mirror that gathered light. It contained a defect of effectively point zero zero zero zero zero one inches. that’s 0.000001. The fate of a system that cost taxpayers billions of dollars rested on a number that seems almost imaginary.

So why did this happen? Was this just bad luck, or a combination of factors with an organization bereft of standards and rigor? Were contractors involved?

The Hubble Telescope — Optical Systems Failure Report goes into detail, below:

The primary mirror is a disc of glass 2.4 m in diameter, whose polished front surface is coated with a very thin layer of aluminum. When glass is polished, small amounts of material are worn away, so by selectively polishing different parts of a mirror, the shape is altered. During the manufacture of all telescope mirrors there are many repetitive cycles in which the surface is tested by reflecting light from it; the surface is then selectively polished to correct any errors in its shape. The error in the HST’s mirror occurred because the optical test used in this process was not set up correctly; thus the surface was polished into the wrong shape

The design of the telescope and the measuring instruments was performed well by skilled optical scientists. However, the fabrication was the responsibility of the Optical Operations Division at the Perkin-Elmer Corporation (P-E), which was insulated from review or technical supervision. The P-E design scientists, management, and Technical Advisory Group, as well as NASA management and 1 NASA review activities, all failed to follow the fabrication process with reasonable diligence and, according to testimony, were unaware that discrepant data existed, although the data were of concern to some members of P-E’s Optical Operations Division. Reliance on a single test method was a process which was clearly vulnerable to simple error. Such errors had been seen in other telescope programs, yet no independent tests were planned, although some simple tests to protect against major error were considered and rejected. During the critical time period, there was great concern about cost and schedule, which further inhibited consideration of independent tests.

The final report slammed both NASA and the optics contractor, Perkin-Elmer. They found that while manufacturing, quality control issues misaligned the instrumentation that measured the mirrors for correctness and nobody else assumed there could be an issue. So off they went to space. NASA had a heated relationship with Perkin-Elmer, so much so that the report called out the contractor for regular schedule slippage, cost overruns, and quality control problems.

I just call it by what it was: A big ball of mud.

I have no doubt that you could imagine a similar situation. You don’t have wrinkles on your forehead and gray freckling your hair until you’ve witnessed a software project melt down at the precise time it shouldn’t.

It’s not so much of if it’ll happen, it’s more of a when.

Software running on the internet, especially in the consumer application and user interface world tend to follow a similar pattern. One level down, and you start to question how this has worked so well for so long. Is it me? Do I lack the essential programmer-stuff that lets me see the vision in how this all orchestrates into the output of a true free electron’s thought patterns that never grew out of the prototype phases?

I’d love to be surprised. But in the real world, I’ll sulk into my chair and mumble under my breath about not having enough time or energy to pour into fixing the problem. I have kids to provide for. I have some semblance of a life that I want to live outside of the boundaries of my office.

The other truth that nobody tells you is that if you want to really be the best at what you do, in your profession, it takes endless patience and consensus building to guide your peers into doing it the Right Way. No single person can be the bedrock of a sufficiently complex system. It just isn’t realistic to expect a few people to steward a project into something that I’d want to strap into and let it carefully explode so that I could travel hundreds of thousands of miles to walk around a desolate wasteland that could kill me at any second.

In the software world, perfection is simply being correct. There’s no shades of gray about being correct or incorrect. The computer doesn’t care much for nuance. You are either correct or you aren’t.

Real and extensive mental exhaustion comes from working out every possible input and output to a given activity, and then translating that into a precise instruction set for an entity that has the intelligence of a wet blanket. Unless you are perfect, things end up going from usable to a nightmare. Insidiously, this often happens in subtle ways that are easy to miss.

The overwhelming emotional response to this metamorphosis of bullshit is where I find a lot of programmers at, day to day. “What idiot would do such a thing?” is a common complaint.

They’ll blame the APIs, they’ll blame obtuse or brittle interfaces. They’ll blame absolutely everybody — including the testers— for having work in an environment so vast, broken, and functionally idiotic that they just can’t write Good Code.

Frothing spittle and twitching at the eyeballs, they’ll be lurched over their keyboards, four in the morning, looking through the same file over and over again, manically searching for any potential problems before giving up moving on to another and repeating the whole vicious cycle.

This is insanity. The way we build software right now is completely fucked.

I’ve been giving this a lot of thought, and I’ve been doing scores of reading. I don’t have an answer, but I think there’s a sort of system that I tend to follow, and when I see somebody deliberately break out of that system, It drives me up the wall. I want to stop them and ask them why they’re doing things so badly. Does this make me a dick? Shouldn’t we stop when we see our peers doing something ridiculous or dangerous or just flat out incorrect and guide them toward the Right Way?

I’ve seen people breaking out of this system, including myself. Sometimes it’s out of expediency, sometimes it’s because this is just a prototype, and that’s okay. Prototyping is what Good Coders do, right?

More than I’d like to admit, its been nothing more than simple procrastination.

Procrastination is a symptom that all software developers have. It’s acquired over each and every accomplishment they’ve had along the way to this point in time. Every time they’ve shipped some Good Code, there is a drip of hubris into the bucket of egoism that they’ve just become this walking behemoth, capable of moving mountains.

We just can’t help it. It’s the Makers High. We wouldn’t put up with countless endless nights, souped up on lethal levels of caffeination and sugar, working to the sounds of completely ridiculous music that we believe get us into flow and make us the most productive.

Really though, all this ends up doing is detracting from what we’re good at.

Developers, Engineers, Coders, Hackers, whatever you want to call them — They’re all the same — they’re all analytical and egotistical. The systems we forge are born out of a thought exercise and grow organically out of the requirements as we know them to be — in the moment — and as a group, we don’t tend to backtrack unless it means coming to terms with the fact that we were wrong.

It’s not like we just forgot to get the milk from the supermarket or left our wallet at home every once and a while. It’s like creating Frankenstein and then, after you’ve hit it with lightning and given it life, while attempting to walk, you realize that you didn’t bolt the legs on.

That’s one reason engineers can be finicky, difficult people. We’re shoved bug reports and defects in our faces like they’re just some paperwork we have to do. There’s significant psychological subtlety in place that most program managers don’t really understand, since most haven’t had that feeling of building the thing and forgetting the detail that breaks the thing.

Unless you’ve written a buggy program, you don’t realize that you’re addressing our intellect. This is why I think that every engineer on the planet looks at a bug report and feels a twinge of pain as they read whatever detail that was left to serve as a figurative shame sticker on the report card of their creation. It really sucks when you’re just flat out wrong.

Being wrong — rather, being incorrect — is a humbling experience. The catastrophically incorrect, which is when software crashes, money is lost, or the absolute worst, data is stolen, is the kind of thing that makes you question your career choice. It makes you want to curl up into a ball and weep at how stupid you were when you find the problem.

But what you should have had was a swift kick in the ass and a system that prevents you from being the egotistic procrastinator you are.

What follows is my philosphy for writing programs. I try to follow this as best as I can, and use it as a means for checking my ego at my editor.

There is no silver bullet, so before you disagree with anything here, take a moment to ask yourself if you’re technically correct, or just trying to sound smarter than I am.

Code doesn’t change. It mutates.

A healthy codebase is one that is thriving with life and activity. Much like the genetics of any living thing, it requires constant mutation to evolve and harness new capabilities. The cost of all of this mutation can be messy, and if not carefully checked, inaction can lead to death.

Dead code — unused, old, brittle, or broken — must be expunged early and often for the continued health of a system. Commenting out and committing doesn’t count. Refactoring and not updating documentation or tests is a cardinal sin.

If you’ve ever played with a big box of lego bricks, you’d probably find that unless you were following specific directions, there’s a decent chance that your awesome spaceship ended up with a few weird appendages or blocks that were out of alignment. Over time, unless corrected, those blocks end up as a permanent blemish on the overall structure.

Our codebases are no different. Perfection isn’t the goal, it’s the baseline.

What defines perfect, though? Perfect is the enemy of good, isn’t it?

I think simplicity is perfect. Simple is elegant. Simple works.

Complex solutions to problems show defects in our comprehension of a feature, or of how that feature works within the larger system. When you feel like you have to retrace your steps when working with a file, that’s a sign that your code is getting too complex, and you should think about refactoring, time permitting.

The more complex your solution gets, the more mutations that it will have over time, and the more likely it’ll become the root cause of a problem rather than the fix to another.

Define a functional vocabulary.

You write software for two specific groups. The compiler, and the consumer. The consumer for what you write is other developers. Thus, agreeing to idioms in communication are key in order to participate in the discussion.

Don’t really worry about the compiler. It’s basically a blithering idiot. Assuming that a compiler were clever would remove the need for our job. Developers, though— that’s another story.

Imagine for a moment that you’re sitting in a meeting at work. People are talking about a new feature that needs to be implemented, and you are tapped to make the feature and push it live, all within a week.

People are throwing around acronyms and words that you don’t know. You’re handed a diagram of what you can only assume are a tube sock and a bottle of nail polish, and that’s it, you’ve got a week. Good luck.

So now you get to run head first into a project that you’ve never worked in before and figure out how to tell it what a tube sock is an how to make it this shade of nail polish in a week.

Senior programmers that I’ve worked with who were worthy of the title are able to find similarities into objects and move those from ‘gym sock’ into ‘tube sock’ and go from that point. Less senior developers tend to try to tell a dumb compiler exactly what a ‘tubè söck’ looks like. junior programmers attempt to find a tube sock online and copy and paste that into our project, only to spend the other 4.99 days figuring out why the tube sock looks more like a thimble and is blue.

People have argued with me at length that their code is readable, thus is discounted from having the same rules as all other code in a project. Readable code therefore is elegant enough for any common developer to read and understand how it is used, and in which context.

Reality is different. Your readable code is just hubris. You wrote a feature that may not be documented, and may not have gone through a refactoring phase and got cleaned up to standard because it’s ‘readable’.

So really, your readable code flies in the face of standards. All it does is throw the reality of the situation into the other programmers who have to maintain that feature in the future — perhaps when you’ve long since left — and they have to decode not only the instructions for the computer but the instructions for humans.

Be simple. Focus in the small. Ruthlessly analytize what you’re creating or modifying, and make a note of it in docstrings or full documentation blocks. Tell yourself what you’re going to do, and then implement that sentence. When you’re finished, take that sentence and write a test, then you can move on.

Review code as though you’ve never seen the system it exists in. Does it make sense? Overly esoteric classes only work for the extreme cases, and only with the proper ridiculous and long comment explaining the straying from the norm.

Assume that every developer who has to open this file has a picture of you and your family, your address, and a vendetta.

Documentation is the encyclopedia of your mutations.

I absolutely do not believe a single person who says that their code is self explanatory. I firmly believe and will happily defend this position. Anything less than function/method/class/module level comments and you’re just lazy.

I’m still shocked that this is considered a hyperbolic position to take. People give you money for your creative writing output, and yet, you refuse to do any of it outside of the absolute baseline. Basic. For the sake of those who are your brothers and sisters on the front lines, make their lives easier.

A few lines of comments describing the contents of a file are far more likely to impress anybody than any clever optimization you may attempt to do beyond them. How often have you looked at a library that was well commented and remarked, “Oh hey, this even has comments!”.

Documentation is critical to prevent the signs of mud growing on the walls of your project. The encyclopedia of mutation gives everyone access, and equality of knowledge on how to use and mutate it further. It’s the importance of sequencing the human genome. Why would you not want this?

Having a dictionary that’s well organized is as essential as the dictionary itself. What language do you write in? It doesn’t matter — it’s got an automatic tool that turns docstrings into a webpage.

Automation is essential.

Every single time you stop writing is time that you’ve wasted doing something that you shouldn’t have to do.

Make is one of the oldest programs on the planet, yet only recently in the UI world, we’ve begun to automate the most tedious of tasks.

Automation is how you can grade everyone’s knowledge of the vocabulary and the rules of the grammar of the system. Linters, tests, continuous integration and automatic documentation generation are things that take effectively fractional margins of time compared to the lifecycle of the project and give them back to you.

Why is it that automation isn’t something everyone would want? We’re lazy, as I mentioned earlier, and if we can avoid it, we shouldn’t need to do it.

Regardless of what you’re building, tools exist that can automate vast portions of overhead from your project. Spend the time to invest in the scaffolding of what you’re building, and you’ll be safer in the long run.

Prototyping! —I get it. Who wants to do anything automated as a prototype? Well- the best of the best tend to automate their automations. Boilerplates, empty repositories— Blanks — are everywhere, especially in the web. Artists would get nothing done if they had to hand stretch every canvas and make their own oil and acrylics every time they needed to paint, so why do we do this to ourselves as developers?

My basic rule is this: If something is performed more than three times in a 4 hour span, automate it. No exceptions. Assuming this task is 10 minutes of effort each hour, that’s an aggregate of 3 hours saved every week. 14 hours a month, and so forth.

Gravity is my secret weapon.

This is something that speaks to my lifetime battle with debt. Dave Ramsay, a guy who’s ideas (on personal finances) I enjoy, has a theory about paying off debt as fast as possible.

The theory is, paraphrased, that if you focus on the smallest debt with all of your energy first, and get it completely paid off as fast as you can, while paying the minimums on every other debt you have, you can focus all of the effort from that onto the next one.

As you continue up the chain to the largest debt, typically mortgages, cars, and so forth, you’ll be better able to make a dent in the principal of the debt with larger than expected payments.

For the astute reader that has ever dealt with crushing amounts of technical debt, this theory might give you pause for a moment.

A good credit rating for a US citizen means that they have more affordable means of borrowing, and they can get more out of their money than folks with a bad credit rating, if at all.

Why should your codebase be any different? If new features and refactoring effort were credit, you’d want to be able to maximize how much your effort will get you before having to pay off the debt.

This is the snowball effect. Use gravity to help your snowball grow from a few minor annoyances to shipping an entire new suite of functionality quickly and deliberately.

Your peers are your students. Your code is your syllabus.

Take every opportunity you can to educate your peers about what your code does. Are there certain ways to interact with your interface? Do I need to have an instance of this or is it new-able? is there a pattern to how this file is constructed? Is there a private or public interface?

Code reviews are such an excellent opportunity to flip the switch for your co-workers.

All too often, I’ve seen code reviews go from the ‘The English Patient’ to ‘The Spanish Inquisition’, and frankly the environment is one of the most important — if not dangerous — interactions you have with your team.

Critically, code reviews give you an opportunity to show competence to your peers. It’s a five minute show and tell about what you’ve been doing. It shows that you’ve been catching on to the language of the project and can be fluent in it. It helps you build trust and show off your understanding of the relationships of the vocabulary.

I know you have no time. There’s no budget, there’s no flexibility in the features for launch and you certainly wouldn’t want to spend a day sitting in a conference room when there’s code to be written.

Do it anyway. Do it with ferocity and attention. Make time. Be measured, back up your arguments with fact, and whatever you do, do not utter the words “Well, actually…”. If you do, you’re out of the meeting.

Egotism and Defects are interdependent.

My final rule is one burned into my mind from a path of scorched earth I’ve left behind me.

Experience is the tincture we apply to failure caused by egotism. The most incredible developers I have met in my career have been the some of the warmest, decent, humble, approachable individuals I’ve had the pleasure of working with, without exception.

You’ve probably met some of these people, or at least I’d hope you’d have the good sense to seek them out and emulate them in their behavior. These are the people who aren’t politically afraid to ask if you actually understand something, and then spend the afternoon over beers and wings explaining just how they interact with one another, and why the decisions were made to build them this way.

They are the absolute backbone of any engineering culture. They are the vault of institutional knowledge of any company. Befriend them. Learn everything you can from them.

Egotism is selfishness in the guise of cleverness. Brevity is the soul of wit, in english, perhaps, but in code it can be a dangerous cloak to complexity or a lack of comprehension. Brash, dismissive developers are almost to the person hiding a lack of self confidence or are so absorbed in Egotism that they simply cannot believe they are wrong. They are. Go look at their defect counts over the last year. Bring an umbrella when you open the door, it’ll be messy.

Try real hard not to be an asshole. Nobody wants to work with someone who thinks everything they’ve written has been brilliant. We’re generally a self deprecating people. When you tell us that your shit doesn’t stink, we automatically assume it does and will start smelling it by default.

Being humble doesn’t mean that you can’t revel in your successes. It just means that once it breaks — and it will — you just get right to work on what went wrong, chuckling at the defect title being an obtuse little sentence, and discuss lunch options.

That’s it.

Never assume your code is finished. Remember; code mutates. Mutation happens with or without direct influence. Document it, and make the mutations as simple as you can, but no simpler. Don’t be a dick. Try to teach others about your decisions for each mutation.

Your peers require your respect, your attention, and your effort. You are the best person to set the example.

Ember Components, Controllers, and the Interface Model

I write lots of ember components.  Most components have a certain amount of interop with the controller that is presenting it. How you manage that coupling makes all the difference, though.

There’s two schools of thought for components.  The idiomatic way, as presented in the ember guides, would be to have a single action for a component that is bound to an action or method on the presenting controller.  This style of design lets you work on having a component to one thing well, though it has a few limitations.  For starters, if you’re building a component because there’s (almost) no reason to use a view, a single action and some bound properties doesn’t make life easy for having a robust component.  Second, most UI widgets I end up building do quite a few things in the context of itself based upon the state of the controller.

The second way, and the way I’ve been working lately, is to pass the presenting context as a property called “ctx” to the component.  This allows me to use any method, property, or computed on the controller in my component without having to explicitly bind each value.  You could argue that you’re saving on setter/getter calls due to fetching directly from the controller.  You could also argue this is handy because it allows a controller to mixin support for a style of component.  Hey — that means we get interfaces! in javascript!

Lets say we have the following bits:

This looks wacky, but there’s a sort of mad scientist vibe happening here.  We’ve been able to define a discreet bit of functionality within a mixin that any controller can use to support a component.

To me, this looks like a better model than the one-action-multiple-bindings approach that the guides provide. You have the flexibility to provide action bubbling by invoking actions on a controller, which eliminates the need for a large implementation at the component level.

This all comes with one giant disclaimer — this approach works because it requires discipline.  If this looks like it’s a lot of extra work– that’s because it is. And that’s okay, because we’re doing something wacky with a pattern that doesn’t technically exist in the language we’re working in.  Most of the time, I’d recommend you build toward the best case – which is standalone, loosely coupled components that don’t work with the controller much at all.

But, for those moments where that’s not enough, and you’re about to build a view, this is the best alternative I’ve been able to find.

Twitter? Points!

Hey twitter. Just so you know before we get started, I think you’re cool. I enjoy the time we spend together, generally speaking. It’s just — Look.

I don’t really know why I check you so often. Most things that I happen to be following during the ‘boring’ parts of the year; You know the kind. No elections, no colossal world event has really hit maximum information saturation that I can count on you to provide when something qualifies. Snowden, I guess? That’s kind of why I have a bit of a beef, but not really because of the NSA security angle.

It’s news, certainly. But it’s not drama, and that’s what you push on your users more than anything else. Although I don’t think that’s really what you’re good at.

When the news broke that there was this guy named Edward Snowden and he did some Very Questionable Things regarding Our Nations Security (quite), baby – you were saturated.

Tweet after tweet of raucous fury and indignation, followed with the echos of the Entertaining Crazies that is inevitable about every big hashtaggable news story.

It’s really irritating you can’t italicize text, twitter. posting   and then ! immediately afterwards after a beat is really just not the same as it is in an IM conversation. If the real-time angle was really about making the platform more of an “instant communication tool”, you’ve left out some basics about writing.

I think, as a platform, that subconsciously, you care more about prose and sentence structure than you’re willing to admit.

You have to craft a really great tweet that contrasts the average mental puke of the common twitterer into something that can get hundreds of retweets.  Everything in comedy is timing and context, right? Twitter’s really the only large scale platform where I can use their message delivery contract as a way of defining the product better.

That’s cool — because the natural side effect is that you have a big differentiator than any other service that existed when twitter first did.

You posted stuff, but the web was more primitive then. You just refreshed to see new content. Maybe you had a app or client that gave you real time capability, but it was never really a concrete contract of the service.  What twitter did was literally opening up your feed and realizing that there was a few tenths of a second difference between you hitting ‘submit’ and it showing up on my screen and the screen of however many people are following you, if they happen to be looking at the time.

There’s really no upper limit on the creativity that twitter provides for the connoisseur. If you buy into the theory that writing within a structure forces you to work within the medium, 140 characters was the best arbitrary decision ever made. You force the really clever people to craft these gems of creative writing. You also let people work in stream of consciousness style writing and, for the first time on the web, it’s actually forced to be concise.  Vine followed it to it’s logical conclusion.

I’d like to think @nerdist and company thought like I just described when they were making @midnight.  It’s the most clever way of monitizing twitter I’ve seen yet.


edit; I just got “Well, Actually”‘d by @nerdist himself:


Ember.js Controllers for the Absolute Beginner


Mastering controllers in Ember has it’s perks. I’ve found that I tend to slowly reduce all of my views into components as time carries on. This has two interesting side effects.

First, you’ll depend less on events like ‘clicking’ or ‘touching’ and only use them to trigger actions on the controller via Ember.ViewTargetActionSupport. Second, and I think this is the cooler effect of the two, you’ll begin to see clear and descriptive action names rather than what usually gets described as a comment within a click handler of a view.

Controllers in Ember are vast. They contain endless functionality for you to utilize, and are really well documented.

The root Controller API docs are here:

Do’s and Do not’s

Smart use of get() and set() help ember do all of their clever observables and data binding. Using ‘raw accessors’ on properties can sometimes result in observables not firing. Always use get() and set() for single property operations, while using getProperties() and setProperties() for anything that sets many things.

Be smart about using things like incrementProperty() and decrementProperty(). Sometimes being more expressive is worth a trivial performance penalty.

I find it’s incredibly useful for keeping mentally organized is routinely prune your controller classes into logical groups. Think #REGION or something similar.

Actionable Stuff

Actions, as an abstraction of events, even if it’s just semantics, seems to help me add a nice layer between a direct view manipulation operation and business logic rules. This layer between the view logic of “Hey, the mouse moved!”, and the controller logic of “The user moved their mouse into this area that shows a contextual menu, I better update what I’m displaying so they see it” into easy to organize, declarative functions that describe exactly what my implementation needs to fulfill.

Think of the abstraction of an interface between these two things. According to SOLID, we should follow the Single Responsibility principle to split things between what the user is doing and what information it requires so that the user can do that thing. Tracking position data of the users mouse versus what regions are interesting for the mouse to be in require completely different schools of implementation details.

I realize this sounds a bit like rudimentary MVC – but that’s the point I’m making. Ember’s MVC model is effectively the french champaign to other javascript MVC’s Coors Light. You should think about how easy it is to work within your codebase as a way of increasing how much you can get done with it versus other options. It’s about luxury. The best part about luxury is that things are easier.

Think long and hard about what parts of what you’re doing are concrete enough to unit test versus an integration test.

This is my basic ‘theory’ of controller design: If they are more easily unit tested, you should put them in a view. If they’re easier to integration test, then put them in your controllers.

Okay. Right. Controllers.

There are three types of controllers you can define:

  • Ember.Controller: “I don’t have a direct model.”

I tend to use base controllers for things that I need to register and inject into other controllers or models. Also useful as an effective grouping of business logic that does not require to be instantiated multiple times. Controllers without a template are fine.

  • Ember.ObjectController: “I have one and only one Ember.Object as a model”

Object controllers tend to populate my root resources as collective state of the application within that resource tree. An example of this is defining something like this.resource(‘posts’) in my router. I have a posts.index route, a posts.list route, and a posts.single route. They do about what you expect. For reasons cooked up in the marketing department, we have to track how many links a user has clicked on that contain the class of “.track” because everyone in marketing has lost their minds. “Fine”, you say, and get to work on implementing this preposterous feature. You’ll probably need to choose the correct abstraction layer for the data we’ll be tracking. Where does that go?

I’ve found that these sorts of items work well as a single Model, which is basically a fancy way of saying “an Ember.Object”. Ember doesn’t define a “Model” class to subclass from. Just Objects. Go with that and pass it as the model (or a property on the Ember.Route sitting at the top of things) and assign it to the controller during Ember.Route.setupController()’s hook.

Define a few actions at the route level that manipulate that model definition, and now you can call the controller’s this.send(‘actionName’, params) to bubble up from your controller to the route actions, and now you can manage state across multiple child route changes from a resource object. Go make some coffee and curse your co-workers in marketing.

  • ArrayController: “Many Instances of like Objects”

The array controller expects that the root datatype returned from the model hook is an Array. There are some sugar bonuses through using this subclass, such as {{#each}} support in your templates.

Being efficient

Using cacheFor(‘prop’) is helpful when using computed properties. This will access the current computed state without recalculating it.

using has(‘prop’) will bubble. This means you can check for a particular state property or some similar case without having to worry about all of the wiring around needs: [] and references to other classes.

using needs: [‘foo’] within your controller will define a property called ‘controllers’ within the scope of your controller. You can use this system to access other controllers that may be available in the applications current state. usage is simple, just call this.get(‘’) to access the instance of a controller defined within needs.

ArrayControllers automatically add an arrayObserver to it’s content / model property. This means that you can define two optional hooks on the array controller through arrayWillChange() and arrayDidChange(), each of which will be passed the parameters (observedObj, first item, items removed, items added). You could easily implement a lot of simple housekeeping and mutation effects straight from that interface.

Enumerables are Incredibles
The API documentation for enumerables are here: Ember.Enumerable

Enumerables help abstract looking into and working with the contents of enumerables. Usually this just means that ember gives array controllers a big pile of functions that work quite a bit like how underscore.js does. Here’s a basic list of what you get, for free, just by using an ArrayController:

– addEnumerableObserver
– any
– compact
– contains
– enumerableContentDidChange
– enumerableContentWillChange
– every
– filter
– filterBy
– find
– findBy
– forEach
– getEach
– invoke
– isAny
– isEvery
– map
– mapBy
– nextObject
– reduce
– reject
– rejectBy
– removeEnumerableObserver
– setEach
– sortBy
– toArray
– uniq
– without

Controllers are the iron beams of your skyscraper

Take the time to go over the documentation related to controllers. Go look at discourse and their wealth of production level controllers that comprise their app.

I hope this post was helpful. Comments? Questions? Post below or ping me on twitter via @landongn


Things I wish someone had told me when I was learning Ember.js

This article is really old and shouldn’t be used anymore. Check out the ember guides instead.

  1. Learn the nuances between a route and a resource.  A resource is a definition of a thing. a route is something that thing can do. Nesting resources just means that you may have a dependency or parent / child relationship.
  2. If something doesn’t need to interact with any other controller, view, or component, it should be a component to maintain your sanity.
  3. Make a /packages/ directory, one for each namespace.  Grouping files by name helps enforce the naming conventions that are all over the place.  Do the same with your sources.  e.g; /packages/application/applicationRoute.js
  4. follow the [namespace][Type] naming convention, so that you can super+p any file by typing it’s namespace. e.g; /packages/application/applicationView.js.  The only exceptions are components due to limitations of the framework. (expects a components folder and a templates/components folder).
  5. Don’t use AMD, CJS, or browserify.  This forces you to work within the conventions of the framework, as all references to other namespaces are available within your declarations in nearly all scenarios (controllers can use needs: [], route actions bubble, view’s have ViewTargetActionSupport mixins available, etc.)  I personally use grunt-neuter.
  6. Think declaratively and reactively about how you want your logic to flow.  An example of this would be defining a ‘currentIndex’ property, and binding to when that index changes via observers or computed properties.
  7. Avoid pub/sub and Ember.Evented as much as you can.  It’s tempting to go the easy route with pub/sub to communicate with other components.  It’s almost universally a bad idea to do this, since there are so many ways to communicate with other parts of your application.
  8. avoid any logic within your templates.  They should be focused strictly on presentation.  Create computed properties on your controllers for defining the state of a view, and use those in if statements if you absolutely must.
  9. don’t use the {{each}} syntactic sugar.  use {{each foo in object}}.
  10. Long names are okay.  You shouldn’t be worried about using computedCurrentIndex vs idx in your definitions.  Think of the other developers who might someday look at this.  Do be that guy who tries to save a few bytes in javascript because they want to eliminate characters.  If you’re not using Uglify already in your grunt toolchain, What the hell is wrong with you?
  11. Treat your javascript as annotated source code, rather than something that gets interpreted.  What gets spit out of uglify doesn’t really impact any of your compiled code; go hog wild.
  12. components are effectively a controller, view, and template without a specific route.
  13. learn how to use the {{render}}, {{#view}} and {{view}} handlebars helpers.   {{render}} is invaluable for partials that may or may not need state. {{#view}} lets you define a yield block in your template or define it inline if need be.   {{view}} can be used for any self contained views you may need to otherwise {{render}} as a partial.
  14. Avoid Ember.Containeras much as you can.  If something cannot be accurately represented within an Ember.Object, try again.  The API is ugly and frankly Ember.Objects give you just about all of the value of them, short of their singleton-like nature (which you can manage with an IIFE and an instance if you must).
  15. this.send('someActionName') within the context of an any controller or route will trigger that action on the controller first, and will bubble.  Use this to your advantage wherever possible.  Need to communicate with routes to a parent of your own? this.send('action') all day long.  Need to be able to override actions in a specific controller or route? just return false from the route, or return true to continue propagation.
  16. jQuery events, short of very specific events or library integrations, should be eliminated in favor or route/controller actions, or handled by a view directly.  This will save you from having to fight the framework later on when you start running into edge cases, dangling references, or worse; zombie events.
  17. Initializers are to be abused whenever possible.  Use them with aplomb. App.Initializer('namespace', initialize: function () {}); – learn what App.delayReadiness() and App.advanceReadiness() are (iOS developer? this is a retain/release cycle for your application’s boot up.  once the retain cycle hits zero, your app is going to start up. Want fixtures? Load them via an initializer and inject them into an Ember.Namespace).
  18. Mixins are great for abstracting common things.  The easiest example would be defining a keyboard event as a mixin, then just executing methods on a “keystrokes” hash in your mixed-in class.   Voila- now every controller or route or what have you can support specific keyboard combinations.   Need to handle pagination? make a consistent mixin api and use it across the application. These are the towels that make you DRY. (groan)
  19. if you find yourself using this._super() pretty much anywhere other than in route.init() or controller.init(), ask yourself long and hard if that inheritance chain can’t be handled in a mixin.  You can probably refactor that for the sanity of everyone.
  20. within the context of a route you can access methods such as this.modelFor('namespace') or this.controllerFor('namespace').  If those elements are currently active, they will return their models or controllers.  Don’t make extra http requests if you can avoid it.
  21. make sure that within a route’s setupController hook, that you set the model on the controller before doing ANYTHING else in that hook. e.g; controller.set('model', model);.  Nothing else will work and it’ll throw an error otherwise. You may see model and content interchangeably used. Use model, not content, it’s getting depreciated.
  22. when you define a resource within your router, you’ll get route.index, route.error, route.loading routes for free, regardless of if you define them (you ought to, especially index).
  23. resources defined in your router have two layers; the base resource (defined as whatever your namespace is + route, controller, or view.) will be loaded FIRST, and then any sub-routes of that resource are loaded.  This means that an App.FooRoute, App.FooController, and App.FooView are loaded before App.FooIndexRoute and App.FooIndexController are set up.  use this.modelFor('foo') to grab the parent’s model if you need data.  Your separation of concerns here is that you want to have the parent resource manage it’s model, and any routes defined under it take care of performing actions with that model.  This one took me ages.
  24. Need to handle view transitions, in the visual sense?  Define a mixin that implements two methods: didInsertElement (be sure to call this._super()!), which in turn calls didAppear.  Each view’s didAppear hook can then set up any transitional properties necessary to animate the view appearing.
  25. in the vast majority of cases, you’ll be binding a lot of classes.  learn the semantics of the {{bind-attr}} helper when it relates to classes.
  26. figure out a good way to bind properties to inline-styles.  You may balk at this, but what do you think jquery.transit, TWEEN, and jquery.animate() do?  now imagine you could databind to those animation flags, using rAF.
  27. when using a component in a template, remember that the assignment is {{my-component INTERNAL_BINDING=EXTERNAL_BINDING}}.  Don’t be afraid to pass in an entire controller’s context if that component is complex.
  28. on that note, don’t be afraid to nest components into one another.  There’s no reason why you shouldn’t do that.


This list is by no means exhaustive, but it’s a good starting point of little tricks i’ve picked up along the way. Have one to add? leave a comment or ping me on twitter @landongn

Being unproductive sucks. Breaking the cycle can be writing ten lines of code, or forking some interesting project on github and poking at it with a stick. Every developer is different. Find your charger somewhere and go do. Do it every day. Do it with quality in mind.

Why I like game engines.


Tooling needs to be good to feel productive.  There’s a sense that you can never really profile well enough.  Constant fiddling with data structure variations for Entity and Component patterns.  You’re not at a sub 17ms loop, so you spend days figuring out how to hack the inner entity tick loop to optimize away 3,000th of a second to get there.