Explaining closures to a five year old…

Once upon a time, someone on Stack Overflow asked the question, “How to explain Dependency Injection to a 5-year old”

The author of the question was really just looking for a good simple explanation but the title had resonated with people and I was surprised to see that person after person had either declared it impossible or had made a snarky comment about child abuse or something. But the answer was really obvious so I posted my answer: http://stackoverflow.com/questions/1638919/how-to-explain-dependency-injection-to-a-5-year-old/1638961#1638961

And I got more up votes than for anything I’ve ever answered before or since. So when I was asked in a recent job interview if I could explain dependency injection, I laughed, and then I explained why I laughed and what my answer had been. Then later in the interview I was suddenly thrown a new one, “Can you explain closures? No wait, can you explain closures to a five year old.” I have to admit, I vapor locked. I could not come up with an answer that a five year old could possibly understand. To me closures have three elements you have to talk about if you want to explain them (or at least how they are in JavaScript which is where I have the most exposure to them). They are, a repeatable set of code that can be handed around and called in different circumstances, a set of variables which were bound when the closure was created, and another set of variables which can be passed into the closure so they are different every time it is invoked. So I did explain it at that level and the interviewer was pleased, at least to the extent that I got the job.

But I couldn’t let that drop, so I thought about it and it occurred to me that there was a pretty good analogy in a child’s life to closures. So I wrote it down and sent it to the interviewer the next day, and maybe that’s why I got the job after all. But anyway, I give you closures for a five year old…

You know how you like to play Star Wars*? I know what you mean when you say you’re going to go do that and I can tell you to “go play Star Wars” and you understand me.

You can play it in different places, like over at Jimmy’s sandbox and it will be Star Wars on Tattooine or in your big box that is Jabba the Hutt’s palace, but you can always have your Luke Skywalker, Han Solo, and Darth Vader with you so that part stays the same as when you first played it in your own room.

*Substitute Barbie if you prefer.

Can you do JavaScript development with just an iPad at hand?

I recently headed off on a five day vacation and though I do have my priorities in order (eat, see the sights, take photos, walk a lot, read a lot) there is inevitably some downtime as the days go on. I didn’t want to lug along a laptop on this vacation so I resolved to see if there was any practical way to play with AngularJS and Ember.js (two frameworks I’ve been interested in recently) using only my iPad and an inexpensive Bluetooth keyboard.*

iPad and Bluetooth keyboard

For those who wish to skip ahead, the short answer is that it is possible, but it’s not much fun figuring it out so I’ll tell you later how I did it. As for whether it’s practical, I don’t think I’d consider it for anything except a small test project and the reason why comes down to one simple thing: debugging. If you’re a modern JavaScript developer you’re used to wonderful tools like Firebug and the Chrome Developer Tools for debugging and while Safari on iOS once had access to some basics like the JavaScript console those have been removed from iOS 6 in favor of a new remote debugging method. The new solution relies on a remote connection to Safari on Mac OS X. I’m sure it’s a much more sophisticated solution but why did we need to lose all JavaScript debugging support on iOS to get it? If I have to have my Mac along to do debugging I might as well do the JavaScript work on OS X in the first place…

That leaves your only debugging option as Firebug Lite 1.4, a project which has basically been abandoned due to lack of funds or interest or something and when I tried to combine it with AngularJS I was never able to get it to appear within the browser. I had more success with Ember.js because it both appeared and showed all the console messages from Ember, however the script tab was unable to show me the contents of any of the JavaScript files I was including locally. Due to the slow performance of the wi-fi at my hotel I pulled firebug-lite.js, jquery, handlebars, ember, etc. all down to my iPad and put them in the same location as the index.html file and the main.js file I was editing. Due to some form of security restriction with how the files were being loaded into the local browser Firebug Lite was unable to show any of them to me.

Ow.

That means that you’re going to be flying completely blind with AngularJS unless you’re prepared to handle logging via some other mechanism and even on Ember.js, are we really looking forward to something that’s reduced us to debugging entirely via log messages?


Textastic

I promised that I would say what I found worked best for development work and it was Textastic. It will let you create directories, fill them with files, edit them, and then view them with a built in instance of the iOS browser. It’s simple and straightforward and I was able to paste in sample AngularJS and Ember.js pages and they worked just great. I just couldn’t ever debug them properly. It does cost a few dollars but if you’re just looking for some easy way to play with HTML, CSS, or some simple JavaScript when all you have is an iPad (and hopefully a paired keyboard) then it’ll do in a pinch.

BTW, Cloud9 IDE looks like it would be an even better solution to this problem but they use the Ace editor and for whatever reason, it doesn’t work well on an iPad. I had problems with cursor position being one place while actual editing was another, it didn’t want to work well with my keyboard, it seemed slow, etc. There needs to be some work done on either the editor itself or on the iPad browser (or perhaps both) to make that a more viable solution.

Textastic - Ember.js plus Firebug LiteP.S. Most of this blog entry was written on the self same iPad/keyboard so don’t think the iPad is useless for any form of content creation, it just doesn’t do software development well at this time.

* Specifically a third generation iPad and the AmazonBasics Bluetooth Keyboard.

What I learned from… Ruby on Rails

After I read the excellent article 4 Things Java Programmers Can Learn from Clojure (without Learning Clojure) I not only took in the interesting lessons the author had, but I was prompted to think about all the lessons I’ve learned over the years from the various frameworks, languages, APIs, projects, and people I’ve worked with.

So, in the interest of starting a series which I may or may not update periodically, here’s the first installment of “What I learned from…”. I decided to start with the single framework I spent not that much time with (off and on for a couple of years) but from which I learned more than any other; Ruby on Rails.

Here are five things that I learned from Ruby on Rails:

1: A holistic approach can be wonderful

A lot of frameworks and languages end up just being a big bucket of parts from which you can pull to assemble your own development platform. What ends up happening is that every business ends up with their own variant on that mix.

Rails is often referred to as “opinionated”. In practice that means that they make decisions for how things will be, whether its file formats, or directory structure, or the libraries which are included as standard. They try to come up with a solution that will work 80% of the time for every need a web application developer typically has and then wire that up as the standard in the framework. However, in many cases they have put in work to ensure that you could replace a given piece if your app is one of the 20% for whom that particular solution isn’t a good fit.

2: All the “extras” as standard

This is kind of saying the same thing as my comment about a holistic approach, but lots of other frameworks I’ve worked with skipped huge swaths of problems and yet still seemed to think of themselves as “one stop” solutions. Rails saw that you didn’t really have a solution unless you had addressed package installation, testing, different deploynment environments, database changes, etc. Here are three big ones that are either usually skipped or which didn’t get much attention until post-Rails.

  • Testing – No, testing isn’t really optional. It makes your code better and it costs very little once you get over initial setup costs. Any effort put in by the framework to make it easier is time spent that multiplies tens or perhaps hundreds of thousands of times as it encourages people to improve their projects.
  • Environments – This is such a basic thing that I’m astonished how few frameworks deal with it. Virtually all software is run in development mode with different settings than in production. Even if those are your only two enviroments (or if you have others like test and beta), you can benefit from having support for different configurations and setup that are per environment.
  • Migrations – Although there are some third party Java libraries (Flyway, LiquiBase) that try to offer the same kind of functionality, I haven’t seen Rail’s concept of a series of updates which can take your database to the latest version to match your code (or backwards when needed) take off nearly the way a lot of other early Rails stuff seems to have been adopted elsewhere. I think just about every app development framework which deals with databases would benefit from it and I’m always surprised this one hasn’t spread more, though I noticed a recent Kickstarter to add them to Django.

3: Convention over configuration

If you’ve ever worked with Struts then you’re familiar with files that have to be filled in with data every time you add a new page to an application. Rails avoids that by simply saying, “Put this type of file in this directory and I’ll know, by convention, what you want me to do with it.” In many cases it can use the name and location of a file to know everything about how to hook it into an existing application.

There are people out there in your career who will try to convince you that having a file (or in some cases, many files) you have to edit are better than simple conventions. That they allow you “flexibility” and you can put your files anywhere you want. Do not listen to those people.

4: Proscribed directory layout

Simple test, take a random open source Rails project out of Github and a Java one. Try to find stuff and quickly understand each of the two projects. The Maven proponents would claim that adopting Maven gets you that same kind of structure to your project for Java and I don’t have enough experience with it to agree or disagree. But my experience with regular Java projects tells me that each one is a “unique little snowflake.”

5: method_missing

This is actually a Ruby thing and not a Rails thing at all, but Rails gets lots of mileage from it.

method_missing is a method that gets called whenever a method gets called on a Ruby class that doesn’t exist. However, you can implement method_missing yourself and you get full information on what the code tried to call. Rails uses that in ActiveRecord to synthesize new functions on the fly to keep the syntax of their ORM system ridiculously simple. For example, “Person.find_all_by_name(‘John’)”. Is there really a find_all_by_name? Nope. Can it create one on the fly based on the name of the function you called? You bet.

It seems like method_missing is something that would only work in a dynamic interpreted language like Ruby, but I’ve long thought that you could create a completely compiled language that would be capable of synthesizing new functions like this at compile time as well. The benefits are largely in the area of ease-of-coding but they are real ones. For example, why bother having getters and setters on your classes if they could be synthesized automatically?

I’m not sure where I’m ever going to use a language construct like this again unless I somebody asks my advice about writing a new language, but I’m storing it away. You never can tell when something like that will come in handy.

Easy background images for your iOS views

On an iOS game I’m developing I wanted a background image on some of my views. That’s an easy thing to do in the interface builder by simply adding a UIImageView stretched to the full extents of its containing view. However, I’ve layed it out for the four inch form factor of an iPhone 5 or the equivalent iPod Touch, how will it react to the form factor of an iPhone 4, 4S, or the older Touch?

The answer is that thanks to Auto Layout your controls can be made to adjust quite nicely, however, you’re going to have some issues with that image. By default the image view adjusted its size to the size of the containing window and squeezed my background image. Ick.

The fact that you may have two versions of the image, one Retina and one not (that is, background.png and background@2x.png) doesn’t save you because there are older devices that have both Retina displays and smaller screens. What you need is a solution that works with 4″ Retina, 3.5″ Retina, and 3.5″ non-Retina screens.

The background.png isn’t an issue. It should only come into play for non-Retina screens and to my knowledge there are no four inch non-Retina screens. Go ahead and just lay it out for 320 by 480 and be done with that one. Then, if the background is one where you can design a version that can safely lose 176 pixels in the long dimension (via a border or other area that can be safely clipped), then lay out a background that is 640 by 1136 with 88 pixels at the top and bottom that will be clipped off when it is viewed on the smaller screen. Then you can change one small setting on the image view so it will center and clip the image rather than squeeze it and you’re done.

The background image as it would appear on an iPhone 5 (640 x 1136).

The background image as it would appear on an iPhone 5 or similar 4″ Retina device (640 x 1136).

The same image automatically cropped top and bottom as seen on an iPhone 4 (or similar Retina device with a 3.5" screen).

The same image automatically cropped top and bottom as seen on an iPhone 4 (or similar Retina device with a 3.5″ screen).

The mode setting that makes it work. By default it's set to "Scale to Fill", change it to "Aspect Fill" and it will keep the width full but center and crop the image.

The mode setting that makes it work. By default it’s set to “Scale to Fill”, change it to “Aspect Fill” and it will keep the width full but center and crop the image.

Two images + One setting = Something that gives you easy backgrounds for all small iOS devices

But, if that’s not cutting it for you, there’s another choice. Have a third image ready. iOS has naming conventions for images (you saw some of them above with the @2x) that helps them load the right image for Retina or non-Retina and iPhone/iPod Touch vs iPad. However, they didn’t include a naming convention for the different form factors of 3.5″ vs. 4″.

So an alternative is to load a different image specifically for the Retina 3.5″ and let the non-Retina 3.5″ and Retina 4″ be handled automatically by the image naming conventions. Here’s some sample code that could go in the viewDidLoad to override and load an alternate image:

- (void)viewDidLoad {
  [super viewDidLoad];

  // Do any additional setup after loading the view, typically from a nib.

  // We're relying on automatic loading of background.png and
  // background@2x.png to handle the non-Retina 3.5" devices and the Retina 4"
  // devices.
  //
  // So we're manually detecting Retina 3.5" devices and loading a special
  // image just for those.
  if  ((UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) &&
    [[UIScreen mainScreen] scale] > 1.0 &&
    [UIScreen mainScreen].bounds.size.height != 568.f) {
      [self.backgroundImageView setImage:[UIImage imageNamed:@"alternateBackground.png"]];
  }
}

Bringing Unit Tests To Untestable Java Code

I deal with a lot of code that has never had any unit tests for it at all. In fact, it was often written in such a way that creating unit tests for it seems pretty horrific because you would find yourself having to load data into multiple database tables, set up all manner of services and files, etc. just in order to test it properly. So what I’m going to tell you is the simple, not-too-painful way I chose to make some of this code testable.

To me it’s all about removing all of the external dependencies from the code. If I can pull out all of the sections that are getting remote connections to EJBs, all of the data source lookups and queries, file reads, etc. and abstracting those out then I can test the code fairly easily because all I’ll be testing is the logic it had that surrounded all of those external calls to get data of one sort or another. So that’s what I do, I remove all of the code that does those lookups and abstract it out.

Note: Some of the feedback I’ve gotten tells me that I should make it clear that what I’m talking about below is only the refactoring part of getting your code to a unit testable state. After you perform some of the steps you might be well placed to look into either Spring or JSR-299 (for example Weld, which is their reference implementation) to do dependency injection. Or even into mock frameworks to do simpler implementations of your FooHelper for testing purposes. If you’ve got one you like a lot, let me know about it. I haven’t used any mock libraries for Java yet.

Step 1 – Use the refactoring capabilities in your IDE to extract some methods

I’m using Eclipse in this example, but I’m sure you could do much the same thing in Netbeans or any other major IDE.

Eclipse has a function on the context sensitive menu to extract a method. Just select a section of the code that goes and looks up something in a file or gets a JDBC connection and executes a query (or calls some code that does) and click the right mouse button to get the context menu, then select Refactor > Extract Method… and fill out the info in the dialog box where it asks you what to call your new method, etc. The refactoring will create an all new function which takes a set of parameters passed in and replace the code in the original spot with a call to that function. Repeat as needed on the offending section of code until you don’t have any code within it that isn’t actual logic that calls these new methods that use external resources.

Step 2 – Pull the new methods out into an external class

I don’t doubt that I could probably get Eclipse to do all of this too but at the moment I perform the next step manually.

Let’s say that the code that I was pulling methods out of was called foo(). Then I would create a new class called ProductionFooHelper at this point. I would pull all of the methods I extracted out of the class foo() was part of and put them into ProductionFooHelper(). That immediately breaks the foo() code because it no longer knows where the functions it used to call are anymore; but it leaves us with a version of foo that doesn’t require any exterior resources. That brings us to…

Step 3 – Extract an interface from the ProductionFooHelper class

Here Eclipse will do the tedious work for us again. Go to the ProductionFooHelper class and right click. Select Refactor > Extract Interface… from the context menu that pops up.

You can just select all of the methods to be in the interface and give it a name like FooHelper. Click OK and it will be created. Note that ProductionFooHelper should be marked as implementing the FooHelper interface.

Step 4 – Fix the failing calls within foo()

Go back to the class containing the foo() code and add a new parameter to it. The new parameter would be something like “FooHelper helper”. Then all the function calls within foo() that are currently showing as errors within the IDE can have “helper.” put in front of them. That will indicate that we’re calling that function on the passed in class. At this point everything in the code should resolve again except for the spot you originally called foo(). It will need to have an instance of ProductionFooHelper created and passed into it before it compiles successfully.

At this point we’ve extracted all the code which had external dependencies into another helper class and we have a production version of that class that should give us the exact same behavior we’ve always had. But if we were to produce a MockFooHelper that implemented FooHelper and produced faked results for unit tests, then we could test foo() at our hearts content knowing that we never have to do database setup or anything else unless we want to. The specific implementation of the functions in the FooHelper is up to us for testing purposes.

This may seem a convoluted way to get to testable code and maybe you’ve got much better ways to achieve this same thing. If you do, I’d love to know about it so I can improve my own coding skills. But if not, I have to say that it actually works. I’ve used it recently in a hierarchical fashion where innermost code had a helper interface extracted, then another close to it, and then yet a third. Then I wanted code that called all of them to be unit testable so I extracted a new interface that implemented the other three interfaces and added all new functions as well. The production helper had all of the methods for the innermost stuff as well as the outermost. The result is that I now have four different test points in the code where I can control everything that goes in and out and I was able to whip off a dozen new tests for code that once had none due to its complexity and the difficulty of setting something up.

100+ Year Old Color Photos and Amazon Kindle Apps Coming

The 1906 San Francisco Earthquake Aftermath, In Color – A couple of photos taken with an early color photo process have been reassembled (using Photoshop of course) so you can see that the past wasn’t really in black and white.

Amazon Adds Apps to the Kindle – I like my Kindle DX, I like it a lot, but I do not love it. I love my iPod Touch. It is my constant companion and many are the days when I return it home with a battery that is quite drained from use. I can think of many many ways to make my Kindle much better than it is today because the UI often very poor, even for it’s intended use as a book reader. Perhaps this will help it get past some of those problems or maybe it’s just too little too late.

Follow up to the post: Here’s the link to sign up for notification when the Kindle dev kit is released.