Yan Pritzker photographer, entrepreneur, software engineer, musician, skier

Blog :: Git Workflows Book :: Dotfiles :: Photography :: About Me

TwitterCounter for @skwp

Get the news feed
Get updates by email
Follow me on twitter

hello, i'm yan

I am a photographer, entrepreneur, software engineer, guitarist, climber, and telemark skier

This blog is about startups, blogging, Ruby On Rails, virtualization and cloud computing, photography, customer service, marketing, ux and design, git, and lots more.

I am the chief technical something or other at Reverb.com - The Marketplace for Musicians. We're hiring web designers!

Recent Tweets

Selected Reading

Archives

Contact

Reach me at yan at pritzker.ws

Five Rules for Writing Good Code

Posted 29 September 2009 @ 4pm in code



Submit to HN

1. Write for an audience

Code tends to outlive jobs. When we create code, we are not writing for ourselves, but for an audience of peers and progeny that will look upon it and have to maintain it. Do we want them to do so with awe and respect, or with fear and disgust? Writing maintainable code not only makes our life easier, but the lives of those around us, and garners admiration, praise, and rewards – if not always financial, at the very least karmic.

2. Establish a clean framework for future changes

If we start writing new code, and the pattern we establish is that we’ve copied and pasted a line across ten functions, what will happen when someone else comes along to add an eleventh function? Let’s face it, even the neatest programmers can get lazy. If something has been copy-pasted ten times, it will get copy-pasted for the 11th time, and a year later, when we find out we have to change the logic or content of that line, we are now changing 50 lines where we could have had one. Untangling code is always a lot harder than writing it, and we could have prevented the spread of the copy-paste disease by evaluating our code initially for repetitive statements. Always establish a framework for others to follow by writing clean code that reduces repetition, and encourages maintainability by isolating each piece of logic and content to one spot only.

3. Be brief, self-descriptive, and avoid inline comments

Five line functions with descriptive names are easy to understand. They require no comments. Thirty line functions take quite a bit of brainpower to digest, and usually have smelly comments scattered all throughout trying to explain bits of the function. Hundred line functions are an assault on all that is holy and stink to high heaven. If we see lots of comments interspersed in a method, it is a good sign that the code cannot be easily understood. Break it down into lots of little functions with descriptive names, and all of a sudden our code reads like a very clear and concise recipe, and we find that the comments become redundant. Most comments that live inside functions are parasitic organisms, treat them with suspicion.

4. Follow language standards and community conventions

If we break conventions, the next person to read our code will wonder why we did so. When our code raises questions about its style, the reader may start wondering if there was some specific reason that we coded it that way. Worse, they may perpetuate our unusual style through imitation and copy-paste tactics. This makes code harder to understand and wastes other people’s time. I’ve heard an argument from more than one person that they will code with the style they are comfortable with rather than follow language convention. This is especially true of people migrating from one language to another without investing their time in learning new habits and techniques. Remember that most of the time, we are writing code that someone else will be maintaining. Make their job easier by conforming to widely acknowledged standards, so they don’t have to spend any extra mental energy reading through it. It may take we a larger effort initially, but it will pay off with dividends when it comes to maintenance.

5. Really learn the language and the framework

Lots of bad code is written because of language or framework ignorance. If we don’t know the framework we use, we might reinvent the wheel or write obtuse code because we’re not taking advantage of the conventions and helpers already created for us. No need to be a walking encyclopedia, but remember to occasionally open up that encyclopedia and read through it so that you know at least what’s out there. I am sometimes surprised by new things I find in a framework I’ve used for quite a while, that makes my life a whole lot easier. Don’t neglect the docs, and don’t neglect to keep up with blogs that discuss new techniques.

I’m not really back, I’m just pretending. That’s all for now :)

12 Comments

Posted by
Nathan Leach
1 October 2009 @ 7am

Yan,

Nice, concise list of rules. I like them all. I would add that comments can be useful in the sense that you can say “why” you are doing something…the “how” should be the clear part in the code itself. What do you think?

I do mostly corporate development, where standards dictate a certain level of inline documentation. It takes a lot of time and effort to change those rules (sigh).

Keep up the good work!


Posted by
Yan
1 October 2009 @ 9am

Yes, of course you are right – comments explaining Why are not a bad idea. However, almost always the right place for comments is outside of a method/class/chunk of code depending on your paradigm, explaining why the method does something. When you find them interspersed within a large method it usually means the method itself is too long. Inline documentation is not inherently bad, it’s just bad when it’s used as a substitute for breaking code down into small, easy to understand functions with self-descriptive names.


Posted by
Thor
28 November 2009 @ 5pm

In fact, in Code Complete, Steve McConnell discusses how most research shows no correlation with routine length and error rates – an in fact, at least one study showed that shorter routines are more prone to errors. A counterintuitive result for software quality authorities, no doubt.


Posted by
landondyer
28 November 2009 @ 6pm

The best programs I’ve read or had to maintain “tell a story.” It’s a lot like reading Hemmingway; short bits of code interspersed with high-level guidance in comments. The code is spare and lacks bells and whistles; it does what it needs to do and no more.

Using plenty of whitespace helps a lot, too.

I work on a system that does have a lot of 100 line functions. I don’t think it’s that bad; while it’d be nice to get on a “large functions are eevvvilll” warpath, I think that other qualities of code are much more important, and there are 300 line functions written by adults that are easier to read than 20 line functions written by people who just seem careless. (The “let’s make functions 5 lines long” school of thought makes my head spin whenever I get eight or ten method calls in).


Posted by
Yan
28 November 2009 @ 6pm

@Thor that is an interesting bit of research. But my post is not about error rates, but saving people’s time in maintaining your code. I think it’s still true that short routines are easier to immediately grasp, especially if the method is properly named.

@landondyer to be sure, what I’ve written is not gospel, and is not always true. But if I write a post that says “sometimes short functions are good and sometimes long ones are good” it loses all its flavor and point. You are right, nested function calls to small functions can be a pain – but I think nesting is probably a code smell in and of itself and doesn’t necessarily have to do with method length, but rather how the code is organized, and how objects are interacting with each other.

I love the “tell a story” concept, that is exactly what I meant when I said that the code should read like a recipe. Meaningful method names, and keeping things on the same order of abstraction within a method is what helps tell the story. Usually, if the story is told well you don’t need to look inside the subchapters/sub-methods to see how they work, you can read the ‘table of contents’ which is a method consisting of calls to meaningfully described methods. Conversely you can look at any submethod and understand it entirely just by its name and simplicity of its code.


Posted by
Yan
28 November 2009 @ 6pm

@Thor I also think it’s true that 5 line methods are easier to unit test than 200 line methods. Given that you are testing your code, I would expect error rates to be reduced in 5 line methods. Of course it’s possible people get lazy and don’t test the 5 line methods because they assume they can understand all the implications, whereas everyone is afraid as hell of a 200 line method so they test it really thoroughly.


Posted by
Michael Hoisie
29 November 2009 @ 2am

Great post. I definitely agree with the #4, your code should be idiomatic for the language you’re using. I’d probably suggest to seek code reviews from people who are smarter/more experienced than you.


Posted by
Abhinav Upadhyay
29 November 2009 @ 8am

Great tips!!! These are very important points and have a lot of importance in team based development.
The explanations make a lot of sense.


Posted by
Luciano Cheng
29 November 2009 @ 4pm

Yan,

Great post.

Number 5, the point about knowing the language and the framework, is a style flaw that I see constantly. Some developers will code C like Fortran, C like C++, or Java like C++, without bothering to learn how to use a language or its framework. This in turn makes the code a nightmare to extend or debug later on by others.

For point 3, to add to the discussion above, I always keep in mind is that there are several common situations where you cannot avoid long functions, such as with OpenGL routines or GUI initializations. In these situations the function might be long, but perfectly acceptable if written in a self-documenting style.


Posted by
Pranab Ghosh
4 March 2010 @ 10pm

When reading code following the call chain for some use case, if you get the same feeling as when you can’t wait to turn the next page of a well written book, you know it’s well written software. Then reading software becomes as much fun as writing.

Pranab


Posted by
Kurt
6 March 2013 @ 11am

I teach Computer Science in high school, and I just wanted to say that I’m making my students read and discuss this article. Thanks!


Posted by
yan
14 March 2013 @ 11am

Awesome Kurt! I am so glad to inspire the new generation of software craftsmen ;)


Leave a Comment

To post code, use <code></code> tag around your code