⇥ The myth of the myth of self-commenting code

April 30, 2009
5 comments
 
⇥ Permalink

On Code Commenting And Technical Debt | BrandonSavage.net

Interesting post by Brandon—I disagree only on one main point:

This myth of self-documenting code needs to be squashed once and for all. Commenting is important, and unless your code does nothing other than display “Hello World!” it’s going to need some explanation.

I find this view of coding a little misguided, to be honest—in fact, I would go as far as saying that code doesn’t need any comments.

Wait, did I just say that? Yes, I did, and here’s why: code is a discussion between the developer and a machine. Writing code that cannot be comprehended by another human being is a bit like writing a letter to your dear friend in a language you can write but not read—strange, at best.

Good code should be self-documenting insofar as you should be able to understand what the code does without the assistance of any comments—after all, the computer gets it, so why shouldn’t you? This can easily be done by the judicious use of clear logic and good programming practices like giving your variables names that are actually related to what they do.

What I suspect Brandon really means is that the comments are there to illustrate the intentions of the author when those intentions are not immediately made obvious by the code itself. This, I daresay, is the crux of Eli’s argument that commenting inside the code is the most important contribution that a developer can make towards eliminating technical debt. That’s because commenting inside the code helps understand the reasoning behind the choices that were made when writing the code, rather than what the code itself accomplishes.

Let me make an example using an actual piece of code taken from a project I’m working on in an effort to avoid the hello-world syndrome that so often affects this kind of post:


function construct(array $pathInfo) {
$section = $pathInfo[0];
$file = $pathInfo[1];

// Assume that the location of this file is inside the main trunk, and that pathInfo has already been filtered.

$path = dirname(
FILE) . '/../../' . $section . '/xml/static/' . $file . '.xml';

if (!file_exists($path)) {
Controller::singleton()->doError(404);
}

parent::
construct('main/xsl/template.xsl', $path);
}


Now, as you can see this code contains only one comment, but I think that any reasonably competent developer would have no problem understanding what it does, because the code itself gives you all the assistance and hints you need. On the other hand, all sorts of big red WARNING flashing lights would be going on in a developer’s mind without the comment: why is the code looking for things using relatives paths? And, most disconcertingly, why isn’t the $pathInfo array being filtered before usage*?

Thus, the concept of “self-documenting” code is not a myth—code should be written so as to tell a developer what it does without the need for any comments. It is a myth insofar as people use it as an excuse to avoid documenting their intentions, which is really what comments are useful for.


* I cheated a bit here, because in the real codebase the filtering is done system-wide, so part of this comment is really superfluous if you know the codebase’s overall design, which, of course, would be documented elsewhere.

⇥ May I suggest a rev=completelyUnrelated attribute?

Brooklyn novelist Peter Brett found his muse and wrote first novel commuting on the F line


That’s gotta make for a couple of sore thumbs—but the best part is the ten links in the article, of which one is relevant to the topic at hand. But, hey, at least they didn’t link articles and most adverbs.

⇥ The book industry is stupid


If the world were a less stupid place, there really would be no need for bookstores. You’d simply go online, find a book you want and have it printed out remotely at a location that’s convenient to you. This way, publishers would save money by not having to print a million copies to sell 100,000, authors would be able to negotiate higher royalties and not have to deal with the problem of accounting for reserves and returns, and the entire accounting process would be simple and automatic. And don’t even get me started on the savings for the environment: no more shipping, no more waste of paper (since you only print what you need) and a greater distribution of refuse.

Of course, there would be two huge losers: bookstore chains and distributors, which luckily are already doing an excellent job of destroying the market anyway.

Small bookstores would, on the other hand, thrive, because they would be able to offer a valuable service (printing any book at any time) that is perfect for their small scale.

⇥ To except is human; to handle is divine.

April 22, 2009
4 comments
 
⇥ Permalink

If you write code, you’re writing bugs—it’s a simple fact of life, and the sooner a developer accepts it, the sooner he or she can work towards mitigating the damage that mistakes and errors inevitably carry with themselves.

After many more years in this industry than I care to admit, it still surprises me how little attention developers pay to error management—and, let’s be clear, I don’t mean preventing errors, but managing them.

Errors as Opportunities
When an error occurs, the vast majority of the web-based application code that I see during my reviews performs the software equivalent of running around with its head cut off: the developer spends an inordinate amount of time and resources trying to make the software look like what was essentially a catastrophic failure was nothing more than a small temporary hiccup. Enter Error-500 pages that attempt to redirect, provide excuses and, generally, cover up the fact that something went horribly, horribly wrong.

In reality, by the time an error has occurred, there are only two possible outcomes: either you expected the error to occur, in which case you have already written code to handle the failure, or you didn’t, in which case your main focus should be to use the error as a learning opportunity.

Doing the Right Thing
When I write web code, if an unexpected error occurs, I actually want the software to fail. The reasoning is simple: if an abnormal condition occurs in the application, I don’t want any of its possible side effects to carry over into other areas of the program and potentially cause even more problems. Thus, I spend little time actually handling the error is very short: I redirect the user to a simple page that communicates the fact that a temporary error condition has occurred. I don’t even bother trying to recover, and I certainly don’t advocate that the user try again—the last thing that I want is more damage.

On the other hand, I spend a considerable amount of time collecting information. Logging an error is not nearly enough: you need to be able to examine as much of the conditions that surrounded its occurrence. Generally, I collect information about:

  • All the local and global variables present at the time of the crash
  • The entire HTTP environment—GET and POST data, cookies, Apache environment variables, and so forth
  • Breadcrumbs that indicate how the use came upon the particular document that caused the error
  • Some critical information on the overall health of the hardware—machine load, memory usage, and so forth

The idea is that the more information you have on hand, the more likely you will be to understand how the error occurred and, therefore, either fix the bug that caused it or write code to turn it from an unexpected error condition to an expected one.

Timeliness is Close to Godliness
In addition to collecting information about an error, you also need to make sure that the IT support team gets notified of it within the appropriate timeframe. At my company, when we write software we often categorize exceptions according to a number of different traits—one of which is its criticality. An exception with a low criticality level, for example, will generate little more than an entry into our logging system—whereas a critical exception (such as, for example, a database that suddenly fails to respond) warrants an escalating series of actions, like sending an e-mail to the IT folks or, in more extreme cases, even page someone.

It pays, when you’re designing the architecture for a system, to introduce the concept of criticality early on, so that you get to decide how important any given class of errors is based on the specific constraints of your business requirements, as opposed to some abstract concept of ideal error reporting functionality. Items that might be critical to your particular business—like the ability to perform fraud checks on an e-commerce site that consistently manages high-risk transactions—may warrant actions that for others may not be as important.

Break Before You Fix
Fixing an error as soon as you become aware can be a costly mistake—and a difficult one to understand from a business perspective. When the world comes crashing down on your company in the form of a broken website, the last thing that management and investors are going to want to hear is “well, let us figure out what’s wrong first,” but, realistically, that’s exactly what you should be saying.

Far too often, I see developers rushing into fixing a bug without considering all the possible consequences of their changes—thus making a strong case for doing the exact opposite!

A bug fix should always be preceded by a reproduction test. It’s not until you’ve managed to consistently cause a bug to rear its ugly head that you have really understood what causes it. A proper test provides you with an easy, quick and consistent way to reproduce a bug and make sure that you have effectively squashed. More importantly, a test “is forever”—it becomes a useful regression tool so that the next time you fix a bug you have one more way to ensure that your changes do not have any undesired side effects.

Of course, in order to write a test, you need some sort of test harness, which is a deceptively simple concept that a lot of developers (and managers) still seem to have a big problem coming to terms with. You don’t have to be a believer in TDD to appreciate the advantage of a good testing platform—and today you have access to so many that are easy to use, powerful and inexpensive that it really doesn’t make sense for your project not to have one, no matter how small its size or simple its function.

If you’re interested in more on handling errors, Jeff Atwood at Coding Horror has recently published an interesting piece on the subject.

⇥ A quick review of the new 17" Unibody MacBook Pro

April 19, 2009
6 comments
 
⇥ Permalink

If you follow me on Twitter, you know that I recently—well about a week ago, at any rate—switched from my trusty, 3-year-old 15″ MacBook Pro to a brand-new 17″ Unibody MbP (you know, the one with the battery that can’t be removed).

One of the things that really annoy me about review sites is that they are all interested in scooping each other and, therefore, their reviews never really have any depth. Personally, I don’t really care about what the specs of a computer are, or how they match up with the competition, or how well a computer performs in the contrived-benchmark-du-jour.

What I care about is how well it performs for me.

Before you laugh this off as another Tabini oddity, coming up with a meaningful review is not that hard—what it takes is time, and a real user… you know, someone who actually uses the machine for a real purpose instead of trying to get an article on a website as quickly as possible. If more people did that, we’d know less about RAM and hard disks, and more about what they can do to us.

Thus, here’s my quick review of the MbP.

The user
I used to think that I am a bit of an oddity in terms of computer usage: I use XCode alongside Pages on a machine that runs a rather complex Apache installation and a custom-built version of PHP. However, it turns out that I’m hardly alone: a bunch of tech-business people are in my same shoes: they need to write code and handle accounting, all in the same day.

As I am not a gamer—at least most of the time—graphics and power do relatively little for me. As far as I am concerned, the defining qualities of a computer are portability, desktop real estate and overall ownership experience. Here, I got to try out all three.

The experience
I like shopping at the Apple Store—although I do not normally need much in the way of buying advice, I appreciate the opportunity to window shop and make sure that the choice I’ve made is the right one; there are some things, like picking a screen type, that one just can’t do on the Internet. Plus, there is always the plus of being able to walk with your new machine under your arm.

I also like Apple customer service. Although I’ve had a few occasional hiccups, the folks at the Apple Store have always been very good to me. In this particular case, the first machine I bought was damaged—to be honest, I’m not sure if it was my fault, as, although I normally treat hardware with care, I might have bumped it on the way home. No matter—a visit back to the store resulted in a brand new system, no questions asked.

The other great thing about buying Apple is that you get really good support wherever you are. Last year, I was in Wilmington, DE for a trial and my machine developed a nagging problem with its battery. Rather than having it die on the stand, I took it to the local Apple store, where, despite the fact that the machine had been bought in a different country, they gave me a brand-new battery, again without asking much in the way of questions (it helps, of course, that I insist on getting all my receipts via e-mail on my Mobile Me account: this way, even if my computer is dead, all I need to pull them up is a browser and any computer).

My only real complaint here is the fact that in-store computers are only available with the 5,400 RPM hard drives, which is just plain stupid. The price difference compared to the 7,200 is only $50, but the performance hit is likely to be quite significant. Besides, you just can’t get a faster hard drive even if you want, unless you go on their website. What gives?

The machine
The new MbP is very portable. With my usage pattern (mostly writing code or documents, e-mail, browsing, some code compilation time here and there), I can get a solid 7 hours’ worth of computer time—in fact, the biggest problem that I’ve had this far with the machine if my inability to properly calibrate the battery, because the machine can stay awake longer than me.

Despite its size, the computer can be easily carried around. The construction is sturdy (I broke my very first Apple laptop by slamming my fist on the wrist rest when some piece of code I was writing refused to work after a few hours of trying—I have since learned the hard way not to do that again, but I have a feeling that the new Unibody construction can take a lot more abuse than its predecessor).

A big plus for me is the fact that (a) there are three—count ‘em, three—USB ports on the machine, and the are all on the same side (the left, to be precise). This is very handy when using my portable mouse, which requires a dongle* together with my iPhone for development and my microphone headset for carrying on conversation over the Net. I suspect that a left-handed person might be a little put off by the location of the ports, however.

The screen
The biggest selling point for me is the screen—at 1,900 x 1,200, it has the same resolution as my 24″ iMac, but, given the smaller screen size, offers a much higher pixel density than its larger cousin. This makes for a strange dichotomy: on one hand, everything becomes tiny, which does take time to get used to. On the other, the amount of real estate is nothing short of fantastic, particularly when working with multiple code windows, or editing a word processing document at the same time as you’re working on a spreadsheet—something that comes in handy when I do my budgeting.

Glossy or matte? Ah, the agony of choice. I ended up going with the antiglare option (which, curiously, you can actually get at the Apple Store), but I confess having second thoughts about my choice. Given how bloody bright the screen is, I really don’t think that one could have a problem with it, even in full sunlight. In fact, I wouldn’t be surprised if the FAA were to forbid its use anywhere on the approach path of commercial and military airports for fear of blinding passing pilots.

Overall impression
Overall, I am happy with the purchase. The MbP feels like a desktop machine—the first time I have been able to say that about a laptop—without being as unwieldy as one. As I mentioned, power and memory are not really concerns, but the machine does feel very responsive, even with the 5,400 RPM hard disk (which I plan on eventually replacing either with an SSD or a 7,200 RPM). From the point of view of screen capabilities and portabilities, the MbP is a clear winner; the only way I think I would be happier would be with a 17″ version of the MacBook Air—although I shiver at the thought of how expensive that would be.

Most importantly, if you are in the market for a new laptop, the MbP gives you an opportunity to overcome any of the compromises you would typically have to make: it’s relatively light, powerful and sturdy, and has a screen second to none.


Quick addendum: the one thing that really bothers me about the MbP is that it is virtually impossible to find accessories for it. I couldn’t buy a hard shell case, because nobody makes them, and the same goes for wrist mats (I hate the feeling of aluminium against my skin, and now I have to worry of eventually discoloring it). If Apple were a little less paranoid about security and shared more of their specs, we’d have these damn things already.



* Yes, I know about Bluetooth mice: they are about as portable as a tank, and require the same amount of battery power. Oh, and for some reason they cost twice as much as non-BT wireless rodents.

⇥ Reality is much worse than fiction

Every now and then, I come across a news item—like this—which talks about some poor guy (or gal) somewhere who had the distinctly unpleasant surprise of receiving a $25,000 bill because his or her phone was stolen and used to call Namibia, or Peru, or the Moon.

I feel for those people—I really do. I’ve paid a $20,000 telco bill a few times (alas, all legitimately billed) and I know how painful it is when you expect it… so, I can only imagine how horrible it must be when you don’t.

On the surface, this looks like pure greed on behalf of phone companies that will do whatever they can to screw the little guy. Sure, it’s your responsibility to monitor your phone usage, but it’s trivial for the phone company to put an automatic block on your account when you go, say, 10% over your average monthly spending for the last 12 months (incidentally, the company I use, Fido, does this by default—an act of uncharacteristic decency for a company owned by the worst media conglomerate in Canada). The credit card industry has done it and, realistically, it should be at most a handful of lines of code.

However, let me give you this little story from my bag of “I can’t believe I once heard this” tales. About seven or eight years ago, I did some work for a telco—whose name shall remain unnamed in order to protect the innocent, the guilty and the NDA I signed. One of the subprojects—for which, luckily, I wasn’t responsible—was the ability to bill customers directly on their phone bill.

This involved interfacing with the department that handles the billing system, which claimed—I kid you not—that adding a new revenue centre to said billing system required a whopping seven months of notice.

If adding a new item to a phone bill can “take” seven months, I will let you imagine the massive amount of time and resources that implementing a simple anti-fraud system can require. It’s just the way these companies roll—which is, unfortunately, much sadder than if they were actually trying to screw people over.

⇥ Introducing sight-free dialing for the iPhone

April 16, 2009
4 comments
 
⇥ Permalink

A few weeks back, I stumbled upon this video by the Google engineers who have been working on the eyes-free project for Android and I found it very interesting. At the same time, I found their solution a little awkward in that it relies on the user’s sensing the boundaries between virtual keys using tactile feedback—something that I don’t think able-bodied people (who can still benefit from this kind of technology to safely use the phone without looking at the screen) will be able to easily do.

After a few days of head-banging, I convinced my partner Arbi Arzoumani that this would make a good project for our nascent AFK Studio, the boutique iPhone development that we started earlier in the year.

Therefore, I am happy to announce the release of DialX, the world’s first sight-free dialer for the iPhone capable of dialing arbitrary phone numbers without looking at the screen. We have a complete list of capabilities over the at the DialX site, but, as they say, a video is worth a thousand words, so here we go:




I have a few coupons for a free copy of DialX available. If you would like one, please DM me on Twitter (@mtabini) and I will be happy to oblige (as long as I have any left). Please note that these coupons are good only for the US iTunes App Store.

Do you like DialX? Digg or Reddit this article and help us spread the word. Comments? Thoughts? Suggestions? Drop a comment below.

⇥ Quick note: moderation is now on

April 15, 2009
3 comments
 
⇥ Permalink

It appears that spammers have plenty of time on their hand; therefore, since neither CAPTCHAs nor moderation on old posts seem to deter them, I have turned on full moderation on this blog.


Moderation is, of course, not an excuse for censorship. I will not prevent messages from being posted unless they are completely off-topic or obviously spammy—there is a certain amount of personal judgment involved, clearly, but given that pretty much all the comments I filter out are about viagra, porn, shoes (seriously—shoes??) and so forth, I don’t think there will be a problem. To be clear: messages critical of my posts will not be moderated out under any circumstance, including obvious idiocy.

⇥ Business by the pound

Analysts and journalists seem to have an unhealthy obsession with Apple. For example, I came across this article on Business Week, whence I draw this gem of journalistic imbecility:

And while a teardown doesn’t account for the costs of design, software, manufacturing, or shipping, these cost estimates help fill in the blanks toward estimating the profit on each device sold.


Let me put this another way: would you accept my measuring the worth of your house based on the pounds of timber or the number of bricks it contains? Not only would that ignore things like the cost of designing the house, researching the materials, hiring the labourers, building it, getting all the necessary permits, and so on, but also other things, like, say your location (comparable perhaps to all the marketing money Apple has to funnel into iPods), the cost of maintaining it, the risk of somebody slipping and falling (lawsuit, anyone?), the cost of improvements, and so on.

On one hand, I almost pity these journalists. Apple treats them like rabid dogs, instead of kissing their ass like everybody else does, and so what else can they do but take what essentially amounts to a curiosity—or, at best, a relatively insignificant aspect of the production of a device that belongs to an ecosystem as complex as the iPod’s—and build a whole business analysis out of it.

Edit: oh, incidentally, I’d expect that a magazine called “Business Week” would actually know that “profit margin” is not calculated based on the cost of raw materials alone. Heck, even Wikipedia knows that it’s the net profit-to-revenue ratio after all costs and taxes. Sheesh!

⇥ Typography you can use

One of the downsides of working in the publishing business is that, after a relatively short amount of time, one loses the ability to enjoy reading the way normal people do.

This is not to mean that I no longer like to read—quite the contrary—but that I no longer can read any text on any medium without paying attention to its typographical design. Conversations between my partners and I usually start with “did you read that book?” and end up in some variation of “yes, the font was awesome—but they clearly haven’t mastered a good justification algorithm yet.”

On the web, most people don’t seem to know what to make of basic typography. In an effort to improve the general state of things, let me introduce you to three typographical elements that I use more often than, it seems, most other people: the endash, the emdash and the ellipsis.

Endashes and emdashes (also called en-dashes and em-dashes) are closely related cousins of the comma and semicolon. An endash (so called because it is roughly the width of the glyph n) is used to indicate a range. For example:

php|architect, Volumes I–IV


The use of an endash, as opposed to the simple dash, is useful because it’s less likely that an automated process reading through a piece of text will confuse a range for a subtraction. This may seem trivial until you find yourself in the position of having to parse large quantities of text for the purpose of, say, compiling a book. It’s happened to me once, and I’ve been a proponent of endashes ever since.

On OSX, the endash can be produced by typing ⌥ + – (that’s Option-minus sign).

The emdash (whose name derives from the fact that it’s roughly the width of the glyph m) is (primarily—it also has other uses) a distant cousin of the comma. You can use it to indicate a portion of text that would normally belong between parentheses—in fact, it was once described to me as somewhere between a comma and a parenthetical remark. Think of the emdash as one more weapon in your grammatical arsenal—it’s less ambiguous than a comma (which, after all, could be used for a number of different reasons). It provides a considerable amount of separation between the two words that surround it—thus giving your eyes a visual queue that a new remark is being introduced.

The setting of an emdash—that is, whether it should be surrounded by a space (open setting) or not (closed setting), is a matter of much debate. I have a personal preference for closed setting, because I like how an emdash visually links two words while actually providing separation in the thread of a sentence.

On OSX, an emdash is produced by typing ⌥ + ⇧ + – (that’s Option-Shift-minus sign).

Finally, the ellipsis is a glyph that most people are familiar with—they just don’t use it properly. An ellipsis is a series of three small dots that either identifies an omission in the text or an aposiopesis (that is, an unfinished sentence). For example, I could use an ellipsis as such:

If I only had a few million dollars to spare…


Most people, as I mentioned, create an ellipsis using three periods. This is wrong. Please, please, stop doing that. Periods have a number of uses, but producing an ellipsis is not one of them—unless, of course, you’re stuck in 1947 and your keyboard goes “clackety-clack” when you type. In that case, you have my sympathies.

Jokes aside, there are a number of good reasons why you should learn to use the proper ellipsis glyps instead of three periods. First of all, it’s typographically correct—most likely, your font glyps have been properly calibrated so that the individual marks of the ellipsis are the correct size (which is probably not the same size as a period) and are at the proper distance (which is definitely not the same as the distance between three periods). Additionally, you provide a valuable clue to any piece of software tasked with analyzing your text. Finally, you save two characters—which is very handy in today’s Twitter world.

On OSX, you can produce an ellipsis by typing ⌥ + ; (that’s Option-semicolon).

There you have it—three important typographical elements that will make your text more articulate. Of course, the rules for their usage are all but set in stone—there are plenty of conflicting schools of thought on the use of endash vs. emdash, for example (heck, there are conflicting schools of thought on how they should be called, let alone used), but the use of proper typography is an excellent device to force you to think more closely about your writing habits—especially your grammar.


Of course, such discussions never centre around our own products, which are, by definition, perfect.