Falsiness and Null Objects

Posted on June 1st, 2011 by | 2 Comments »

Recently, I went to RailsConf. I saw a bunch of talks and met some cool people. This is not a RailsConf post-mortem post (if you’re interested, though, I’ve collected some notes from myself and some others here). This post is about what, in retrospect, was probably the best talk I went to (and I went to several really awesome talks). I’ve been mulling over it since I got back, basically, and that seems like a good result from a talk. That talk was Avdi Grimm‘s Confident Code (slides, my notes).

One thing in particular sort of caught at the edge of my thought patterns: The Null Object Pattern. I don’t have a CS degree and so I’m missing a lot of the formal training about design patterns that many programmers have (and, probably, forget), so I’d never heard of it. When Avdi started talking about how ActiveRecord’s try method is a code smell, I was like, “Yes!” I would not say that I hate it, but I have seen several times some line of code that looks like this:

1
@user.try(:posts).try(:recent).try(:first)

I mean… bleh. But I didn’t know a way that looked any better to me, really. Anyway, you can look at the notes and slides to learn about what Avdi says about the Null Object Pattern. I thought it was awesome and so when I went home, I decided to take it for a test drive.

The Test Course

So in a project at work, we have Users and they may or may not have one Subscription. Hopefully, you can picture this complex object graph. Subscriptions may or may not be “current” based on various business rules mostly to do with whether you paid us or not. So, naturally, we have a Subscrption#current? method. But we’re using the User as a sort of presenter for Subscriptions. So you don’t want to call @user.subscription.current?. That’s a code smell. So on User we had this method:

1
2
3
def current?
  subscription.try(:current?)
end

There’s that rascal try. “This,” I thought, “is a perfect spot for that Maybe method from Avdi’s talk.” So I rewrote it thusly:

1
2
3
def current?
  Maybe(subscription).current?
end

W00t, right? Wrong. The accompanying NullObject class looks like this:

1
2
3
4
5
6
7
8
9
class NullObject
  def method_missing(*args, &block)
    self
  end
 
  def nil?
    true
  end
end

That method missing treatment, so handy in avoiding the chain of trys in my first example, is the gotcha. It means that if I have a User without a Subscription for whatever reason, calling User#current? returns an instance of NullObject, which will pass, say, the boolean clause of an if statement.

So, not sure as to whether I’d misunderstood something, was making some dumb mistake or what, I emailed Avdi. He said, basically, “Awesome question. I will answer it in a blog post.” And, lo, he did. Go read that post to see what he said. The comments also have some good ideas.

Noodles

If you read my comment, I said I was going to noodle on stuff and post again. I had more thoughts than it seemed like would fit in a blog comment. Hence this post. So my initial thought was disappointment. It turned out the Null Object Pattern wasn’t as powerful (in Ruby) as I’d hoped, since if you might have something (calling Maybe) the chances that you’ll have some conditional asking a boolean business-rule question about it is not low.

So I thought about how to get around that. You could, for instance, make a more complex method_missing definition that grepped the message name for /\?$/ and returned false. That’s fail, though. It falls down the moment you have something like this:

1
2
3
if Maybe(@posts).empty?
  # Intuitively, you'd expect NullObject#empty? to have put you in here.
end

But then I realized that Avdi was making a higher-level point: since it is not possible to make your own objects look falsey in Ruby, you have to have another solution. Trying to define various question-mark methods on NullObject is trying to untie the knot, but I should be looking for a way to cut it. So it got me thinking: Why the hell to I have Users without Subscriptions, anyway? Shouldn’t User#current? express that business logic clearly, rather than just express the logic that enforces it? Yes. Yes, it should.

We have some Users who are also admins, who have special rights. It’s also conceivable that we could give away a free account for whatever reason. So, really, we want something like this:

1
2
3
def current?
  self.free_account? || subscription.current?
end

But, this thought it incomplete. It expresses the business logic cleanly: The User is current if they’re flagged as free or if their Subscription is up to date. However, if the weird case of a User who is neither free nor has an associated Subscription crops up, we still have to hunt down the “Undefined method ‘current?’ for nil” error. It sort of has be reaching for Maybe again.

Or maybe (heh, you see what I did there) I want to steal another trick from Avdi’s presentation and have User#subscription return :no_subscription_defined_for_user so that the error message makes some more sense. I don’t like redefining ActiveRecord‘s default accessor methods, though, to transparently return the symbol if the real object is missing.

If you’ve got any thoughts, I’d love to hear them.

Efficiency in Algorithms Everywhere

Posted on March 2nd, 2010 by | No Comments »

I have heard UI folks talk a lot about how everything has a UI. Doors have a UI, you know? If there’s a horizontal bar, it’s clear that you’re supposed to push. If there’s a vertical bar, that invites you to pull. It’s a poor UI if you walk up and the door looks like it wants you to pull, but, in fact, requires you to push. I’ve been seeing UIs everywhere since I first heard this idea.

I realized just the other day that I also look for efficient algorithms everywhere. I think I may have been doing it for years and just not realized it. Maybe other people do this, too, but I’ve never heard anyone say it out loud in quite this way. Maybe I’m insane or OCD. I’m just going to present some that catch my eye frequently (or have recently, anyway) and rant about them. How’s that for a thesis?

The Cash Register

I often buy things at stores. Most of my transactions are via credit card. Especially when I’m buying, say, lunch, the transaction is so small that the store doesn’t ask me for my signature (let alone ID). So after placing my order, the employee tells me the total and I hand over my card. They then swipe it and stand there while we both wait for the receipt to print out and the register to see that the transaction went through. Then I get handed back a receipt (maybe with an order number) and card at the same time. I have to keep the receipt out and put the card back in my wallet. I may also have to carry away a cup to be filled with soda.

Frequently as I’m handed my receipt and card at once I’m told, “ThankyouforcomingtoRestauranthaveaniceday?” in a big rush and then glared at because it takes me a second to put my card away, pick up my receipt and cup and move along. If time is such a big deal (and during a lunch rush, let us understand that it is) that you’ll glare at a paying customer over it, perhaps an ounce of algorithmic analysis should go into minimizing it, no? If, for instance, I was handed the card back immediately, then I could put it away and be done with it before I am handed a receipt and cup. Then I can immediately move and let the next customer up. This increases the number of times the employee has to reach across the register and the number of times I have to reach to meet them, but that action takes much less time than it does for me to operate my wallet or for the credit card machine to get a response from the credit card validation server. It bugs me.

The Bus

Some people seem to think that there are two discreet tasks when boarding the bus: Waiting-in-line-to-pay-and-board and swiping-card-or-paying. This is sort of ridiculous to me. Clearly you can get your money or card out while you wait. In fact, unless you just managed to catch it in time, you probably saw the bus coming a block away or so, which gives you plenty of time to discover that your bus card is not in the pocket of your backpack that you thought it was and frantically search for it before (whew) finding it… all without making several other people wait.

What would be even more speedy, though, would be to be more organized on an even higher level: always keep your bus pass in the same place (infrequent riders, of course, won’t benefit from this). I generally ride by bike when I take the bus, which means I have to load the bike on the front before boarding. It’s not really possible to load it while holding a bus card, but I still manage to have it out and ready by the time I walk around to the front door and pay terminal thing. That’s because it’s always in the same spot in my wallet.

Making Titles For Wrap-Up Sections Sucks

The connection of this post to programming is perhaps tenuous, but hopefully you can see where I’m going. I wish laypeople knew just a little about thinking in this way and applied it to stuff like this. I like to think doing so has made my life easier and I feel like it’s let me be more courteous to those around me.

Also, this was intended to be my February post, but I was trying to come up with another example. In the interest of staying in the habit of posting, though, I’m just going to hit publish and call it done. Feel free to complain about that in the comments.

FYI: My Tastes in Role Playing Games

Posted on October 7th, 2009 by | No Comments »

This is one of those posts bloggers write so that they can repeatedly refer to it later on. I intend this to be a short introduction to role playing (as in nerds at a table with dice, not a couple playing Santa or whatever your kink is) followed by a bit about my tastes and general habits regarding the hobby.

What’s an RPG?

If you want, check out the Wikipedia article on it, but my definition of a role playing game is this: There are some number of players and generally one Game Master (Dungeon Master, Referee, etc. terminology varies). The players and Game Master (GM) are telling a story together. Each player makes a character (a Player Character: PC) and they constitute the main characters of the story. In order to offer some tension for events where chance plays a part in the outcome, the group is generally using a set of rules that uses a randomizing tool (various kinds dice are most popular, but I’ve heard of cards, for instance) to help decide if the characters succeeded or failed at certain tasks. The important thing, here, is this sentence: The players and GM are telling a story together.

The GM is in charge, basically, of running the simulation, as it were. He (please don’t take offense at my use of pronouns, Lady GMs) manages the world, figures out what the various not-protagonist characters (Non-Player Characters: NPCs) are doing, arbitrates the result of any actions taken by the players the outcome of which is not guaranteed, etc. The other thing that the GM does is he plots the stories the group tells together. Plotting for an RPG campaign, however, is significantly different from plotting for a book or movie because the players each control one of the main characters. So the GM ends up getting a general idea of where things are headed, what the major goals of various NPCs are and then how the PCs fit into it all. Then the PCs get in there and muck things up in interesting, fun ways. This collaboration in authorship means (like laying out a web page) letting go of a certain non-trivial amount of control as compared to, say, a novel author.

The Ways of Ben

In my specific group, I’m the GM. I have, right now, three folks playing in the campaign I’m running. In many schools of GM thought, game play from one sitting to the next are strung together to form a “campaign”. The term originates from D&D’s origins in table top war gaming, so it can be a bit of a misnomer as it’s used today. What constitutes “a campaign” varies widely. My definition, which you’re about to read, is not in the majority, but it is how I do things.

In my social circle, a campaign is like a book: It has a beginning, middle and end. There’s some unifying plot that ties it all together. When the plot is done, those characters go away and you read an entirely different story (please ignore Robert Jordan for purposes of this analogy). A lot of people think of a campaign and the game as one and the same. They might be confused or skeptical about the same group of people just putting down one group of characters and making new ones. Campaigns without an end point in mind from the start can last for years and years and they generally increase in power level (trying to out do themselves over and over) to a place where the characters are fighting gods or eating planets or something suitably EPIC. People have fun doing this and that’s great for them, but it’s not for me. It starts to feel like a TV show that’s been running too many seasons in a row (better bring in Henry Winkler and some skis). I like a narrative arc and I like to pick the amount of epicness from the get go and have it be relatively stable. Also, having campaigns with a designed ending lets me change settings and try on a lot of different ideas. Which leads me to my next point.

My system of choice is GURPS. You can follow that link or not, but suffice it to say that it stands for Generic Universal RolePlaying System. It’s basically a toolkit of rules without any setting information (contrast the famous Dungeons & Dragons, which describes the world the game is played in to great detail). The thing I like about this aspect is that you can play a D&D-like fantasy campaign to completion, then play a space opera and then play a police procedural or something. The ability to try out one thing for a while (length of my campaigns varies wildly, so take that with a grain of salt) and then entirely change gears for the next campaign is a big draw for me. As a GM I really enjoy the world-creation aspect and so I’m constantly thinking about what worlds would be fun to play in and what stories would be fun to play out in them; what kind of interesting people might live there. You get the idea. That’s not the only reason I like GURPS, but I don’t want to evangelize too much. Maybe that’s a future post.

Another thing I do that I’ve heard very few people talk about is I’ve got a GM consultant. This is new as of my most recent campaign, but it’s worked out so well, I can’t imagine why I’d stop doing things this way unless the consultant turned into a player. Basically, the friend who introduced me to GURPS moved away and, in order to get his role playing fix, offered to help me hash over things with the world building of the campaign I was thinking of running. I recommend this technique to every GM that can swing it. Having two minds on the task, as long as you work well together, is an incredible boon. Your NPCs will seem more real and your world can afford to be more complex. It’s easier to track more events happening at once and you’re both going to think of cool things that the other wouldn’t have. I feel like it’s been multiplicative rather than additive to the quality of the campaign world.

Most RPG groups make a “party” or other group of characters that more or less always act in concert. They make decisions together and go do things all as a group. Lengthening the parade of unconventionality, that’s not how I do things. If your character is not in the scene, you’re not in the room. For some campaign settings, that means players (especially early on) can spend a non-trivial amount of time in my living room playing Rock Band or whatever instead of role playing. The win is that by containing information, you can, for instance, more easily dole out clues to each of the players and have them piece it together later when they’re all in. This is cool for the players, not for the GM, I should note. The other thing it does is it lets each player get used to his character and how to play him without the noise of other players doing the same thing; to establish a sort of a base line. It takes a while to really figure out how to inhabit a character you’re playing and unlike other kinds of acting, there aren’t really rehearsals.

I’ve implied that there’s a stage, early on, where the characters aren’t spending a lot of time together. This is a symptom of what my GM-consultant and I call the Dann-style Campaign (Dann was the guy that introduced my consultant to GURPS). Dann-style Campaigns are very formulaic, but it is a formula that works very well. There are 3 (less commonly 4) PCs. They don’t know each other at the start of the story and they all have different goals, needs and reasons for doing things. There is some kind of plot or conspiracy or mystery going on and their various goals draw them into being involved in it, which causes them to meet and discover/uncover/solve it together. The entire campaign general centers around a single, well developed location (say a single city). The fact that the characters are strangers and have different goals means they don’t trust each other right off. The fact that they have different (possibly opposed) goals means they want different things to get done or have different priorities for things to get done. Together, those two facts make it not uncommon for a player to say, “Great. You guys go do that, I’ll catch up with you later,” and then go do his own thing.

I hope this makes a bit of sense to the uninitiated. If you’ve read anything by William Gibson, he uses this sort of story telling a lot. There will be several independent stories going on that, in the end, all have to do with each other in some way and come crashing together at some point in the tale. Now, Gibson tends to have things come together in the final act. In a Dann-style campaign, you generally want the PCs to all meet and start collaborating around the half-way point of the first act. “Act”, here, is a vague unit of story-telling, not anything specific, mind.

Or think of a show like Lost, where the characters are strangers at the start and there’s a high level of distrust and paranoia about each other. People spend a fair amount of time doing things on their own. From setting to setting, of course, the level of distrust can be dialed up or down. In Lost, the level of distrust is rather high between some protagonists and there’s a fair amount of alliance shifting as time goes on. In a Dann-style campaign, you wouldn’t have as many PCs as Lost has main characters and so shifting alliances between them would be somewhat tricky to do if you wanted it.

All of this is really in service to the next post I want to write which addresses some ideas I’ve been batting around about how and what to vary up in the Dann-Style formula. It seemed that, before I talked about variations, I should do a kind of an introduction to my style and, then, that an introduction to what an RPG is, etc. seemed appropriate. If you have questions about anything I’ve put here, post a comment and I’ll be happy to answer it. Be warned, I may try to convince you that you should give role playing a try.

Breaking Expectations

Posted on July 31st, 2009 by | No Comments »

Whenever we interact with the world, we use cognitive shortcuts. It’s handy, you know. We make assumptions about our environment so that, if we’ve guessed right, we can respond appropriately to our environment more quickly as it changes. It’s a survival technique.

However, it can sometimes get us into trouble, especially socially. We see someone dressed a certain way or giving some other kind of social cue and we assume other things about them. Most of the time, this works brilliantly; they’re sending those cues on purpose and we’re supposed to interpret them the way that we do. Or they’re not sending those cues on purpose, but they’re identifying with a group and so our reaction is still appropriate.

I have a hard time, sometimes, in social situations. I have had to learn, via careful and intentional observation and memorization, many social conventions that it seems others picked up earlier, easier or more instinctively. So I’m somewhat sensitive, now, to the social cues that others send. Which is to say that I’m more consciously aware of the ones I notice, not that I notice all the little ones; the fact that I have to consciously process them slows me down and I miss many cues because of it.

I struggled, for a long time, with the fact that others often acted as if I understood some cue I’d missed (a reasonable assumption on their part, statistically speaking). And I realized that I was sending as many “normal” social cues as I could in order to fit in (my younger self was less comfortable being a huge nerd than my present self). But this meant that people were under the impression that I conformed to their expectations… I was basically lying to them.

So I set about trying to find some things I could do that would indicate to someone that they’d be best served (assuming their goal was to communicate effectively with me) being fully mentally engaged, rather than on auto-pilot. When i first had this idea, I also had the idea that I was special and different and so more deserving of people’s full attention. I’ve since become a bit more humble in that regard.

I don’t want to get into a whole ton of detail about my personal expectation breaking journey. I want to come to my point, which is this: I wanted to break people’s expectations so that they’d have a “What?” moment and hopefully clue in that something new or uncommon was going on. Instinctively, I knew I shouldn’t go _too_ far off, but it’s not something I realized until recently.

Whether it’s yourself or a product or brand, I think people often want to break expectations. And I feel like people hand out that advice a lot. It’s decent advice, too. However, it’s one thing to wear funny socks or something and another to dress in a gorilla suit every day. Funny socks are different enough that people will look at you oddly, but still feel like they can have a conversation with you. A gorilla suit is so radical that many people will assume they can’t cope to the difference, whether they’re right or wrong.

The analogy that popped into my head when I initially thought of this was a window. If you want people to see you (assuming you’re transparent, like, you know, a window), then you might think that cracks would help. I certainly notice a window with a crack more than one without. But if you apply too much force, you’ll shatter the glass and there will be gaps in the window and jaggey bits that people are afraid to some too near, etc. It’s a much more upsetting experience. I guess my advice on the topic (for those that want it) is this: Break expectations if you like, but apply light pressure so you don’t shatter them.

Version Control Your Computer

Posted on February 12th, 2009 by | No Comments »

I’ve mentioned @carl_youngblood here before. Someone once was trying to buy him something with his name on it. I think it was a key chain. You know the kind, right? However, then didn’t have “Carl” only “Carlos”. So we joked that, one day, he needs to write an operating system and name it CarlOS. Aren’t we funny? I know. I’m sorry. Anyway, the other day, we actually got into some OS discussion that I thought had some interesting enough ideas to post here.

So how many computers do you own and use? I’ve got a desktop at home, a laptop and a machine at work. It’s sort of a bummer to have different stuff or different versions of stuff, or stuff with different preferences on different computers. At least, for me it can really jack up my work flow. Especially if there is some application I use a lot with non-default preferences. Man, that bugs me! Remembering it all, bleh.

One thing Carl’s fantasized about is having a computing environment the same everywhere you go. That’s sort of a mainframe or dumb-workstation idea, which is not new at all. However, what if your whole computer were version controlled? You could branch it (so you don’t have your work apps at home, etc.) and merge changes from one branch to another, if you wanted. You could check out a different branch on one machine and it would feel like you were on another.

Clearly an OS would have to be built from the ground up for this idea. You’d also have to have some kind of provision about storing the non-checked out branches locally. Also cloning the repo would be a hassle at current average (even high speed) connection speeds. But how cool would it be to install, say, Textmate at work and get all your settings right, etc. and then go home and merge that change in (You could merge it from work, I guess and then just pull from home. Whatever.)? You could get diff data (hard to implement, but with metadat not impossible):

$os diff gaming HEAD
+ Steam
+ Half-Life 2
+ X-Fire
- Textmate

Or whatever. You get the idea. Reverting would making backing up and creating, uh… what does Windows call them? Recovery Points? It would make all that easy and moot. Clearly Linus Torvalds needs to be in on this “project”; he has the experience in both OS design and version controlling that would be invaluable. Not that, you know, Carl or I are actually considering doing anything with this idea. It’s an interesting thought experiment, though.