rohan singh

software engineer. bicyclist & rock climber. craft beer addict.

Responsive Android Apps With Scala

When it comes to building responsive Android apps, there are two commandments:

  1. Don’t block the UI thread, ever.
  2. Only access and modify the UI from the UI thread itself.

The Android Dev Guide goes into some detail about this. The usual solutions in Java are to:

  • Spawn a thread that does work and then invoke View.post with a Runnable that manipulates the UI.
  • Implement and run an AsyncTask that does work in doInBackground, and then manipulates the UI in onPostExecute.

As you can see, both these solutions — though they are the bread and butter of Android development — are pretty verbose and unwieldy:

I prefer AsyncTask, which has better semantics, but implementing one AsyncTask after another quickly becomes tedious. Same with writing line after line of Runnable boilerplate.

Enter Scala, using either the sbt Android plugin or my Maven-based solution.

The first step is to create an implicit conversion from a function to a Runnable, which can then be passed to View.post or runOnUiThread. Once we’ve done that, it’s simple to use spawn from scala.concurrent.ops to do background work.

Here’s a fully functional example:

This is so much nicer than the Java alternative. Instead of up to ten lines of boilerplate for each background task, we end up with just the spawn and runOnUiThread.

If you’re waiting for that final push to switch over to Scala for your Android development, I highly recommend the sbt plugin for Android. Take a look at its brilliant Getting Started guide, which will have you up and running in just a few minutes.

Fixing Thunderbolt Ethernet on the MacBook Pro

A few weeks ago, I had to make one of the toughest choices I’ve had in a while: a 30” Dell display, or a 27” Apple Thunderbolt display. I went with the Thunderbolt display, partly because the colors are better, but mostly for the convenience of having USB and ethernet integrated into the display.

The way this works, you can just plug your USB peripherals and your network cord into the Thunderbolt display. Then, whenever you dock your MacBook Pro, you just connect the single Thunderbolt cable and the display, USB devices, and network all work magically.

It’s much more convenient than doing the daily morning dance of plugging four or five things into your MacBook, and it’s the closest thing we have to a good MacBook Pro dock.

Well, that’s the theory anyway. In reality, while the USB works fairly decently, the ethernet connection dropped out on day one, and I haven’t been able to get it back since. Until today.

Here are the final steps that worked for me. Hopefully somebody else can save a bit of time with this:

  1. With the Thunderbolt display connected, visit the Network tab in System Preferences. If you see Display Ethernet and/or Display FireWire in the list of network interfaces, select each one and use the minus (-) button at the bottom of the list to remove it.

    For me, Display FireWire was listed, but Display Ethernet was not. I’ve heard of others having strange symptoms with neither or both listed.

  2. Unplug the Thunderbolt display. This will not work if you keep the display plugged in while doing the next few steps. Trust me, I tried it.

  3. sudo rm /Library/Preferences/SystemConfiguration/NetworkInterfaces.plist

  4. Restart your MacBook Pro and log back in. Once you’ve logged in, connect your Thunderbolt display again.

  5. Visit the Network tab in System Preferences again. If you see Display Ethernet and Display FireWire listed, you’re all good. Otherwise, click the plus (+) button at the bottom of the list of network interfaces.

    From the Interface dropdown, select the interface you have missing and click Create. If you have both interfaces missing like I did, you will have to repeat this step for the other interface.

After all that, everything seems to be working smoothly for me.

Stockholm Speaks Out on ACTA

If you haven’t heard about ACTA, it’s a damaging piece of legislation very similar to SOPA — the difference being that ACTA is international in scope and much closer to becoming reality than SOPA ever was. Here is a video explaining ACTA which I found to be quite educational.

Anyway, Stockholm decided to take to the streets to protest ACTA today. Here are a few photos of the fairly well-attended event that I managed to snap on my phone:

Crazy Color-Coded Problems

Earlier this week I moved from Seattle to Stockholm, where I’ll be working at Spotify. I arrived and started settling in on Friday. On Saturday, I decided to check out out the local bouldering scene.

There’s quite a few gyms in the area, and the closest ones to downtown are run by Klättercentret and Klätterverket. The Klättercentret in Solna is the place I was really looking forward to visiting. But since it’s closed for renovation until next week, I instead found myself at the Klättercentret in Telefonplan.

What I found there was a style of setting I had never seen before on such a scale — instead of being marked by tape, problems are based on holds that are of the same color and style.

Here’s a photo of the place by Helena Wahlman at the Swedish photo blog:

Look closely and you’ll see that there’s pretty much no tape on the wall. For example, neither of the holds the guy in the photo is using are marked. Instead, he knows to use them because they are yellow.

What little tape there is just marks the start and end of a problem. The color of the tape is what specifies the problem’s approximate grade:

At the moment I’m not sure if this is a regional thing or just a Klättercentret thing.

One thing I can tell you is that, at first, I was very, very confused! I’d expected a different grading system, but when I first walked up to the wall in Telefonplan, I seriously had no idea what was going on. Of course, I tried to figure out what other people were doing, but I’m not used to looking at the color of holds.

Until I realized what was up, I just figured everyone was improvising their own problems. Also, at the time I hadn’t realized that the vast majority of the bouldering area at Telefonplan was on a different floor. Those things combined to make me wonder if I was in some special kind of hell where bouldering was just a joke.

What finally made it click for me is when I found a long overhanging problem comprised entirely of bright orange holds. Once I saw that, everything clicked into place and I could suddenly see all the problems everywhere! There were quite a few excellent problems, and overall it was a great session.

Thoughts on this style of setting:

  • Grading. The approximate grading is something I can appreciate. It lets you walk up to a problem and have a general idea of what it’s going to be like, but without forming preconceptions of whether or not you can handle it. Moreover, it reflects the reality of a gym problem where grading is inexact and approximate, based on the perception of a single setter.

  • Visibility. Once you get used to the idea, identifying holds based on hold color isn’t that different from tape color. You do have the same problem as with tape where similar adjacent colors can be difficult to pick apart. In some cases, you have an additional problem where heavily-chalked holds become difficult to identify.

  • Style. Each problem definitely takes on a certain style based on the type of hold used. I imagine this could be really handy when you want to train a specific skill. If you pick a problem that starts with a sloper, it’s going to be full of slopers that came from the same set. Same with crimps, or jugs or pockets or what-have-you. As an example, I’ve set something similar before using a single set of bright pink crimps, and it was great for training crimps.

All that said, I’m still not sure about this system. In a way, I’m sure it encourages creativity, as limits and constraints tend to do.

Yet, the fact remains — with a given set of holds, you can express more problems and permutations if you can mix holds of different colors. Then again, the point of setting is to create challenging, climbable problems, not just to mathematically optimize your theoretical problem space.

Isn’t All Coding About Being Too Clever?

Every now and then I have a discussion or lecture with my roommate Chris, on some aspect of software engineer, architecture, process management, or programming in general. His specialization is psychology, so while this exercise can be cathartic, it’s largely pointless. I’ve decided that it might be more effective to write these things down and post them.

Today, prompted by a discussion on what I should name some new object, Chris asked:

Isn’t all coding about being too clever?

I think that is a conception that many laypeople and beginning programmers have — that we should try to be clever. Seasoned engineers will know that being clever can be one of the worst sins.

Here was my response, paraphrased:

The goal is to write the minimal code that (a) gets the job done, (b) doesn’t break, and (c) is understandable and maintainable by other people.

“Clever” often meets the first requirement, can sometimes meet the second, and always fails miserably at the third — which is actually the most important one. All things equal, I’d often rather have a broken system that I can understand than a rat’s nest of code that happens to work.

That said, sometimes you do come across clever code that meets all of those requirements. These are small masterpieces and works of art and should be regarded as such.

Extreme Response Times

Looks like I have some serious optimization to do for the new stuff that I’ve been building:

At least the latency seems pretty good?

The Inner-Platform Effect

Today someone on Hacker News posted a link to the Wikipedia article on the inner-platform effect, which is “the tendency of software architects to create a system so customizable as to become a replica, and often a poor replica, of the software development platform they are using.”

One of my favorite parts of the article (emphasis mine):

In the database world, developers are sometimes tempted to bypass the RDBMS, for example by storing everything in one big table with two columns labelled key and value. While this entity-attribute-value model allows the developer to break out from the structure imposed by an SQL database, it loses out on all the benefits, since all of the work that could be done efficiently by the RDBMS is forced onto the application instead. Queries become much more convoluted, the indexes and query optimizer can no longer work effectively, and data validity constraints are not enforced. Such designs rarely make their way into real world production systems, however, because performance tends to be little better than abysmal, due to all the extra joins required.

Oh man, if only. I can think of at least one example of a a platform with this very problem — and with the associated horrible performance profile — that is very widely deployed and used in production environments around the world. I’m sure you can think of others.

Actually Dreaming in Code

Before I begin, here are a few great, relevant xkcd’s: #719 #430 #203

Anyhow, say what you will about Scott Rosenberg’s book, Dreaming in Code — but the fact is, it makes Googling for experiences of actually dreaming in code fairly impossible.

Personally though, I find dreaming in code to be very real. My dreams have always quite vividly blended reality and the imaginary, often leaving me confused as to which is which, and leaving me with a somewhat tenuous connection to the former. Code dreams are no different, and I’ve found that mine fit into three major types:

  1. The Text Editor. This is your fairly standard code dream. In my case, white background, plain text and some code appearing or being written. Sometimes, it might make sense and actually relate to a project I’ve been working on or code I’ve being writing, but quite often this code doesn’t make any sense whatsoever.

    Often, there is no background or text, but just the lines and constructs of code floating in a place where there is no physical reality. I wonder if mathematicians have dreams similar to these, but with mathematical constructs?

  2. The Inspiration. These dreams are comparatively rare, and don’t actually seem to involve any coding whatsoever. However, they very specifically relate to something I am working on, and when I wake up I know how to structure some code that I have been struggling with.

    This seems to be a pretty straightforward case of the brain working on a waking-world concern while asleep. Too bad the hours aren’t billable.

  3. Code Blends With Reality. This is the strangest type of dream and the most difficult to relate, but in many ways my favorite. In these dreams, physical reality seems to blend and mix with the reality of code. While there is a normal dream of the physical world underlying everything here, in these dreams I interact with that world with code instead of in the normal physical manner.

    For example, I might find myself writing a script to light a campfire. Or instead of traveling from place to place by walking or in a car, I might just fiddle with the parameters that define my location. People may speak in code or in concepts rather than words.

Overall, I find #3 to be the most common type of code dream I have, as well as the most interesting. It lets the world become a playground that is strangely close to the real world. It is almost as if, in these dreams, magic is real, and code is magic.

While it’s probably not the most important thing in the world, I’m really curious to hear whether lots of other people out there dream in code, and how everyone else’s code dreams differ from mine.

After all, we spend an amazing amount of time asleep throughout the course of our lives. Who knows, maybe if talk about dreaming code enough, clients will agree that those hours asleep should be billable after all, eh?

Stone Sublimely Self-Righteous

Every winter for the past few years, I’ve spent at least a weekend in San Diego. Not only is the tropical sun a great respite from gloomy Seattle, but San Diego — against all odds and expectations — is a brilliant beer town, and home to the iconic Stone Brewing Co.

To get myself into the right mindset for my upcoming trip, tonight I am enjoying Stone’s Sublimely Self-Righteous Ale. As frequent drinkers of Stone are surely aware, that brewery is full of downright bastards.

Which is why I just had to share this brilliant excerpt from the label on the back of this dastardly, self-rightous bottle:

Yes, we damn well know our stuff here at Stone, and it would be irresponsible of us to not acknowledge how remarkable this heavenly creation of ours is. Thus the name we are compelled to give it — Stone Sublimely Self-Rightous Ale – serves as a reminder of just how good we are, in both liquid and verbal form.

And also:

When you’re good, you’re good. And when you do something great, the least you can do is acknowledge it. Others benefit from knowing.

For the record, this self-righteous ale lives up to its label and leaves a smile on your face — or, at least, on mine.

What I’ve Been Reading (Dec. 26, 2011)

What follows are the most insightful, interesting, or otherwise noteworthy articles I’ve stumbled across over the past couple weeks.

  • Democracy is not a truth machine. One of the best articles I’ve read all week. In it, a bearded philosopher eloquently demonstrates why democratic processes can’t be trusted to find the truth about objective facts about reality. For example, while a democratic process can be used to decide what we should do about climate change, the underlying scientific reality is not up for debate.

  • Why we invented monsters. Paul Carr start with the idea that monsters grew into the human consciousness in the image of predators, such as felines and snakes. Eventually, as protohumans transformed from a prey species into predators, our imaginations transformed as well.

  • The scandal of the Alabama poor cut off from water. It really kills me that we need a foreign news source to report about the fact that America’s infrastructure is failing and the promises of citizenship aren’t panning out for some of those who have the greatest need. Reading this article, others like it, and watching the documentary Waiting for “Superman” over the weekend has left me with a lot of questions in a place where there are few good answers.

  • Why America’s Death Penalty Just Got Us Sanctioned by Europe. The European Union has decided that it will have no part in the barbarism involved in the methodical killing of human beings by their peers. I completely agree with Ford Vox’s characterization of the situation:

    The death penalty is a blind spot in our democracy, our own peculiar national anosognosia. It probably will take the rest of the world shouting us down in order to recognize our impairment.

  • A tale of two systems. The folks at Remapping Debate contrast a failing labor system in America with a robust, unionized system in Germany.

  • Hitch. Sam Harris, eloquent as always, on Christopher Hitchens’ death:

    Needless to say, he was effortlessly lucid and witty—and taking no prisoners. There should be a name for the peculiar cocktail of emotion I then enjoyed: one part astonishment, one part relief, two parts envy; stir. It would not be the last time I drank it in his honor.

  • Freakonomics: What Went Wrong?. Andrew Gelman and Kaiser Fung examine many of the conclusions in Freakonomics and Superfreakonomics which have worked themselves into the cultural consciousness and which are now taken for granted. Specifically, they show that many of these conclusions are just plain wrong.