Mansions of cards: Osinki, CDOs, and the role of software
The aim of software is, in a sense, to create an alternative reality. After all, when you use your cell phone, you simply want to push the fewest buttons possible and call, text, purchase, listen, download, e-mail, or browse. The power we all hold in our hands is shocking, yet it’s controlled by a few swipes of a finger. The drive to simplify the user’s contact with the machine has an inherent side effect of disguising the complexity of a given task. Over time, the users of any software are inured to the intricate nature of what they are doing. Also, as the software does more of the “thinking,” the user does less.
From My Manhattan Project: How I helped build the bomb that blew up Wall Street. Highly recommended; the article touches on the ethics of software development, user interface design, complexity, and the classic question of the degree to which a creator may be held responsible for the acts of his or her creation.
It is not Osinski’s fault that his software makes it very easy to perform some otherwise rather difficult algorithms; that is, after all, much of what a computer does. But it does make me wonder that he agreed to work on it understanding full well that the technique was built on entire mansions of cards, and it serves as an ample reminder that our moral compasses are so often attuned only to the values of those around us.
But what, then, is appropriate user design? Should business software be ugly, difficult to use? Should it, like a disassembled watch, expose its innards for all the world to poke and prod at? Must an operation that you suspect your user does not rightly understand always come with a warning label: “Don’t touch unless you really, truly know what you’re doing”? Isn’t that just condescending to your users?
Like everyone else, I’ve used my share of software that I absolutely loathed; software that made simple tasks hard and hard tasks devilishly impossible, their user experience an afterthought, a victim of shrinking budgets and small visions. If there’s anything I’d like to see improved in what you might term the ecosystem of enterprise software, it’s the fact that so much of it is, from a human point of view, really wretched. If you must make people use the stuff, don’t make them dread the experience.
But am I wrong? Should an ugly veneer serve as a reflection of inner ugliness, or of my own lack of understanding? I don’t know how many kinds of Photoshop filters work; should I as their user ask the designers of Photoshop for a poor interface design, so as to force me to pay a psychic penalty for my ignorance?
Of course not. As developers, our eagerness to please our clients and stakeholders is, after all, only human, and anyway, software projects do not have a great track record of success when it comes to satisfying the demands of their procurers. Some projects are wise and some are not; Osinki labored foolishly, although surely if he had not taken up the call some other equally talented developer would have. Agile development, I think, provides us with the tools to build software more rapidly and closer to spec than ever before; so let us then pick our projects wisely.
Posted in Professional | no comments |
Code comments, alias_method_chain, extensions, and the importance of expressing intent
At ThoughtWorks, everyone submits a code sample as part of their interview process. The comment I received from my interviewer about mine struck me, though, and it sticks with me to this day. “The code looks fine,” he said, “but what’s with all the comments?”
My introductory CS course at Northeastern University taught me a lot of things that have resonated in my experience in the industry, but we were taught one thing that, as it turns out, almost none of my colleagues agree with: that all of your methods, classes, and modules should be preceded by a simple, one-line comment that states the purpose of code unit in question. Far be it from me to gainsay Neal Ford, who believes that code comments are a smell, but there are days when I disagree: Even developers with the best intentions and training in the world can’t always write clear code.
A Brief Re-Introduction to Class Re-opening
The problem manifests itself most acutely through the Ruby mechanism of class re-opening (sometimes dismissively referred to as “monkey-patching”). You can go about it in a number of ways, and the codebase I’m working on these days has employed each and every one of them at some point or another. The advantage you gain from being able to reopen classes is that you can patch the framework you’re using unobtrusively in order to fix bugs or improve performance. The downside is that you don’t get to choose the names of the methods you’re overriding: they may make perfect sense in the context of the class you’re overriding, but none whatsoever as an isolated patch.
A reopened class looks something like this:
In the first example, we’ve patched String directly; in the second, class_eval’d it for an added layer of complexity; and finally we’ve defined our own module and added it to String after the fact, which is fact the recommended way of going about it. We can use IRB and the method method to try to figure out where our patch is coming from:
Notice that only the last one gives us a helping hand when we’re trying to figure out where this method was defined.
Overriding, not extending
Now imagine there’s a bug in the String class: a colossally poorly-designed method, something that’s significantly impacting your ability to get something done in the language. (While this doesn’t happen in Ruby very often, it’s like to have occurred at least once in the framework of your choice.) In the bad old days, you’d have had to patch Ruby directly; if you were good about it, you’d submit your patch to Matz, and it’d get integrated as part of some future release. But the language itself gives you an escape valve: override the method, and your implementation gets used.
On my current project, we do this all the time.
But what happens when the framework gets upgraded? Is this extension still necessary? Why did anyone put it there in the first place? What’s with this Subversion check-in comment? Why didn’t anyone say anything in the code?
Enter alias_method_chain
alias_method_chain is a Rails method patched into Ruby that allows you to extend a method without blowing away the old version. You can read Marcel’s post on it on the Rails blog from back in the dawn of time, two years ago, when they added it to the framework. In action, it looks something like this:
Suddenly our extended method has an identity again: it has a name that clearly indicates both the method it’s trying to extend and the feature we’re adding on top of it. Hallelujah!
Why does this matter?
The ability to re-open classes is an insanely powerful tool. I love it, not least because it never means having to write another XUtil (XmlUtil, DateUtil, StringUtil…) class again to make up for the deficiencies of someone else’s API. I could never tell you, in good conscience, not to use it.
But cleaning up becomes a bit of a mess when you have to upgrade frameworks (or language versions, for that matter) as we’ve had to do recently on our project. We carry a copy of Rails around in our vendor directory, like most projects do, but we’ve tried to be good about making our extensions externally, through class re-opening, rather than patching the Rails code directly as men and women did in days of yore. But because, out of habit, none of these extensions carry any comments, we’ve had a devil of a time trying to figure out not what they do (we can always read the code) but why they’re there, and whether we can finally, for the love of God, delete them now that we’re upgrading to Rails 2.2.
But take it from me, one developer to another, who hath had to maintain thine extension, yea, even unto multiple new Rails versions: using the tips above will help me, and those like me, figure out what the dickens you were trying to do. And for Heaven’s sake, when you don’t have the luxury of naming your methods to make it clear what they do or why they’ve changed, leave a quick comment.
Posted in Professional | no comments |
An introduction to mocking and stubbing in Ruby
I gave a presentation on mocking and stubbing in Ruby a couple weeks ago at the Atlanta Ruby Group and the maintainers of the group have been kind enough to put the video online. It’s a large and energetic group and I had a lot of fun presenting, as indeed I always have watching others present there. If you’re new to unit testing in Ruby and you’re wondering what the fuss is about, check it out and let me know what you think at btguthrie@gmail.com. Slides here, or just watch the presentation.
Posted in Professional | no comments |
What the Rails Hosting survey says about the Ruby on Rails community
Some highlights, or anyway things that caught my eye, when I read the 2009 Rails Hosting survey of Ruby on Rails developers:
- Around 60% of the community has been using Ruby and Ruby on Rails for 2 years or more. It’s not yet a mature community, but there is now a reasonably large body of expertise to draw from in solving problems in and around the framework.
- Rails developers on average develop two to five new applications per year, and deploy them several times a week to several times a week.
- Most of these are probably small:
- Generally respondents either self-host or use a small-scale VPS service like Slicehost (which I myself host this blog on; recommended.)
- Respondents claim to be highly sensitive to the price of their hosting provider.
- Most don’t use performance, uptime, or process monitoring.
- It surprised me to see that almost a quarter don’t use any automated deploy process whatsoever, which sounds painful. Furthermore, 5% claimed they were still using FastCGI+Apache. Crazy.
- The community has largely moved over to Git as the SCM of choice, although Github is not widely used as a centralized code repository—only a third claim that their source code is hosted there.
- Passenger has, this year, finally surpassed Mongrel as the rails server of choice.
I see a community that’s still youthful but is starting to mature. I’m still proud to be a Ruby developer, and glad to be a part of the community. Here’s hoping for more good years ahead.
Posted in Professional | no comments |
Announcing the release of ResourceFull 0.7.1
ResourceFull integrates with ActionController to provide a comprehensive RESTful resource modeling and querying framework. It provides parameter queryability, paging, sorting, separation of controller concerns, multiple formats (HTML, XML, JSON), CRUD access permissions, and API metadata surrounding the resource itself. It’s opinionated but is intended to provide you with as much as possible without limiting your ability to customize its behavior.
This plugin was extracted from a series of Rails projects intended to serve as the services tier of a series of loosely-coupled applications built in a style reminiscent of the RADAR architecture.
ResourceFull lives on Github at http://github.com/bguthrie/resource_full/.
GOALS
The major distinguishing features of ResourceFull are:
- Queryability: the ability to designate certain parameters as queryable, and map them to columns and SQL queries in the underlying model. These queries chain together multiple named or unnamed scopes and can be used either for a SQL SELECT or SELECT COUNT. This functionality may be moved into a separate plugin in the future.
- Pagination and orderability: it automatically responds to requests for limit, offset, order_by, and order_dir.
- Implementation: Default implementations for HTML, XML, and JSON controller requests.
- API documentation: ResourceFull-enabled Rails apps are able to provide automatic documentation of the resources they expose, up to a point. (This is enabled in large part by the queryability functionality and other resource-level descriptors.) It’s my hope that this can eventually be consumed by a Rails resource registrar that acts as the single source of record for multiple REST engines within an organization.
EXAMPLE
This allows for the following:
/users/bguthrie.xml
/users?name=Guthrie
/users?email_address=gmail
/users.xml?city=Chicago&name=Brian,Paul,Alicia&order_by=city&order_dir=asc
/users.xml?limit=10&offset=30
/users/bguthrie/addresses
>> UsersController.to_xml
=> "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n ..."
API DOCUMENTATION
To enable ResourceFull to document your resources at /resources.xml and /resources/
Posted in Professional | no comments |
Onewaysweet: a way to track conversations
Onewaystweet is a simple Twitter mashup that helps you track what people are saying about your site, and when. It hashes the URL (using several different URL compression services, or at any rate, the ones that offer idempotent hashes of the given URL) and performs multiple followup Twitter searches so you don’t have to.
Robert Scoble thinks Twitter isn’t for conversations. That may be true, but that don’t mean that people ain’t sayin’ stuff. Pop in a URL, subscribe to the RSS feed, and follow the results. They may surprise you. Then again, they may not, which may also be surprising. Is disappointment a kind of surprise?
Actually, the queries that result in the greatest amount of buzz have certainly surprised me. Obie Fernandez’s minor mea culpa on the Rails Maturity Model generated a lot of controversy and results in (as of the writing of this post) a fair number of hits; the current New York Times headlines story does not. Is Twitter still so tech-centric?
On the technical front, I’m currently deploying it on Heroku, which was almost absurdly simple to do. As advertised: git push and you’re done, though the site doesn’t use a database and I can’t speak to the deployment experience in that regard. The fact that the developer preview is free certainly doesn’t hurt. Their explanation of how it works is sexy but short on gritty details. I’m okay with that, because in my idealized fantasy world deployment is always Somebody’s Else’s Problem. But the bitter Rake hacker in me is convinced that not having SSH access will be a huge pain in the patootie at some point in the future.
Posted in Professional | no comments |
Do unit tests find bugs?
Suggested controversy background reading: Joel hates tests, Uncle Bob is incredulous, Kent Beck is offended, the VP of software development for Justin.tv shoots proudly from the hip, Jay doesn’t see the big deal but blogs about it anyway, and here’s little old me, exxagerating only slightly. Hat tip to every single developer on Twitter.
So, bugs. Do tests find ‘em? Good lord, yes. I don’t know what kind of unit tests you write, but mine find bugs all the time, though not generally until I try to change something ‘twere better left unchanged. I can’t begin to count the number of times a well-placed test has saved my own individual slice of bacon or the collective bacon of my team. Maybe I’m no rock star, but most of your team members won’t be, and a good rock star may well make a bad teammate. A robust test suite is the critical difference between me being enthusiastic about improving my team’s code and being terrified of doing so for fear of breaking something.
And finding bugs isn’t even the best reason to write tests.
- They communicate intent and serve as a living, breathing specification for a codebase that may not have one.
- They allow you to reason about code that hasn’t been written yet.
- They demonstrate how best to utilize what’s already there.
- They bring discipline and coordination to your process.
Two things really brought me around on testing:
- I’ve worked on several large, complicated codebases written in a dynamically-typed high-level language.
- I’ve had several great mentors who’ve demonstrated to my satisfaction the zen-like benefits thereof.
- Every time I have written code without testing it as I go I’ve come to regret the decision, without fail, even on personal, why-bother-testing stuff. I honestly don’t know how you people get a decent night’s sleep.
Stuff can break:
- Tests that once described the behavior of a particular module in a very granular fashion start to inhibit your ability to change evolve code in reasonable ways. Write more robust tests.
- Slow tests can result in a slow build cycle. There are technical solutions for this. (You do continuously integrate, don’t you?)
- 100% code coverage is hard to achieve. Code coverage is a funky measurement and a perfect score is no guarantee that you’re actually perfectly tested. I will also happily acknowledge that striving for it seems to yield diminishing returns. I try to stay above 90%, 95% if I can swing it, but I don’t let not hitting 100% bother me.
- Plus all of the other triumphs and tribulations that go along with maintaining a good test suite, as with any other body of code.
If you’re still undecided, well, it helps to work with someone who’s done it before.
Posted in Professional | no comments |
Ioke mocking, Mocha as exemplar
A little while back I volunteered to work on a mocking framework for Ioke when my friend Carlos suggested it might be helpful. I’m a bit embarrassed that I don’t have more to show for myself after all of my flailing about, but in my defense, it’s been a spare-time sort of a thing. If you’d like to follow my progress you can do so on my Github fork of Ioke.
Building a mocking framework for Ioke has raised a number of interesting questions, which I’ll run through here. If you have any suggestions or questions, I’d love to hear them.
Is full-bore mocking worth it when prototyping makes it so easy to stub?
Ioke is a prototype-based programming language: any object can mimic any other object. You can declare a constant by capitalizing the name of your mock (Foo = Origin mimic) or an “instance” of that constant by lowercasing the reference (someFoo = Foo mimic). Mimicking an object adopts all of its cells, which is to say, its data and behaviors.
if you would like to instantiate an object you need to ensure that the mimic begins life with unique data structures, because if you don’t it will share the same references as its origin. The convention in Ioke as it stands currently is to declare a create method: someFoo = Foo create. That method will often look something like this:
Foo = Origin mimic do(
create = method("Creates a new Foo", self with(objects: [], name: "A name"))
)
The advantage of this approach is that stubbing is trivially easy: you can mimic any object, any time, and replacing the behavior of one of its cells is as simple as redeclaring it:
someFoo = Foo create ;; someFoo objects is now an empty list someFoo objects = set() ;; someFoo objects is now a set someFoo objects = method(...) ;; And so on.
So, why do you need a mocking framework?
Steve Yegge, in his article about what he terms the universal design pattern, praises JavaScript (a similarly prototype-based programming language) for making it so easy to test Java classes. This doesn’t quite get at the whole story; mocking frameworks offer at least three distinct advantages over simply replacing the method call:
- They can set precise expectations in terms of method arity, arguments, and order of invocation, though I confess that I don’t often use the more advanced features of most mocking frameworks.
- They can enforce certain rules about the mockability of particular cells; for example, that you don’t set an expectation on a cell that doesn’t actually exist. I wish I used these features much, much more often than I do.
- They can replace the original cell (method) definition when the test has finished running, which is extremely important if you want to stub out behaviors related to domain models that might be reused in other tests.
All of those seem like things worth having.
Should the existence of macros suggest a different API for mocks?
I started out by following a fairly convention syntax:
foo should receive("bar") with(:qux) andReturn(5)
Ola suggested that I deploy a little macro-foo in support of readability, and that’s the way it stands right now:
foo should receive bar(:qux) andReturn(5)
One could imagine further refinements on the form; if you have any, as always, drop me a line.
This syntax bothers me a bit because it runs so counter to what I’m used to seeing in languages where every argument is eagerly evaluated. In the above example, we expect the cell “bar” to be invoked with an argument of :qux. Now, clearly we don’t actually want to invoke the bar method directly; it doesn’t exist right now, certainly not as a receiver on any object that makes any sense. But what about :qux? What if the above had been written as:
expectedArgument = :qux foo should receive bar(expectedArgument) andReturn(5)
Clearly we need to evaluate the arguments to that method call but leave the call itself alone. Weird? I don’t know. You tell me.
What inspiration can we draw from frameworks in non-prototype languages?
I’ve found that I do my best learning through experience, and so didn’t make a serious attempt to understand the internals of other mocking frameworks; having used them extensively, I figured, I have a pretty good idea of their capabilities, and so dove in unencumbered by reason, research, or even a decent working knowledge of Ioke. It’s been tremendous fun and as usual I’ve gone through my share of pain, but one of the nicest parts has been actually spending time inside Mocha itself after it became clear that I needed a bit of guidance.
It turns out that prototyping doesn’t get you all the way there precisely because there are some features of a mocking framework, as suggested above, that require some deeper thinking about expectations. How do you know if one is satisfied? How do you pick from competing calls with different argument expectations? Multiple or infinitely allowed invocations? Sequenced return values? Block yields? And so forth.
Although there are pieces of it that feel vaguely stitched-together, as though Mocha and Stubba never quite met at the seams, it’s been fun code to read. Mocha’s a good example of a library that does something complex in a reasonably straightforward manner. The methods are brief and readable, and though there’s a bit more indirection than I’d like (what’s the difference between verified? and satisfied? What does it mean to match? or invoke? How do you pick apart three different mock methods in three different places?) I’d happily recommend it to others as a good example of how to pull off some hairy Ruby functionality without writing a whole lot of hairy Ruby code in the process.
What do I mean by that? Here’s the main expects method that gets mixed in to the Object class:
def expects(symbol)
mockery = Mocha::Mockery.instance
mockery.on_stubbing(self, symbol)
method = stubba_method.new(stubba_object, symbol)
mockery.stubba.stub(method)
mocha.expects(symbol, caller)
end
Each one of those lines is pretty dense: it requires a lot of backtracking to understand why it’s there and what it does. But there aren’t many of them, and they can all be explored methodically, and understanding one leads to understanding the next. Much of Mocha is like that: moderately sized, neither opaque in its density or transparent in its verbosity. Nice, I suppose, for my own definition of nice.
I’ve also learned a lot about the framework that I didn’t know before (for example, I didn’t know that it was possible to configure Mocha to warn against or even disallow mocking nonexistent methods) and will bring that knowledge with me to future projects.
But I don’t regret having not read the source first. Trying and failing gave me the context I needed to understand why Mocha made some of the choices it did, even if I don’t agree with all of them, and in the coming days and weeks I’ll be stealing drawing inspiration from most of them. Thanks and kudos, guys.
Posted in Professional | 2 comments |
Refactoring A Strange Codebase
Nat Pryce points out an interesting connection to the Dunning-Kruger effect as applied to other peoples’ code. I’ve been burned by it, and tried to learn a little humility, but would be lying if I said I never do it myself now. It’s hard not to stumble across a particularly pernicious part of some miserable module and not want to curse the cruel curs who put you in this predicament.[1]
But I disagree with Nat that embarking upon a large refactoring in a codebase you’re unfamiliar with is a bad idea. On the contrary, I think it’s a great idea, precisely because in all likelihood you will fail, thoroughly and (to the amusement of your new teammates) spectacularly, and in failing you’ll learn a lot more about the structure of the code than you would have if you’d done nothing but make humble, incremental changes for six months. Also, it’s a great way to build a team rapport with all those developers you just alienated two weeks ago by dumping all over their hard work.
As always, though, try to be good to the people who come after you. In this I differ somewhat with my coworkers; because no codebase is perfect, I think the occasional explanatory comment is a very good idea indeed. The relevant quote comes from John F Woods, although I don’t know the origin: “Always code as if the guy who ends up maintaining your code will be a violent psychopath who knows where you live.”
[1] Too much?
Posted in Professional | no comments |
The Ioke programming language
Ola Bini just released the latest version of his Ioke programming language, Ioke S, and I’m having a blast using it. Late last year I started playing around with Clojure, which is a ridiculously promising language with a compelling feature set that you should absolutely check out if you’re interested in the future of Lisps either on the JVM or off it. (I should mention that Stuart Halloway’s Programming Clojure has been my trusty and helpful guide in this endeavor; recommended.)
But as for me, Ioke has stolen my heart: it possesses the syntactic simplicity characteristic of homoiconic languages (and hence the power of macros) paired with the developer-friendly attitude you’d expect from someone who’s spent a lot of time with Ruby.
(I should note at this point that, although Ioke is deeply inspired by Io and Smalltalk, my experience with those languages is limited strictly to reading their code samples. Render unto them all due credit and so forth. I’ve spent much more time with Ruby and to a lesser extent Lisp derivatives.)
It isn’t the fastest JVM-hosted language by any stretch of the imagination, and it doesn’t (yet) have the most compelling feature set. But it’s a lot of what I love about Ruby without any of the syntactic drama, which, with a few wrinkles, is more or less a good thing. And in true open-source style, it’s evolving live, in front of the world, and it’s got a great dev community hacking away on it if you’re looking for something to contribute to.
If I had to point to just one thing that I love about it, ISpec is Ola’s RSpec -inspired BDD testing framework included with the Ioke distribution as one of the first core libraries written entirely in Ioke. Three great things:
- Message-style chained calls mean that it’s absolutely gorgeous to read.
- That same philosophy means that its internal semantics are much, much simpler than RSpec’s, which means that it’s easier to extend. I’m working on adding a mocking framework to it, and tacking “should receive” onto the existing infrastructure was close to trivial.
- ISpec’s code documentation library, Dokgen, integrates seamlessly with the code and ISpec to produce API docs that tie directly into the specs. Go browse Ioke’s API and you’ll see the tests that map to a particular method tied directly into its documentation. I believe strongly in testing the dickens out of your code, and to see the live specified behavior tied directly to method documentation is just awesome.
Stop by the website or the mailing list and let Ola know what you think.
Posted in Professional | no comments |

Your host is