Readit News logoReadit News
Posted by u/amingilani 9 years ago
Ask HN: What are some examples of good code?
I keep reading on HN that I'm order to become a better developer I need to write code everyday, and more importantly read other people's code.

What are some examples of good code that you've seen?

Personally I'm interested in Ruby on Rails and I've recently started going through GitLab-CE[1] but what is your favor code?

[1]: https://gitlab.com/gitlab-org/gitlab-ce

runeks · 9 years ago
Writing code is really a modelling problem: you write down code that describes the model that's inside your head. When you're done, you're left with both working code on a hard drive, and a new, better model inside your head, because you understand the problem better.

So, reading someone else's code can be like reading a model of something that has gone through dozens of iterations, where the bottleneck isn't really understanding "the code", but understanding the thing that is modelled, which the people writing the code are intimately familiar with, unlike you[1].

In my opinion, developing this modelling skill, in yourself, is much more important than watching the result of someone else exercising their modelling skill. A lot can be learned from observing someone else's solution, but this will always be secondary to learning how to craft your own.

[1] For example: try reading compiler code. People have been writing compilers for so long that reading and understanding this code isn't about understanding the actual code, but about understanding how a compiler is modelled (scanning, lexing, parsing).

tumbling_stone · 9 years ago
I completely agree. I've been thinking of replicating a mid-sized project written by a programmer that I respect so that I think a lot more about the model before comparing the code.
rdtsc · 9 years ago
Not Ruby but for C code, I like Redis's code:

https://github.com/antirez/redis/tree/unstable/src

I don't personally use the product, but I find the source well written and always share it as an example of nicely done C code.

Here is some nice Erlang code I like -- network packet parsing:

https://github.com/msantos/pkt/tree/master/src

Notice how concise this is:

    codec(
       <<4:4, HL:4, ToS:8, Len:16,
       Id:16, 0:1, DF:1, MF:1, %% RFC791 states it's a MUST
       Off:13, TTL:8, P:8, Sum:16,
       SA1:8, SA2:8, SA3:8, SA4:8,
       DA1:8, DA2:8, DA3:8, DA4:8,
       Rest/binary>>
    ) when HL >= 5 -> ...
This is due to the beauty of binary pattern matching. You could kind of do it in C by casting to a struct but notice here it is also calculating header length (HL) as part of the match operation. So it can do a bit more than just casting a binary blob to a struct.

Another thing here is that it is also big endian by default so there is not need for htons(), htonl() and such functions sprinkled throughout the code.

ebbv · 9 years ago
Not disputing the code quality of either above project, but over valuing brevity / being concise is a common cause of problems. Specifically, people will often sacrifice readability and robustness for brevity.

At this point in my career I don't really value being concise at all. Which is not to say you shouldn't ever think about "Can I write less code here?" but the goal there should be writing less code to make what you're writing more robust, more stable, more readable and not just shorter.

If there's one thing I could tell every programmer early in their career (including a younger me) it would be; nobody's going to be impressed with how clever you were when they're frustrated trying to understand what the heck is going on. Including you in 6 months.

matt_wulfeck · 9 years ago
It's amazing that this is still highly debatable in our industry. Always write to make debugging easier. Always. There's so many people that worship cleverness over readability.
rdtsc · 9 years ago
There is a difference though when it is something custom and new (say if this code defined or parsed a new protocol) vs parsing an existing protocol. Notice https://tools.ietf.org/html/rfc791#section-3.1 section diagram. That code is basically an almost perfect translation of the RFC diagram, down to the bits involved. That is the beauty here: minimal impedance mismatch between the specification and code.
sealjam · 9 years ago
I am leaving my current team, in part for this very reason. Senior technical people in the organisation don't value readable, understandable code, favouring 150 character one-liners instead. It's proven to be a very effective way of increasing the time taken for anybody except the author to debug issues. In my view, this has increased the perceived value of those responsible.

I'm sure that wasn't their ultimate intention but there's certainly no incentive to change!

sudshekhar · 9 years ago
As a side, what are some good ways to start understanding the bigger projects? Blogs and documentation are helpful but mostly don't talk about the underlying implementation details.

Digging through the code line by line takes a long time and while one does learn a lot, I am sure there has to be a better way of doing this.

Any static analysis tools that help in this regard? Or any other tool/approach that you might recommend?

danbruc · 9 years ago
The Redis code doesn't look exceptionally good to me. I just looked through five files, but things like spacing and the use of braces seem to be pretty inconsistent. There are also a lot of magic numbers and quite a few variables have poor names.
bryanrasmussen · 9 years ago
I agree that things like spacing and inconsistent use of braces may cause code not to look good, but don't really feel it is a surefire indicator of the code not actually being good.
rdtsc · 9 years ago
Noticed those too, also I don't personally like camelCase in C however I still like the code because of how it is laid out and solves the problem. It has the right amount of comments (too many of those is also bad), some functions are large but overall has the a good balance there too.

Also for an example it is also the right sized project. It i not too small and not huge (like Linux kernel) and the overall structure can be understood in a few hours of browsing through.

singularity2001 · 9 years ago
#include "lzfP.h"

# define FRST(p) (((p[0]) << 8) | p[1])

ref = hslot + LZF_HSLOT_BIAS; hslot = ip - LZF_HSLOT_BIAS;

I pity all C programmers who have to deem this beautiful

exDM69 · 9 years ago
That looks clear and concise to me.

It's a part of a performance sensitive mission critical infrastructure. The parts you posted are some of the core data structures that make it fast by squeezing every bit and byte that reasonably can. There are no points awarded for being pretty.

A quick browse around Redis source code looks very clean and elegant to me. There are "hard" low level parts like the stuff you quoted (out of context) and then there are "easy" parts that implement the higher level functionality. It has a decent amount of comments.

Taking one of the "nasty" bits out of context is disingenuous. Every computer program has nasty bits and they're usually there for a reason.

Philipp__ · 9 years ago
This is perfectly fine and readable. No need to pity anyone, especially not C programmers. :)

Dead Comment

mapcars · 9 years ago
What you show in Erlang example is just a syntax. The surrounding code or usage or approach may be bad/ugly. It has nothing to do with code quality.
emodendroket · 9 years ago
This stuff about "reading code" is basically bullshit and nobody does it. http://www.gigamonkeys.com/code-reading/

> Seibel: I’m still curious about this split between what people say and what they actually do. Everyone says, “People should read code” but few people seem to actually do it. I’d be surprised if I interviewed a novelist and asked them what the last novel they had read was, and they said, “Oh, I haven’t really read a novel since I was in grad school.” Writers actually read other writers but it doesn’t seem that programmers really do, even though we say we should.

> Abelson: Yeah. You’re right. But remember, a lot of times you crud up a program to make it finally work and do all of the things that you need it to do, so there’s a lot of extraneous stuff around there that isn’t the core idea.

> Seibel: So basically you’re saying that in the end, most code isn’t worth reading?

> Abelson: Or it’s built from an initial plan or some kind of pseudocode. A lot of the code in books, they have some very cleaned-up version that doesn’t do all the stuff it needs to make it work.

OJFord · 9 years ago
> This stuff about "reading code" is basically bullshit and nobody does it.

Some guy says in an interview it's bullshit, so it is?

You never read other people's code? Not when the documentation's lacking? Not when the documentation's fine, for a framework say, but you need to see an example of how it's actually used in the context of a real application?

majewsky · 9 years ago
The implication that I get from the quote is that people don't read code for the sake of reading code.

And that matches my experience: When I read code, it's precisely because the documentation is lacking, or because I want to match up an error message produced by the code with the logic preceding the error message's origin.

emodendroket · 9 years ago
I wouldn't call Abelson just "some guy" but you obviously didn't click through and read what the article says.

Deleted Comment

Dead Comment

bandushrew · 9 years ago
The thing is, reading code is hard. Even well written code is hard to read and grok, the other kind can take days to absorb.

But it is very effective as a way of spotting certain kinds of bugs, while at the same time gaining a much deeper understanding of a codebase.

Reading code in a non trivial way is a very special skill that not many developers have, but that is very worthwhile to attain.

Whenever I come to a new codebase, I start by grabbing a pretty random bug and reading the code in that area. just flicking through, forcing myself to ask questions about it and finding out the answers.

actively engaging with code like that is an amazingly effective way of absorbing a codebase.

laumars · 9 years ago
Personally I find it easier to read code than to read an English explanation of the code. Obviously comments do help with reading code but in general it's the code that really explains things for me rather than the human description.

I suspect this might be a side effect of my dyslexia, but it's something which often works to my advantage.

sova · 9 years ago
I mean that's all definitely true but if you consider that you're trying to pick up new motifs, different ideas, and understand how people organize the thought and concept behind their code, reading another person's code is invaluable. I think the tricky part comes with looking for quality code. One should go in with an open eye looking to satisfy what you're trying to solve, and read enough to learn how to do that oneself. I don't think casual reading of code will ever be as entertaining as a novel, but if you want to get better by solving specific problems it is a great way to go.
sunir · 9 years ago
Most novelists are bad. Most devs are bad. No one seems to know how to tell they are a bad one, but I think we have a good filter: do you voraciously read other people's work?

Code in books is dumb. The real code to read is other code you use or interact with. eg reading the jquery source or the Rails source or code reviewing a colleague.

Almost always one does this while answering a question about this source. Trying to understand what a library call is doing or tracing a bug.

You learn a lot this way including coding tricks and style points.

jowiar · 9 years ago
The single most important change I've made in how I learn new tools/frameworks/whatnot is Github code searches -- I spend far more time there than on StackOverflow. Maybe this is more important in Scala land, where there are far fewer books and talks and blog posts to work from, and the tool stack is evolving a lot more, but I've found answering many questions of structure / "How do people incorporate this concept into a larger application" to live largely in code.

The answer is never exact, though. Something will have 10 different solutions, and being able to look at them and discuss the tradeoffs that went into the decision is a definite skill.

bbcbasic · 9 years ago
I read others code in code reviews, and as necessity to get the job done. I very occasionally read others code say in GitHub, but not for any desire to get better, but out of curiosity. But when I do that I get bored quickly!
yomly · 9 years ago
You've never thought "gee this is really cool software, I wonder how they implemented xyz..."?
paulsutter · 9 years ago
I'm managing a side project with four devs and I read lots of code. Since It's all performance-oriented algorithmic code, reading is the only way to know what's going on. And none of the code is crudded up. It's actually pretty nice.
emodendroket · 9 years ago
Looking at the code of a project you're working on or managing isn't really the same as just sitting down and reading code for the sake of it.
a3n · 9 years ago
You'll end up reading code if you work on code. Find something to work on. (I don't know what you should work on.)

Just like you can't really learn math just by reading the book, you'll "learn good code" much more effectively if you're working on it and you have to make decisions and judgments to move forward.

vog · 9 years ago
> You'll end up reading code if you work on code.

This.

Also, you'll have a more goal-directed path through the code, which is usually more motivating than understanding code for the sake of understanding.

Of course, there's always the pitfall that people will start making changes willy-nilly, until the code does roughly what they want, without really understanding anything.

But this will vanish as soon as you put higher quality standards to your own work. (e.g. if you want to ensure that it does the correct thing in all edge cases, or if you produce something larger than a quick hack)

emodendroket · 9 years ago
But you'll notice this is nothing like the idea of "reading code" for the sake of it.

Deleted Comment

khedoros1 · 9 years ago
I don't read code just to learn in general, but I read it to find specific undocumented details or to figure out how someone solved a particular problem. Of course, you've got to read a ton of code if you're working in a large project.

It is a great way to find new ways of doing things, and to gain experience-based opinions, but I certainly wouldn't be doing it if I didn't have a very specific goal in mind.

Tomis02 · 9 years ago
Spot on. Most of the time I can barely stand reading my own code, so how about I take a break and read some barely intelligible code written by someone else, using a different coding style and a different mindset? Wreck my brain trying to figure out what on Earth the other person was thinking when they wrote that abomination. You know, just for the kicks.
mmartinson · 9 years ago
Wrecking your brain trying to figure out what another person was thinking is a pretty fascinating way to appreciate the incredible complexity of human beings and how other minds work differently than your own.
_ix · 9 years ago
I disagree. Especially when switching from one framework or language to another, it's a great shortcut for picking up on idioms.
Ace17 · 9 years ago
I wonder what Fabien Sanglard would think of this.

To me, the Quake 1/2 source code has been an invaluable source of insight, as much for small algorithmic stuff (like collision/sliding code) than for its architecture as a whole (like game/engine separation, the edict_t system) ...

Have you never asked yourself "how did they do this" ?

dahauns · 9 years ago
While he might make a few usable points, this article is drenched in non-recognized bias. He takes his (as I see it, heavily bottom-up leaning -> 'in order to grok it I have to essentially rewrite it.') cognitive style and applies it as universal.
emodendroket · 9 years ago
Except that what led him to this point was interviewing multiple world-renowned programmers for his book "Coders at Work" and finding essentially none of them read code regularly either.
johnfn · 9 years ago
Maybe not too many people read code just to read code, but you absolutely have to read code when working on a project that's not your own, and that experience is very valuable.
tmnvix · 9 years ago
You'll find some great examples in a variety of languages on The Architecture of Open Source Applications site:

http://aosabook.org/en/index.html

rs86 · 9 years ago
This book is amazing
symisc_devel · 9 years ago
SQLite/Fossil source tree is a piece of art, practically every single function is well commented, written in clean C, easy to read. DRH has done an astonishing work. I'm impressed by his work. In my company where we do embedded C, the programming style is based on him. https://github.com/symisc/
dualogy · 9 years ago
I took a quick look recently at id software's GitHub repos of their old blockbuster games (Wolfenstein, Doom, Quake) and gotta say it was the first-ever C codebase I encountered that I found eminently readable.. (whether it's "good C", I can't assess though)
Ologn · 9 years ago
I agree, the id code is very well organized and readable.
guillaumec · 9 years ago
Doom original C sources what made me realise how simple and powerful C could be.
wayn3 · 9 years ago
Just reading the first couple replies to this thread, there seems to be some confusion regarding what code quality IS. Two broad categories:

1. Micro code quality. Looking at a single file, someone makes statements about code style - spacing, variable naming, etc. - things you would find in a style guide like PEP8.

2. Code Design. Testable code, the absence of edge cases where unnecessary (for example, turning the root of a tree into an edge case) and broader design questions; and things like correct choice of algorithm.

Code quality kind of encompasses both, but its obvious how you can be bad in one category and still be really good in the other. Really good code is good in both, but if I had to pick, I'd like to be good in category 2 first at the expense of 1. Assuming 2., 1. can be improved easily.

I'd like to say something about concise code as well. Concise code, or code that does a lot in very little lines can be treacherous. This can be fun when your team is all very senior C programmers who actually understand all this code. Then, brevity is good, but when you work in open source, or write software that has to be read by people who are inferior to you, being concise may not be the way to go.

This is almost similar to premature optimization, but not really. People who write really good C code optimize - but not prematurely. They just know that what they're doing is efficient.

bmaeser · 9 years ago
https://github.com/pallets/flask and https://github.com/kennethreitz/requests

both in python, but beautiful code, well structured and you would not need any docs, just read the code

noufalibrahim · 9 years ago
I don't want to take anything away from requests. It's an extremely useful library. However, I do a code walkthrough of various popular libraries with my students and I've never been satisfied with requests internals. The emphasis, I've felt, is more on clean, stable, public API rather than internal consistency and cleanliness. I don't pick it up these days for my classes. Instead, we usually go through the python standard library. Especially the code from Raymond Hettinger.
2bitencryption · 9 years ago
that sounds like a class I would love to take. any suggestions on what in the standard library to check out?
notamy · 9 years ago
Flask is absolutely beautiful; definitely agree with reading through it.