Reflections on one month of iOS development: Part II

February 14th, 2012 by acw

Or, “An intro to iOS/Objective C/Cocoa Touch for people from other programming backgrounds”. This is part II of II. Part I is here.

Now that you’ve gone through part 1 of this series, you should feel that your comprehension of Objective C is coming along, but you’re still wondering how to relate that knowledge to making iOS apps. Great – let’s start turning on the light. We’ll continue to use the source of Paolo Quadrani’s Ecological Footprint app as our example of a working iOS app. Let’s get started:

  1. If you recall from part 1, I said that you can think of the AppDelegate as the entry point to an iOS application. That’s only sort of true – the true entry point is the main.m file (generated by Xcode), which contains a single function that will be very familiar to anyone who’s ever looked at an application built in regular old C: int main (int argc, char *argv[]). This is where our app’s lifecycle begins. The real magic of this function is on line 14, with the call to the UIApplicationMain function. While I’ll leave the details of that call for this excellent discussion, the basic gist is this: the nil arguments tell the function to look for a .plist (Property List XML) file, which contains a key called NSMainNibFile. The value of that key points to an Interface Builder file (.xib), which has a different key that articulates where to find an AppDelegate. In practice, you really can treat the AppDelegate as your entry point, but it’s still worth having the full picture.

  2. So let’s get back into the AppDelegate. Open up the EcoFootprintAppDelegate header and implementation files again. You’ll see that in the interface for the AppDelegate, there’s a member variable of type UIWindow. An AppDelegate must create a UIWindow instance and populate it with views – that’s the delegate’s fundamental purpose. Where does it do that? In the UIApplicationDelegate protocol’s (void)applicationDidFinishLaunching:(UIApplication *)application method. What’s the UIApplication instance that gets passed in? That’s created by the call to UIApplicationMain described above, and is basically the overarching object that controls the event routing within an iOS app.

  3. So how does the applicationDidFinishLaunching: method create its views? By creating instances of those views’ controllers and adding them to the window object through [windowVariable addSubview: [controllerVariable view]]; Let’s walk through it. First, notice on line 11 that the MainViewController.h header is included – we’ll need that to create instances of the controller. Line 50 is where the instantiation takes place. Down on line 61, that instances is used to place the controller’s view in the window. Line 62 then makes the window the main window and causes it to be visible. Voila – your controller’s view is now front and center.

  4. So let’s dig into what makes those views tick. When you add a new view to a project, you’ll typically create three files: an Interface Builder xib file, a controller implementation (ie, subclass of UIViewController) and its corresponding header. You’ll create the xib using IB and lay everthing out. Do nothing more and try to compile it – you’ll get an error about the view outlet not being set. What does that mean? Remember how we are using the controller to access the view to add it to the window? It’s looking for a member (of the controller class) called view, which needs to correspond to the UIView instance that is, in fact, the interface you’re presenting. How does that get set? Look back to line 50 of the implementation file – you’ll see the controller instantiated like this: [[ControllerName alloc] initWithNibName: @”NameFromIB” bundle: nil]; …the initWithNibName method of UIViewController loads the Interface Builder file and sets the controller’s view parameter based on the view outlet set through IB. Since no view outlet has been set in IB, you’re seeing the error.

  5. OK, so how do I eliminate the error? Simple. In Interface Builder, set the File’s Owner property of the view (in the WhateverName.xib window) you’re trying to load to the name of the controller that should correspond to it (I’m guessing this seeming redundancy is so that IB can determine the variables/actions available and prevent errors before compiling). Next, click the second tab of the view’s property window (My View Connections) and drag the view outlet over to the File’s Owner item in the WhateverName.xib window. Done. (Note that my terminology may be off and I’m referring to Xcode 3 – can’t upgrade the work machine yet).

  6. There’s been a lot of talk about UIView instances – why? The basic answer is because pretty much everything in your interface inherits from UIView (or is one directly). Look around the apple class reference docs and you’ll see it in most inheritance hierarchies: UITableView, UIButton, UINavigationBar, etc. Astute readers will notice that components that contain UIViews are, nevertheless, UIViews themselves. UIView instances can establish a container relationship by calling [uiviewInst addSubview: anotherInst]; It’s well worth reading through Apple’s docs on this class – you’ll never build a significant app without it.

  7. I see initWithCoder in some code – what’s that? For the vast majority of cases, you’ll use initWithNibName, not initWithCoder. It’s basically called to deserialize child components from within Interface Builder files. A better answer can be found here.

  8. Great – I’ve got an interface, it compiles and displays… now how do I talk to my controller? There are two ways you’ll want to interface with the controller from IB: configuring variable and assigning methods to handle events. To examine both, take a look at the header and implementation for EcoItemsViewController. On line 13 of the header, you’ll notice the keyword IBOutlet before a member variable definition. IBOutlet marks a variable as available for setting via IB. In almost all cases, these will be UI component variables, such as the UITableView seen here. In IB, the association is completed by accessing the View Connections for the UI component and dragging the New Referencing Outlet property to File’s Owner. You’ll then see a popup menu of possible variables based on type (hopefully including whatever you created in the header) – select the correct variable and you’re golden. Note that you’ll most often see @property definitions for IBOutlets, along with an @synthesize call. Why is this? Take a look here. For methods, the process is pretty similar: instead of defining your event handler as being type (void), you’ll set it to (IBAction). Your method is now similarly available in IB. Click on whatever UI component will be responsible for your event (eg, a UIButton) and find the event in the same View Connections list. For a UIButton, the correct event is often Touch Up Inside. Drag the event to File’s Owner and you’ll see a list of available IBActions – same process as above.

  9. How can I navigate between views? There are canned ways, such as having IB create a tab bar application for you, but I’ll talk about the most flexible way: UINavigationController. Make an instance of this as your first displayed view, but remove the actual visibility of the navigation bar (check its hidden property in IB). Now, in your applicationDidFinishLaunching: method in the AppDelegate, immediately cover that up with the actual first view you’d like to show. To cover it up, do this: [navigationControllerinstance pushViewController: viewInstance animated: YES] (obviously adjust the animated parameter according to your needs). You can call this anywhere in the app, as long as you’ve got a reference to the navigation controller, and push a view to the top. So how will you have an instance of navigation controller from within a pushed page? Simple. self.navigationController is set when a view is pushed, so you should never be without an instance. When you’re done with a view, you can call the popViewControllerAnimated: method: [self.navigationController popViewControllerAnimated:YES]; …This means of navigation is pretty much flexible enough to handle anything you want. Note that this is NOT the way to handle modal windows – check the docs for Modal View Controllers.

  10. A word of caution – iOS UI programming can be frustrating. Apple likes their interfaces to conform to a standard and sometimes it’s difficult to programmatically sidestep their decisions.

Some Odds and Ends:

These are important topics that don’t really fit anywhere else. They’ll tend to come up in more complex apps and are well worth understanding in advance.

  1. So how can I share data between controllers? OK – you’ve tried passing things around, but clearly that won’t work in methods implementing protocols. The next thing you try is sticking things in your AppDelegate and accessing them through a reference, but although that works, it makes you feel like you need to take a shower. Singletons are your shower. The singleton pattern is basically a way to ensure that there’s only ever one instance of an object. Just remember that your shower doesn’t have any soap – you’re still effectively using globals, but it’s better than nothing. I’ll leave you to visit this link for the details on implementation.

  2. I’m updating a UI component but I never see the update – wtf? This one bit me at the end of last week with no time left to solve it (I’ll update when it’s solved). The reason you’re experiencing this is that the update is taking place from a background thread. You need to force the update to run in the main thread. Here’s a StackOverflow question that answers how to do this.

Great – if you’ve followed along, you’re now minimally dangerous with Objective C. Feel free to update me if you learn anything particularly interesting.

Reflections on one month of iOS development

February 11th, 2012 by acw

Or, “An intro to iOS/Objective C/Cocoa Touch for people from other programming backgrounds”. This is part I of II. Part II is here.

(Note: The whole premise of this post is that I’m a beginner at iOS, and it’s useful to see a beginner’s perspective. As a beginner, I’ve probably misstated some things – feel free to drop a correction in the comments).

I’ve always found it interesting to read reports of what others are learning while they’re learning it. Watching someone else make mistakes and uncover revelations is a good shortcut to proficiency, in my experience. With that in mind, let me share some of the things I’ve picked up in just about one month of iOS development (coming from a background of not having an iPhone and only getting a smartphone a few months ago). We’ll cover some basic groundwork by taking a look at an example app.

To start, let’s be green about it and grab the source for Paolo Quadrani’s Ecological Footprint application (I found this from a list of open source iPhone apps and it seemed like a good fit for an intro). Now pop open the EcoFootprintAppDelegate.m file. This is the application delegate, which can be thought of as the entry point to an iOS app.

Looks pretty funny, doesn’t it? Kinda like someone smushed C and Smalltalk together? That’s pretty much what happened. Evidently, some Smalltalk fans decided to add a preprocessor to their C compiler and, voila, Objective C was born. An interesting historical discussion with some good language insight can be found here. One of the most interesting things about Objective C, in my opinion, is that the ANSI C language is a subset of Objective C – that means you can include C libraries in your Objective C programs, which is pretty great! (Note that you can compile Objective C for other platforms using gcc). Let’s dive in:

  1. #import? What about #include? Objective C’s #import statement is basically a nice variant of #include that only loads headers once, preventing circular dependencies. In practice, it seems like C libraries are often included via #include, while Objective C libraries are usually included via #import.

  2. @implementation EcoFootprintAppDelegate? This starts the implementation of a class, which extends to an @end directive. You’ll see a bunch more @directives as you wade through Objective C.

  3. Pop open the EcoFootprintAppDelegate.h header (we’ll use it ’til Section #8) and you’ll see two more: @class and @inteface. These are a little confusing… @class doesn’t actually start a class definition, but rather notifies the compiler that an identifier is a type of class, so that future references in the code are understood to be references to an object and don’t cause complaints. In practice, think of @class as a lightweight replacement for an #import in headers. In order to actually create an instance in your implementation, you’ll need to import the header.

  4. Still in the header, you’ll see a statement of the form @interface ClassName : ParentClass . Let’s break that down. @interface is the way you define a class in the header, the counterpart to @implementation, which also ends at @end. The colon separates the class we’re creating from the name of a parent class which we’ll inherit from. In iOS, even classes that are at the root of their inheritance hierarchy (eg, classes that wouldn’t have a parent in another language) should still inherit from NSObject; you should pretty much never be without a superclass. Also, not that Objective C doesn’t have multiple inheritance.

  5. I omitted the bit from the above line – it deserves separate treatment. This statement, which is totally optional, marks the class as a received of messages defined by the given protocol. What does that mean? Basically that you’ll have to implement methods defined by that protocol, and in exchange, will get some predefined behavior that calls those methods. This will be very important later on when you’re using UI components – many of them define protocols that your controller classes must implement.o. Note that there are informal protocols as well. For that, I’ll refer you to the Apple docs.

  6. Between the brackets, you’ve got instance variable definitions. Pretty self-explanatory. Beyond that, you’ll find method signatures. Note the minus sign in front. Looks like an access modifier, right? Wrong again! It denotes an instance method. Class methods are preceded by a plus sign. In contrast, the @public, @protected and @private statements (no parameters, no @end) are Objective C’s access modifiers. The default access level is @protected. We’ll cover the structure of method parameter lists when we get back into the .m file.

  7. So what are these @property lines after the method signatures? These basically notify the compiler that getter/setter methods will be created for a variable. To actually create the getter/setter, you’ll want to add a corresponding @synthesize statement inside the @implementation in the .m. Note that @property requires a full definition of the variable including type, while @synthesize just needs the variable name. Also note that @property takes parameters that describe treatment of the variable. Often you’ll see (nonatomic, retain). We’ll cover retain and memory management a little later on. As for nonatomic, that basically means that the getter/setter in question will not be thread safe and will be faster than the default. I’ll briefly touch on threading a little later as well.

  8. That’s pretty much it for the header, let’s get back to the implementation .m. At this point, if you’re feeling lost, I encourage you to visit this concise Objective C tutorial. Now let’s jump to line 26, the first method declaration. The applicationDidFinishLaunching method is part of the UIApplicationDelegate protocol we adopted in the header. The (void) that precedes the method name is obviously the return type. What’s different here is the Smalltalk style paramter list, where each parameter follows a colon and an identifier. That means method definitions with multiple parameters look a little strange… something like this:
    - (void) doSomething: (UILabel*) lbl withInput: (UITextField*) input { … }

  9. If you jump around a little, you’ll see a lot of expressions that look like this [object methodCall: parameter1 withAnother: parameter2]; …This is how Objective C methods are invoked. For the above example, a call in the same class might look like: [self doSomething: label1 withInput: text1]; Note that referencing the containing object can be done with the self keyword, like many other languages (Ruby, Python, etc).

  10. Look at line 45 in the implementation file. Notice the pattern of [[ClassName alloc] initWithParameters: param1]; …this is, not surprisingly, a constructor call. Classes can have multiple constructors, all of which must return the newly created object. The return type must be specified in the constructor definition (as for any method), but you’ll often notice that iOS classes will define the type as (id). (id) is a generic pointer to an object, meaning that the constructor can return any kind of object – this enables constructors to be reused in subclasses and is probably a pretty good habit.

  11. You’ll also have noticed, by now, that you’re dealing with C style pointers. Of course, that means you’re also dealing with memory management. Yes, I thought those days were in my past as well. In newer versions of iOS, a system called ARC deals with it for you. I won’t comment on that since I’m developing on an older machine for older versions of iOS right now, but I’ll forward you to a good discussion of ARC. Regardless, it’s probably wise to understand how previous versions handled it, which is basically reference counting. Any time you create a reference to an object (take a look at the NARC rule), you’re incrementing the reference count and if you don’t free that memory when you’re done with it, you’re leaking memory (ie, get ready to crash). Freeing the memory is accomplished with a statement like the one on line 235:
    [variableName release];

  12. While we’re on the topic, there’s a variation on release: [variableName autorelease]. This is used in circumstances where you’d like to mark a variable as no longer having references in a code block where it’s created, but allow a reference to be created elsewhere (ie, a calling method). Thoughtful readers who have looked around the source a bit will have noticed that some methods return objects but don’t require us to release them ([NSString stringWithFormat: @"..."] comes to mind) – that’s because those methods are autoreleasing. There’s an excellent write-up of when to use autorelease here.

  13. @”String”? Odd, isn’t it? The @”" syntax creates an instance of NSString rather than a character pointer. Note the class name. You’ll see a lot of NS* classes, which are derived from the old NextStep system from which Cocoa was born. You’ll also see class names beginning with CF* and CG*, representing Core Foundation and Core Graphics, respectively. For an interesting list of class name prefixes, check this out.

  14. Often, you’ll find you’d like to pass around a reference to something. If you’d like to pass a reference to a method, you’ll do it with the @selector(methodName:) expression. Note that while you’re not articulating the parameters of the method, the method’s full name does include the colon separated identifiers used to compose it. EG, for our example above, we could reference it like this: @selector(doSomething:withInput:). Look at line 45 of the implementation file for an example. Variables might need to be passed by reference as well – for this, there’s the “take the address of” operator: the ampersand. Say I’ve got a function that expects an integer pointer: – (void) doSomethingInt: (int*) something… if I have a regular old integer that I’d like to pass in, I’d better convert it to a pointer:
    [self doSomethingInt: &realInt];

At this point, you’ve got enough to feel fairly comfortable in Objective C – you’re just starting down the road to real skill, but you’ve got enough of a roadmap that you shouldn’t have a hard time tackling whatever comes your way. What’s missing here is a discussion of actual iOS UI programming using Cocoa Touch – stay tuned for part two where I’ll cover that.

Code is about 8.5% of our pie. You?

June 21st, 2011 by acw

The title is borrowed from this guest post I wrote for the blog over at Call Tracking Metrics, a product I’ve been helping build over the last few months that provides analytics for your business’ inbound calls and helps you to optimize your marketing spend. The post is about how startups must be mindful of the tendency to overemphasize technological progress to the detriment of sales and marketing efforts. It’s general consensus that good ideas often fail due to poor execution, and, in my observations of the startup scene, an imbalance in these areas is one of the more common ways execution fails.

Which Projects to Rely On: the Open Source Lifecycle

February 7th, 2011 by acw

Earlier today I got to thinking about how Rails has changed from version two to version three, which lead me to thinking about both the lifecycle of open source projects and, in particular, how they are affected by peer projects and competition. The initial thought that lead to this was: when choosing a piece of software to solve problem X, most people will avoid any solution that isn’t actively under development, which puts a lot of pressure on a project and can lead to poor choices. So what exactly are the competitive pressures that most open source projects face? In thinking about this, I tried to describe the general lifecycle of a successful open source project as viewed by the external user who isn’t contributing to a project but rather trying to figure out which project to use. What I came up with can be summarized by four phases: competition to be a contender; competition to be the best; competition to stay the best; and getting beaten by the competition. Read on for more depth:

Problem/Innovation

Through whatever means, attention is called to a problem or an idea is sparked and something new gets implemented.This is followed, generally, by the emergence of several alternative solutions or implementations. For the user who is attempting to use the technology to solve another problem, this stage is characterized by uncertainties about which solution is best and most likely to become dominant, thereby becoming actively developed and maintained. Choosing the wrong project at this stage can mean that you’re forced to reevaluate your decision after wasting time incorporating it into your own work. For the project, this stage is about competing to become a recognized contender.

At the time I write this, a decent example of a problem space where this is occurring is that of web frameworks for the Erlang language. Although Erlang itself has been around for quite some time, broad interest in using it for web applications is relatively new. There are many approaches, some taking advantage of Erlang’s natural concurrency, others attempting to mimic the MVC frameworks of other languages. However, at a conceptual level, the future of what it means to write Erlang web apps remains uncertain.

Convergence

At this stage, the extant offerings have become more stable and carved out their niches, leaving the user base to naturally gravitate towards what is best based on whatever criteria matter most (and leaving those offerings that have focused on the wrong criteria in the dust). Having bested some of the competition, the leading projects gather momentum and begin to assimilate the desirable features of the also-rans. The lead projects are now name-brands and correct feature selection is important for maintaining a lead and ultimately cornering the market. For the end user, choice is much easier to make here and not as dangerous given that overlap between leaders in the problem space makes switching implementations much easier than before and gaining this kind of visibility usually translates to some amount of longevity. For the project, this stage is about competing to be the best while avoiding introduction of issues (such as technical debt) that will sabotage the project in the future. Note that if many projects successfully compete at this stage for a long time, niches will develop.

The convergence stage is the one most like a continuum, so examples can look very different depending on their progression within the stage. However, an example of a problem space where convergence seems to be occurring right now (though closer to maturity than not) is open source content management. There are hundreds of CMS offerings out there, but a handful like Drupal, Joomla! and WordPress (considered as a CMS, not a blogging platform, where it is almost certainly in the maturity stage) that are cornering the market. None of these is a de facto answer at the moment, but all are solid choices for a user who wants a CMS. None of them will disappear any time soon, and they are all feature-rich.

Maturity

This is the stage that every project wants to reach, but it is not inherently stable. While the leading project has become the de facto solution to the problem in question, competitors whose attention had previously been focused on multiple projects now have the leader squarely in their crosshairs. At this stage, there is enormous pressure to continue innovating, developing and refining. How the project’s developers respond dictates whether useless cruft begins to infect the code base or whether the project’s hard won success is maintained. The project’s main competitive drive at this point is about staying on top. For the potential user, the decision in this case is extremely simple – use something else only if you’ve got information unavailable to the rest of the user base which convincingly shows that the leader will soon be replaced.

The linux kernel itself is an excellent example of mature open source. While there are powerful alternatives like the *BSD family, linux is the first thing most people think of when the term “open source operating system” comes up and will likely continue to dominate for years to come. Linux’s continued success is due to many things, but the leadership behind the kernel project is a significant reason to believe that sustainable choices will continue to be made. Additionally, the separation of the kernel from other elements of the operating environment has allowed the kernel to remain popular while distributions go through their own lifecycles. Fundamentally, this stage is about using your advantage to stack the deck in your favor and linux is doing that very well.

Atrophy

Atrophy is caused by a variety of things, from abandonment to poor feature selection to the surprise appearance of a superior project. Regardless of how it is caused, atrophy means a project is surpassed by its competition. It’s difficult to select an example here because many projects atrophy after garnering their share of adherents who are quick to defend its honor in the face of any claim about its worth. By way of disclaimer, let me point out that while saying X is in the atrophy stage is a major value judgment about X’s utility, it is not saying that X is useless. So while a project may nevertheless still have plenty to offer, it may be objectively not popular enough to choose or too locked into an old way of doing things. It’s less dangerous to make an error in judgment here, where the project has already matured and is stable, than in choosing incorrectly (or too soon) during the problem/innovation stage. The major drawbacks to choosing poorly relate to lack of access to the newest developments and the potential difficulty of finding people who are experts in an aging technology.

Hopefully I won’t alienate too many people by choosing CVS as my example for atrophy. While CVS was the de facto version control system when I began writing code, it has long since been eclipsed by newer solutions to the problem, such as DVCSes like git and mercurial. CVS in and of itself is not bad software and could be safely used for a production product today, but the fact of the matter is that better alternatives are available and it wouldn’t be the wisest choice today.

Outliers

While counterexamples can be found (probably) in any large category of open source, programming languages have a few good ones offhand. Consider that Ruby wasn’t really on most peoples’ maps prior to rails, and that Paul Graham’s success with lisp has fueled a resurgence of interest and respect for what was once considered mostly an AI language. There are numerous other examples of projects/packages that have suddenly burst onto the collective radar outside of the path I’ve described. However, the two outliers I’ve mentioned are indicative of a path that many such projects take: they regain traction as the result of something that uses them, demonstrating their power, that follows a path much more like that described above. (In some ways, this is similar to linux’s continued popularity due to new distributions). In this sense, many outliers are exceptions that prove the rule. Of course, there are also plenty that follow paths that are wildly divergent and have nothing to do with the lifecycle I’ve described.

Epilogue

Before writing out my own ideas, I thought it would be a good idea to see what others think about the subject. The two most relevant links I found are Chad Myers’ Los Techies blog and Brandon Nuttall’s M.S. C.S. thesis from Vanderbilt. Nuttall’s thesis is a very interesting body of work, exploring topics such as why traditional software development methodologies don’t fit open source (and why more recent models like test driven development are a much better fit) as well as the role of bug characterization as one of the major facets of the OSS process. Ultimately, focusing on open source development as a defect centric process lends his thesis to a lower-level more-detailed approach (i.e., he takes the perspective of a contributor versus a user) than what I’ve talked about, but I recommend it as an excellent description of the ecosystem of an open source project. Myers’ post, on the other hand, is a much higher-level view of the lifecycle of an open source project, but it doesn’t really talk about the implications of the various phases and doesn’t address the fact that projects and their phases are dramatically impacted by other projects. What I’ve written here is an even higher level approach than Myers’ and one that is far more focused on the interplay of a project in the greater macrocosm of a problem space.

You can discuss this on Hacker News.

Rails Single Table Inheritance and Polymorphic Associations: Some simple examples

February 1st, 2011 by acw

Getting back to coding after a long hiatus means an opportunity to reexamine things you haven’t seen in quite some time. As I was poking around refamiliarizing myself with rails’ single table inheritance and polymorphic associations, it seemed pretty apparent that there’s a lot of confusion out there about both how these things work and when to use them. I thought it might be useful to explain how I think about the subject, along with a few typical use cases:

1) Single Table Inheritance and Users

A large number of web apps have more than one type of user, such as admins and regular users. You could implement a model/class for each type of user, but reimplementing things like User.sign_on for each class of user isn’t very clean. So you’ll need to create a subclass of User for each of these types, and stick the shared behaviour in the User superclass. If you were to try doing this without using STI, you would run up against some hurdles: Ruby supports only single inheritance, and ActiveRecord uses the class where it is inherited to determine the appropriate table name. While these are certainly not insurmountable, and it’s not that difficult to code around them, making inheritance relationships like this is common enough that we shouldn’t have to repeat a solution: STI to the rescue!

STI is beyond simple to get up and running. All you need to do is add a type:string column to your superclass model. The subclasses don’t get their own table, just rows in the superclass’ table with :type filled in to indicate that they belong to the given subclass. Once set up, you can use the subclasses in associations and ActiveRecord will do the right thing:

class User < ActiveRecord::Base
belongs_to :something
end

class Admin < User
end

class Regular < User
end

class Something
has_many :admins
end

# Let's create a few instances of the subclasses
x = Admin.create!
y = Regular.create!
x.something = Something.create!
y.something = x.something
x.save!
y.save!
# So now there are two User rows relating to Something, but only one is actually an admin, so:
Something.find(1).admins -> [<Admin ...>]
# Something.find(1).users -> Exception... no relationship
# And even if we go through the user model, we get the right thing:
User.find 1 -> <Admin ...>
# We can get all admins without any extra hoops
Admin.all -> [<Admin ...>]

Note that if you’re using the generator to build your subclass models, you should get rid of the migrations that get created. If you don’t you’ll have blank tables created next time you run rake db:migrate, which sounds awfully like the beginning of a problem.

2) Polymorphic associations and Liking/Favoriting

Let’s say you’ve decided that you want users to be able to “favorite” other objects in your app. The inefficient way to do this would be to have a favorite_X table for each type of object X that should be favorite-able. That’s obviously not a very DRY way of approaching things. Instead, it’s better to have a single table that can reach out to all of these other types.

t.references :yzx, :polymorphic => true

The above line in a migration creates exactly the columns needed for doing that – a type and an ID column that can be used to associate with other types of objects. Technically, it created yzx_id and yzx_type based on the symbol passed to t.references, which will allow you (eventually) to access the related object by saying something like: user.favorites[0].yzx.

In order to get that magic x association tacked onto your Favorite objects, all you need to do now is add:

belongs_to :yzx, :polymorphic => true

to your model, and you’re good to go.

That’s the heart of the belongs_to end of a polymorphic association. For Favoriting, that’s really all you need. In other circumstances, however, you’ll need the relationship to allow you to traverse backwards. Doing so is, again, very simple:

has_many :favorites, :as => :yzx # where x is the polymorphic relation name

3) So how do these things work internally?

Both STI and Polymorphic associations could be implemented yourself without too much effort. The only ‘trick’ necessary is the Kernel.const_get method, which allows you to dynamically reference a class by name. For STI, accessing a superclass instance that contains a type column results in instantiation of a subclass instance with all the column data from the superclass instance, including the id. Although it’s not really the same, you can think of it like this:

# the following call
User.find 1 -> <Admin ...>
# would result in something like this:
x=User.find 1
k=Kernel.const_get(x.type)
return k.new.copy_instance_variables_from(x)

While for Polymorphic relationships, accessing an element of an association would result in something like this:

# access the element:
user_var.favorites[0].x -> <Link ...>
# resulting in, roughly
return Kernel.const_get(x.type).find(x.id)

Bear in mind that this is just a way to think about how they work, not an actual guide for implementing alternatives. If you’re really curious about the implementation, I refer you to the ActiveRecord source code!

4) So when should I use STI? Polymorphic associations?

There are some pretty apparent similarities between the two techniques: both allow you to build associations that dynamically determine the type of a referenced object. The major differences are that STI allows you to inherit functionality, while polymorphism allows you to make associations with objects without knowing their type ahead of time. So, generally, STI should be used when there’s an obvious inheritance relationship (IE, a true superclass) and polymorphism should be used when it’s important to be able to defer determination of object types ’til runtime.

The difference of functionality is pretty obvious (either you’re bringing functionality into a subclass or you aren’t), but it’s worth taking a moment to elaborate on the point of determining object types. A good way to look at this is through accessing elements of the association. In an STI relationship as outlined above, you would access the admin users like so:

related_obj.admins

Whereas in a polymorphic relationship, you would say something like:

map {|x| x.favorable } user.favorites

The objects return from the second line of code could be anything… Favorited Posts, Comments, Pictures, etc. and we won’t know what we’ve got ’til we’re actually holding it. Note that this array of polymorphic associations requires us to go through an intermediary step, which gives us a spot to add additional data to the association, if we want to.

For me, it boils down to: if you’ve got two models that should have act like a third model, but have their own functionality as well, use STI; if you’re trying to do something where you’re not going to know what kind of object you’re handling ahead of time, use polymorphism.

Becoming an educated legal consumer (a guide for founders)

January 16th, 2011 by acw

First, I am not a lawyer and this isn’t legal advice.
TL;DR: You can be a better consumer of legal services by reading law school outlines. Links to a bunch of them at the end.

Legal fees are one of the largest component costs of launching a startup, but how educated is the average founder about the service he/she is getting? Stories of legal quicksand abound, from people failing to check their prior employment agreements (potentially entitled a past employer to your IP) to missing out on 83(b) elections (your shares are then taxed at a much higher rate) and everything in between. The lesson here is twofold: the adage that the person who represents himself has a fool for a client is, generally, true; and you shouldn’t just assume that you’re in the clear because an attorney has prepared X document for you – mistakes are made all the time. Get a good attorney and double check their work!

So how can you learn a little about the law in order to be a better educated consumer? There are plenty of commercial resources out there, such as Nolo guides, but one thing many people aren’t aware of are the repositories of class outlines that law students publish every year. As with legal services themselves, there are plenty of issues to be aware of when using outlines, but they can be enormously helpful as a way to develop questions to ask your attorney and as a tool for spotting issues in work that has already been done. You should be aware that many outlines are a few years old – schools often won’t allow their student bar association (who usually distributes such outlines) to publish the latest outlines due to the (probably accurate) belief that it would encourage people to slack off. Some areas, such as tax, change frequently, so try to get something up to date; on the other hand, the common law of contracts isn’t exactly going to rewrite itself overnight. Also, you have no idea who wrote the outline – there’s not a lot of quality control out there, so my advice would be to look at a few outlines from different people/schools. Be aware that almost all of the relevant material taught in an ABA accredited law school will be focused on state common law that is widely accepted or federal law (eg, corporations classes often discuss Delaware laws for obvious reasons). The nuances of the Washington state incorporation statute will not be on an outline from Stanford Law. Note that if for some reason you’re trying to launch in Louisiana, you’re somewhat on your own on any issue that’s not federally legislated – LA is the only state in the Union whose laws come from a civil code.

So what outlines are relevant? What follows is certainly not an exhaustive list, but it should cover a lot of the more common issues.

Contracts – It should be obvious, but if you’re going to be in business, you’re going to be interacting with contract law. Note that some kinds of contracts are governed by additional regulations that may supersede the principles in a basic contracts class. For instance, a contract to buy shares of a company is very much still a contract, but it would be governed by securities laws as well.

Corporations – This class covers some of the issues involved in formation of a business, the liability of founders for business acts, and the powers of board members, among other things. Depending on the course, it may or may not involve some discussion of other business forms such as partnerships (which is what you’ve got amongst the founders ’til you incorporate… usually).

Securities Regulation – Covered here are issues such as what constitutes a security, the rules surrounding the sale (be it private or IPO) of securities such as registration and duties to purchasers, the exemptions that allow you to sell securities without registration, and what happens when you screw up. This is a pretty specialized area of the law, and should warrant a careful look.

Tax – The Internal Revenue Code is a massively complex animal, with regular changes based on the political process. Tax is also a hugely important factor in doing what you want to do – make money on your venture. You will be faced with issues of personal income taxation and those of corporate taxation at every period in your business’ life. There are multiple classes in this area and you may want to start with the outline for Federal Income Tax (which is a worthwhile read for anybody who pays taxes!) as a way to ground further reading (it’s usually a pre-req for other tax courses like Corporate Taxation).

Intellectual Property – Again, a wide field without a specific class (though some schools offer survey courses). Covering areas such as ownership of inventions via patent law, ownership of creative works through copyright, unfair competition via antitrust law (which may seem unrelated, but the purpose of antitrust is the same as other areas of IP – to clear the path for innovation), etc. The majority of issues facing tech startups are probably within the ambit of patent law, so that’s the first thing you should read.

Employment Law – Another wide area. Restrictive covenants that govern a founders’ duties to prior employers are a big issue that can come up. Hiring and firing are also big issues that are governed by employment law. The applicable content in an employment law outline will likely be pretty small, however, given that unrelated things like OSHA are often a large part of the course.

Venture Capital – If you can find an outline for a course like this, you’re in luck. It’s essentially a survey of many issues that founders face, and is a fantastic and very relevant read. The mixture will include a little of all of the above, and it’s a great way to cement your understanding after you’ve worked through some of those outlines. In order to find one of these, you may have to go through one of the for-pay outline banks out there. I haven’t seen it available anywhere else.

Civil Procedure – This, like Contracts, is a required first-year course. Civil procedure is the body of law governing how civil suits are commenced and resolved, including issues like where you can bring suit, motion practice including things like requests for summary judgement, and whether federal or state law applies. In short, this is an area of law you shouldn’t really have to interact with unless Something Really Bad has happened and you’re going to court.

So where can you find this stuff? As mentioned above, the student bar association at many law schools makes outlines available to students. Many schools keep this stuff private, but several are kind enough to allow public access. The links below should be more than enough. Happy reading!

George Washington University Law School – This is my soon to be Alma-mater. Excellent IP program, so a good resource for patent issues.

UC Berkeley Boalt Hall School of Law – Another top IP program. Their outline bank has a survey IP course which is probably a good idea to read.

UC Hastings College of the Law – For some odd reason, Hastings offers their outline bank only in the form of a zip file.

American University Washington College of Law

University of Virginia School of Law

University of Mississippi School of Law – Ole Miss’ outline bank appears to be pretty small, but here for completeness.

University of Maryland School of Law

University of San Francisco School of Law

Vanderbilt University Law School

University of Wisconsin Law School

University of Pennsylvania Law School

UC Davis School of Law

The Internet Legal Research Group – A general collection of outlines that is a decent resource, but usually not as fresh as an outline bank run by students.

OutlineDepot – Some bright law student realized that getting outline authors some cash for their work would incentivize sharing of the most up to date and hard to find info (and make some bank). This can be a good resource for hard to locate stuff like Venture Capital outlines. Well organized also.

There you have it! Whether you only use a single outline to scan over an attorney’s work or you read all the stuff I’ve talked about, you’re at least more informed than the average legal consumer. Good luck!

You can discuss this on Hacker News.

Our First Pivot

January 7th, 2011 by acw

Like anyone trying to launch a startup, I practice regular environmental scanning to determine who my competitors are, what they’re up to, and look for changes in the market. The company I’m working on is basically a new mousetrap for an existing and poorly solved problem. It’s also a problem space that has seen a ton of investment and activity in the last two years, so there is no shortage of contenders. Our approach is pretty different from what’s out there and the direction of most new entrants, so usually an environmental scan doesn’t get my heart racing too much.

Not so one day earlier this week – I found a random thread asking about new industry players from a potential customer. Most of the answers included companies I’d already taken a look at, but halfway down the page I saw a name I hadn’t seen. After poking around their site, I was dumbfounded. Someone had beat us to it – their approach is eerily similar, except they solve a critical element of the problem in a way that is undoubtedly better than what we had at that moment. And they have funding. And they’ve got a team with major successes under their belts. And…

When I finally got a chance to discuss this with my cofounder, his reaction was far more even keeled. “Let’s just keep pushing. At the very least, we can release it and see where it goes.” Exactly the right thing to say. I think this reveals why having more than one founder is so critical: would I have decided to keep on going? Almost certainly, but it’s a lot more difficult to keep focused on a goal when it’s just you by your lonesome fighting against a feeling of being overwhelmed. Saying “Yeah, you’re right” and feeling accountable for continuing is a short cut around wasting time arguing with yourself about it. The popular image of entrepreneurs as doggedly determined to translate a vision into a reality is true in principle, but no matter how much faith you’ve got in your idea, there will be times when you’re shaken.

In the end, I wound up absent mindedly thinking about the problem before sleep a few days later and hitting upon a simple, quick way to radically change our value proposition. It’s enough to differentiate us from our soon-to-be former doppelganger, and adds some pretty cool stuff for our users. It basically bolts onto what we already had, so nothing gets wasted. Whether it’s enough to give us an edge in the end, we’ll have to see, but it’s certainly a big step in the right direction.

So what’s the point of all this? Well, first and foremost, don’t give up. I think the terrifying experience of uncovering your evil twin is probably the rule, not the exception. Regardless, you will have moments that make you think what you’re doing isn’t worth it. That’s wrong – it is. Don’t be afraid to launch and see what happens, even if it seems like someone already does what you do. You don’t know what their situation is… perhaps the founders are bickering and they’re going to disband tomorrow, leaving you a clear path to a home run. Stranger things have happened. And second, have someone there to help you through these struggles. It’s probably easier if it’s a cofounder intimately aware of your business, but it doesn’t matter as long as there’s someone you’ll listen to who can keep your eyes on the prize. And don’t forget to thank them for it when that project you almost gave up on turns out to be a winner.

You can discuss this on Hacker News.

An Erlang quine

December 21st, 2010 by acw

I’m playing around with Erlang for a new project and did a little self-replicating program to get a little more familiar with the language. I went through several iterations, shortening it each time. I’m sure there are probably ways to shorten it further, but I had other stuff to do, so maybe later. However, if you notice anything that I inadvertently missed, feel free to point it out. Here’s the code:

%% A First Erlang Program: Erlang quine
%% by Alex Westholm
-module(quine).
-export([quine/0]).

quine() ->
  Code =
[<<"%% A First Erlang Program: Erlang quine\n%% by Alex Westholm\n-module(quine).\n-export([quine/0]).\n\nquine() ->\n\tCode = \n">>,
 <<"\t[Top | [Bottom]] = Code,\n\tio:format(\"~s~p,\\n~s\",[Top, Code, Bottom]).\n">>],
  [Top | [Bottom]] = Code,
  io:format("~s~p,\n~s",[Top, Code, Bottom]).

Productivity and display size: Are netbooks the answer?

December 15th, 2010 by acw

Many people have spent many hours looking for the optimal developer setup. The prevailing wisdom at this point seems to be that greater screen real estate (read: dual monitors) can dramatically boost productivity. I’d like to offer a counter-example.

My primary development machine is an HP Mini running Ubuntu Netbook Edition. Not exactly the sexiest setup, and certainly not one that I would have chosen if I’d had options. But I didn’t – I’m a broke graduate student who needed the cheapest possible solution after my previous machine failed two weeks before finals. Approximately $250 later, I was up and running with a tiny, but workable Ubuntu system.

I expected this to be a stopgap measure while I saved up to get a decent system, but much to my surprise, I found myself really liking my new machine. Contrary to conventional thought, the tiny screen resolution seems to have boosted my productivity. Looking back on various other setups that have worked well for me, a common thread seems to emerge: simplicity limits distraction. In other words, the minimal resolution of a netbook functions like horse blinders – sure, I can switch windows and slack off on facebook if I like, but it’s not there in the background tempting me.

This seems pretty intuitive: writing code is a task that requires full focus. In pursuit of focus, some people go to the lengths of editing their hosts file to prevent access to various sites, others break down their work time according to various formulae intended to provide a period of intense concentration followed by a break. Yet the trend in display size seems opposed to this theme of productivity enhancing asceticism. For a field like graphic design, greater screen real estate seems an obvious choice, but why do we need it for coding? (That point discussed at length here).

What’s your approach to display size and how does it work for you?

What about business savvy tech co-founders?

October 26th, 2010 by acw

The issue of business guys looking for technical co-founders frequently comes up on the startup forums. The general response is, “Why don’t you learn to code? You’ll be more valuable, you’ll understand the idea better, you’ll be better able to vet any technical co-founder you come across, and, most importantly, it’ll test your resolve to execute on the idea.” I’d tend to agree that, in most circumstances, a business guy with a little bit of a tech background is only a good thing. So if we accept all of these points as valid, it should be pretty evident that counterpoints could be made in favor of tech guys learning some business fundamentals.

Anecdotally, the number of posts on such forums that concern basic issues of business strategy and startup finance would suggest that there’s some self-awareness of this, and that tech guys are actually practicing what they preach. In fact, I’d wager that there are more people within this community who self-identify as being on the technical end of the spectrum who posses a basic understanding of the impact of valuation on financing than self-identified business guys who can write basic SQL queries. If you assume this is correct, there are endless potential explanations for the phenomenon. Personally, I might chalk it up to the prominence of autodidactic learning within the tech community, or maybe it’s the fact that lots of business concepts can be understood without a great deal of prior learning (in contrast to many tech concepts that require understanding of substantial conceptual prerequisites).

So, do you agree? If you consider yourself a business-savvy tech guy, how did you get there? How much of your knowledge has come from experience and how much from proactive knowledge acquisition?

Note: For full disclosure, I would consider myself to straddle the spectrum. I’m a formally educated business guy (almost done with a JD/MBA), who has been at the technical end of a number of startups, having written code professionally for about 11 years. These days I’m working on a project where I do both.