Recently, I’ve been working on a project that customizes my task management software. I’ve been writing it in Ruby, which is a pretty interesting language.
At this point, I’ve probably rewritten the code 3 times.
Because it’s more elegant the second (third!) time around. Because it’s more beautiful, easier to maintain and understand, and easier to extend and grow. But, most importantly, because it feels good.
In fact, every time that feeling hits: “Wait, I could do this better!“, I think of college and my time as a physics major. We all used to work on our problem sets in this one room in Leconte Hall:
I was never that good at physics. My solutions were always ugly, three or four pages long, full of copied terms that never went away, even though everything started beautifully elegant and short, like this lagrangian: 1
When I compared with my classmates, I knew they were out of my league. Not only did they get the right answers, but their answers were beautiful. Short. Concise. Elegant. The answers, in other words, at the back of the book. Invariably, my classmates would say: “Well, you see, if you just chose this” or “Well, if you just rearrange this…”
I never really “grokked” physics deeply enough to feel my way to those insights without help.
But I think I can articulate what, fundamentally, is the most important feeling that guides me to great, elegant code:
Don’t Repeat Yourself, ever.
There’s a whole bunch of reasons why you should write elegant, concise code. I think a lot of people have made convincing arguments, showing that it increases maintainability, flexibility, and so on. I’m going to take a step further. I claim those things are simply gravy.
In the long run, if you want to keep on solving hard problems, or hacking together great prototypes in 8 hours in an all night hackaton, or growing your product, you need to love what you are doing.
The first step towards loving your work is respecting the work you create and honoring the feelings you have while creating it. Don’t stuff those “I can do this better” feelings away because it means you have to rewrite something or take 2 more hours to do it right.
It’s worth it to do it right.
EDIT: I’ve kicked off my language love series, which will be short posts about fun things that I find really elegant in different languages: the first is about dynamically adding methods in ruby.
1. This is a pretty elegant lagrangian for the total energy of a particle in spherical coordinate system. And yes, I got it from wikipedia; I haven’t installed LaTeX in years.