Archive for June 2009

Recent Developments

I’ve been awfully busy the past few weeks, but finally had three separate evenings to sit down and code on some of my little projects this week. I’m anticipating having more time in a couple weeks, as I gave notice on my job on Thursday. I am, however planning a move and exploring numerous job opportunities in my home province.

I managed to fix a couple bugs on WhoHasMy. As previously reported this project was originally coded in 48 hours for the Django Dash competition. We tied for fifth place and have traded the resulting bitbucket account for a github prize. I’m very happy with the placement given that my brilliant co-developers had nil django experience going into the competition and I hadn’t touched it professionally in months. I added a TOS to the page as requested in a comment on my earlier post, fixed some ordering bugs in the lists, fixed a couple broken links, and made it easier to add information about friends when you loan an item to someone not currently in the system. And here we thought it was 100% bug free when we finished our 48 hour stint and stumbled off to bed.

I have also spent a fair bit of time improving Quodroid, the Android app for controlling quod libet on my laptop from my phone. It now uses fancy icon buttons, allows you to specify the host and port you want to connect to, lists the currently playing song whenever you perform an action, allows volume control, and gives a semi-sane error message when the phone can’t connect. In short, its actually useful and usable by someone other than myself. I’ve been using it regularly the past few days. I still have to arrange it to perform the network stuff in a service instead of the main activity, which occasionally becomes unresponsive if the server is slow to respond. I’m actually becoming more comfortable with Java again as I develop this, its not as evil as I thought, but it certainly cuts into productivity.

Today, I made a few changes to opterator. I wrote my first app (a contrived example code-test for a job I’m pursuing) that actually used opterator a couple weeks back and found it was missing a few features. It now the ability to have multiple copies of a single option. Turns out this actually worked, all you had to do was use the ‘append’ action. I wrote three tests, didn’t change a line of code and poof, I had append support! I then realized that storing the action in the docstring was unnecessary as it could be introspected from the type of the keyword argument. This makes the @param docstrings a lot more readable and informative. As simple as this little module is, I feel its one of my more brilliant innovations.

I’ve also tossed around the idea of having multiple opterated main methods in a single module and allow the decorator to pick which one to call depending on the options. This seemed cool at first, but I think it may violate the ‘one best way’ policy of Python. I also realized that deriving sensible error messages and usage strings would be really painful, from the end user’s perspective, so I’m holding off on this until I’ve decided how best to do it.

Style As Communication

A couple weeks ago I read an article. I don’t remember the title, links, topic, or most of the content of the article; indeed, I likely should never have read it. I would have forgotten it altogether except one suggestion that you should ensure the signature on e-mails sent from your blackberry or iphone says “Sent from my blackberry/iphone”. In theory, this allows the recipient to know you were on a mobile when you sent the message and they can excuse the brevity and grammatical errors that tend to occur when typing a message on such devices.

When I receive a one-line comment followed by a second line stating ‘sent from my Blackberry’, my first thought is not, “Ah, they were mobile, they weren’t able to type a polite response”. To the contrary, I tend to think, “They couldn’t be bothered to go back to the office and send me a well-crafted reply. How can I trust they even thought about the question at hand?”

The thing is, how things are worded sends as much information as the words themselves. Critics of the Internet age have long pointed out that face-to-face communication is better because you can pick up on so many non-verbal cues in their gestures, posture, tone, and expression. Yet nobody realizes that text-based communication also says plenty about you and about the message you are conveying.

While we are instructed to ensure our cover letters and resumes have no grammatical errors because it makes a bad impression, in day-to-day business or interpersonal dealings, nobody worries over such things. We’ve all seen the despicable language that has evolved to support the character limits in Twitter and text messaging. It makes the most erudite communicators look like fools.

The full qwerty keyboard on my HTC dream is terrific, but I don’t get anywhere near the 100WPM I can get on my computer keyboard. Messages typed on the mobile can be painful to compose. I always put forth the effort to ensure my grammar is correct and the style is the way I want to sound. It takes me a while and I can’t supply that impressive immediate reply that mobile devices are famous for. But I can give you a hand-crafted response styled ‘just so’, to give you exactly the interpretation I wish you to receive. Chances are I won’t send the message until I get home and review it at a full keyboard where edits are easier.

One can argue that putting an emphasis on grammar and style is a waste of time and the world is clearly learning to evaluate only the content of messages. This is a shame. It restricts our ability to communicate. Properly wielded, style can say so much more than mere content ever will. Like pictures, style can be worth a thousand words. Instead of abandoning style altogether, we should cultivate it, use it as a secondary channel, its own medium of communication.

As a fitting example, compare the following two messages I received recently when trying to sell a desk online:

CALL ME. 416-###-####

vs:

Hi I am interested in the corner desk you are advertising on craigslist. What are the dimension of the desk? And where in Toronto would I be picking it up from?
Thanks,
Emily

When I read these messages, I felt that Emily was more likely to be truly interested in the desk. I felt she would follow through on any commitment she made. I felt she could be believed and trusted. I felt she would let me know if she was going to be late or couldn’t make her appointment. I felt she was friendly and would be a pleasure to deal with.

Emily is now the happy new owner of my corner desk.

She only typed three short sentences, but gave me several paragraphs of information. The former request only typed two words and a phone number. They also gave me several paragraphs of information.

I never called.

Exceptions As Flow Control In Python

I’ve complain in recent months that my knowledge of Python has stagnated. I look at code I wrote six months ago and I still think its well-written code and there isn’t much I would change. It is well-written code, but in previous lives, my definition of good code would evolve.

Possibly due to my early training in Java, I’ve always been quite cautious when raising exceptions. In Java, exceptions are a curse. The overhead of maintaining them and listing which ones can be caught or thrown from a given call-stack is time-consuming and of dubious benefit.

In the past, I’ve read the word ‘Exception’ as meaning ‘an exceptional circumstance I didn’t anticipate’. I don’t raise exceptions often unless I’m writing a library and want to communicate an exceptional circumstance the calling system may not have expected.

Excluded from this definition are ‘error conditions I did anticipate’, such as validation errors or permission checks. When I expect such errors, I tend to include them in the return values. If you’re a python coder you might think I mean this:

## BAD CODE ##
result = some_function_with_error()
if type(result): == tuple:
    error, message = result
    # handle error

But I would never do this. Checking the type of an object in Python is a sure sign you’re doing something wrong, probably very wrong. Either that or you’re writing some kind of introspective framework. I’ve seen code where people return an object in the normal case and a string if its an error. They then check if type(response) == str. This will fail when you ultimately have to switch to unicode, and its going to make your Python 3 porting attempts very confusing. Don’t do it.

However, I frequently use this idiom:

isadmitted = auth.check_privilege()
    if isadmitted != True:
        return isadmitted

In this case, check_privilege is returning either True or an error string. I used to think this was good code, but its actually doing an implicit type check. if you have to write ‘x != True’ instead of ‘not x’, its not proper duck-typing. While its unlikely that boolean will ever have values other than ‘True’ and ‘False’, its highly probable that your function will one-day want to return something else.

That last bit is based on real code I decided to refactor today. I’ve expanded my definition of ‘Exception’ to ‘anything that is not the normal return value of a function’. Now I have code that looks like this:

try:
       response = self.process_post(session)
except (ValidationError, InsufficientPrivledgesError), e:
    session.rollback()
    response = e.response
else:
    session.commit()
finally:
    session.close()
return response

I’ve wondered why so much attention was paid to Python’s try…except handlers in recent releases. Now I know — its because they expect Python coders to use them. Two months ago if I’d written an exception handler that included all of except, else, and finally, I’d have thought I was doing something wrong. My new understanding (notice I don’t say ‘corrected understanding’) is that this is how such code should look.

The good news is: every time I look at code I wrote six months ago and see something that uses an if statement to check a return value for an error condition, I’m going to be itching to rewrite it. My understanding of what good Python code should be has evolved. I’m back!

Django Dash

“I am going to send you a link and I want you to think about it before you just say no.”

That’s how Jason introduced the idea of the Django Dash to me. He figured it’d be fun to try to develop an entire web app in 48 hours using a web framework and Javascript toolkit he was unfamiliar with. (Jason has odd ideas of fun). I agreed, but we’re both aesthetically challenged. We’re good web programmers. Website design and graphics, not so good.

Enter Phil, an acquaintance of Jason’s I had not yet heard of. Great guy, great designer, great team mate.

So last weekend, I spent about 35 out of 48 hours on skype with these two goofballs three timezones away, typing python code and cursing javascript. We made 100 commits more than any other team (but we wore out before we cleared 500). Sleep and exhaustion tried to throw us off course, but we pulled it off. We had a ton of fun and I even learned something (the for statement can have an else clause).

The constant skype linkup really helped in terms of motivation, its so much more productive to just ask a question and have it responded to than to dig through someone’s code trying to figure out what they were thinking, to scan google results looking for the info you need, or to send an e-mail to someone and wait for them to respond. Skype is also more productive than instant messaging. This surprised me; turns out that its much easier to talk and type in or scroll your source window than it is to be constantly switching back and fourth to your IM window.

For those interested, here is the result of our 48 hour sprint, a relatively complete and not-quite bug-free loaned item tracking application: WhoHasMy.

Phil deserves all the credit on the sleek design, he’s totally awesome and is the difference between an ugly django app with ajax calls and a professional one. He also has an entertaining habit of verbifying nouns.

Jason deserves the credit for the initial idea, most of the program design, autocomplete, and bailing us out when git-svn confused us… several times.

I will take credit for an outrageous number of commits editing the to-do file and keeping us organized. I think I may also have written some python code and some interesting ajax requests.

Our top priority was to have fun. And we did — It was a blast. I think we’ve got a decent chance at a prize, though there’s some stiff competition out there. But hey, Who would turn down a free private github subscription or Bacon?