321 points · by amingilani · 9y ago · 162 comments
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
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).
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.
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.
This kind of brevity is extremely helpful when thinking about a problem. You "just" have to grok the mechanics thoroughly. This really helps in designing effective higher level abstractions.
Unequivocally admonishing brevity for ostensible readability kind of ignores the trade offs. I think there are other ways to bootstrap grokkability without having to sacrifice the conceptual clarity of nicely compact code.
[1]: http://www.moserware.com/2008/04/towards-moores-law-software...
I'm sure that wasn't their ultimate intention but there's certainly no incentive to change!
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?
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.
# 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
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.
What's a FRST? The actual code appears to do a LE encoding of a u16, but I can't fathom why you'd call that "FRST". But maybe in context it makes more sense.
The rest, IDK. Can't tell what an "LZF hslot bias" is. Again, might make sense in context.
> 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.
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?
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.
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.
I suspect this might be a side effect of my dyslexia, but it's something which often works to my advantage.
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.
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.
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.
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)
... if you submit your code to the project's owner. :)
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.
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" ?
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.
both in python, but beautiful code, well structured and you would not need any docs, just read the code
I used to do requests but like I said, moved away. I sometimes do pygments to discuss how different lexers etc. are "plugged" in and also to show how messy the command line parsing code there is.
This batch will probably be a little different since I'm reworking it completely. The syllabus for the first batch is here if you're interested in what we covered http://thelycaeum.in/blog/2014/06/10/mentoring_course_time_t...
https://github.com/ztellman/manifold/blob/master/src/manifol...
Also, it is fascinating to consider how Go routines were implemented as part of Clojure core. Huey Petersen wrote a fantastic analysis of how state machines were used to implement Communicating Sequential Processes:
http://hueypetersen.com/posts/2013/08/02/the-state-machines-...
You can read along while looking at the source code here:
https://github.com/clojure/core.async
This is a great implementation of Communicating Sequential Processes, first described by Tony Hoare in 1977:
https://en.wikipedia.org/wiki/Communicating_sequential_proce...
This is the same technique that Javascript/NodeJS uses to implement its async.
It's definitely not uncommon, but yes, that file is on the long side. However, it is rather clean and well-organized.
It may be due to the poor module system (header files) of C where you end up making files slightly longer than ideal because splitting into two files means also adding some header files and thus adding to the maintenance burden.
When writing C code, I usually strive to put a whole "module" in a single file, so that no "private" interfaces have to be put in header files. Everything that needs to be exposed in order to test a module goes in the public interface.
It's a tradeoff and C being C doesn't help (and C++ wouldn't really help here IMO), but I see nothing wrong with the file you picked. It's a bit long but it looks well done to my C programmer eyes.
I also see lots of prototypes (all?!) defined at the top of the file instead of in a header file. They could be made static.
Also, the generic type "int" isn't a good idea because it can change, it helps avoid porting problems to specify the size (int32_t, uint64_t, etc.)
And the memcpy()'s should be changed to memcpy_s().
On the bright side, the comments are quite good and plentiful. Refreshing!
I particularly liked Brian Kernighan's description and implementation of a regex matcher, and Travis Oliphant's discourse about multidimensional iterators in NumPy.
Worth a read.
Looking back up the talk, it points to his review of the book here: http://dtrace.org/blogs/bmc/2007/07/28/on-the-beauty-in-beau...
> More specifically: read [two specific chapters with very different attitudes on what makes code beautiful]. It seems unlikely to me that one person will come away saying that both are beautiful to them. (And I’m not talking new-agey “beautiful to someone” kind of beautiful — I’m talking the ”I want to write code like that” kind of beautiful.) This is not meant to be a value judgement on either of these chapters — just the observation that their definitions of beauty are (in my opinion, anyway) so wildly divergent as to be nearly mutually exclusive. And that’s why the title is perfect: both of these chapters are beautiful to their authors, and we can come away saying ”Hey, if it’s beautiful to you, then great.”
What I've often found is that Peter is just great at isolating the minimum required model/data structure. More often than not, when I notice his solution has half the code of mine, it's because I used the wrong model.
Additionally, I've on occasion consulted the Linux kernel and PostgreSQL repos. Would recommend, although I'm definitely either lying or very ignorant if I said I was familiar with them.
-God objects (they do everything!) and their opposites, freeloaders
-1000-line methods
-No unit tests
-Not-invented-here syndrome, otherwise known as "let's write our own array class!"
-No separation of concerns (everything mashed together)
-Not concerned with issues such as performance, maintenability and security
After you look at too much bad code (which, by the way, will include your own), you acquire a very instinctual understanding of good practices.
The counter to this is dependency hell. I oft times see developers pulling in large, new and compiled dependencies into Python projects for a single pieced of functionality just to avoid being accused of "not-invented-here".
So it won't help if you try and read it.
To paraphrase Tolstoy's quote about happy families: "All good code is alike, yet each bad code is bad in its own way".
I remember a piece of advice from some guru programmer I've read some time ago: "Don't just read the code - compile the program and try and change something in the code, maybe the window title, maybe add a menu item - something silly, but which forces you to figure out where things are done in code."
For me, at least, this helps with the act of writing the code, in addition to the act of reading it. I am not nearly smart enough to keep in mind all of the things that need to be done to write solid code. So I compensate by developing abstractions that let me forget about details, assume they're handled (for the moment) and focus on just a small part of the problem at hand. The act of writing the code in that way tends to lead to a more manageable style.
> -Not concerned with issues such as performance, maintenability and security
This is where engineering sense comes into play. I'd personally rather not pay for things I don't need, particularly if an undue focus on performance, etc. means my cost overruns my budget. Perfect is the enemy of the good, and all that...
I agree, however, making at least an effort is preferable than not caring.
What I had in mind was the developer of a legacy system at my previous work. He couldn't understand why I was fussing over performance metrics and I told him I couldn't understand how he could not. The reply was that they had enough trouble "making the bloody thing working", so anything else was peripheral.
It's in Python and a single file but it comes with a wonderful description and shows how a complicated task can be broken down into a few small and powerful functions.
It's also the reason for trying to break down larger systems into smaller, elegant components.
During the prototype phase, anything goes, speed is paramount, you just have to make it sort of work. Don't get hung up practicing pretty looking code during this phase.
You should always practice, but don't get hung up.
Prototype given the green light? Ready to dive into the build phase?
I'll say this, google for "coding style guide"
Where I see things fail a lot more is in the code equivalent of "How do I structure a paragraph" or "How do I organize this paper", which most things under the "style guide" umbrella don't cover.
I've also always insisted on including at least some loose guides to cover the "how do I structure a paragraph" cases. These generally are going to vary on a project by project basis, though, so they're going to be more vague as a rule.
Personally, I like writing code and borrowing ideas from other, better engineers. I also like my code to be clean and without cruft: https://github.com/keithb-/Valley
But I don't even know if I could "read" my code. It's a web app; there isn't a main(), there isn't a loop. In order for someone to read it, they would need to mentally "send a request" which means they need to somehow have the concepts or the context in their mind when they sit down with the source code. I just don't know how that is supposed to help an engineer, regardless of age or experience.
A tiny C-subset JIT:
https://news.ycombinator.com/item?id=8746054
It might even be controversial to suggest these are examples of "good code" today, because the majority of code I've seen lately seems to be overly verbose and complex. In contrast, these are extremely simple and concise for the amount of functionality they contain. I think this style has unfortunately disappeared over the decades of promoting lowest-common-denominator so-stupid-even-an-illiterate-could-read-it coding styles and enterprise OOP design-pattern bloat-ism, but when I think of "good code", I don't think of Enterprise Java; I think of code which, upon being told what it does, makes you think "wow, I never thought it would be so simple."
Had a ton of fun jumping around.
https://github.com/antirez/kilo
https://github.com/meetecho/janus-gateway
The obvious caveat here is that I have no idea what makes a good C codebase. What I liked in both was I was able to:
compile and run them easily
make tiny changes and observe them easily
read and understand a reasonable portion of them
enjoy the odd comment here and there
If we're talking a small application, such as a new startup, writing efficient and optimized code is hardly a concern. In this case, good code means flexible, easy-to-change code. The code must make it easy to modify existing features and add new ones.
Compare that to, say, Google's search. The feature isn't evolving much anymore, in terms of functionality, but it needs to be as efficient and optimized as possible, considering the bulk of data it needs to read through, and the immense traffic it gets every second. Sure, you still want flexible code, but speed is critical.
If we're talking an open-source project, the most important part could very well be documentation and ease-of-read. when you have dozens to hundreds of people writing new features, making optimizations, and solving bugs (in their free time and without compensation!), quality of communication takes on a new significance.
These are, of course, simplifications, and the accuracy can be debated (as these situations always have an incredible variety of factors), but the point is that "good code" is not something that can be defined in a vacuum: it can only be defined in terms of the situation at hand.
For example, you can see https://github.com/xyncro/freya-optics/blob/master/src/Freya... and can immediately see the clarity and the consistency of the writer.
My advice is actually not so much different than yours. Definitely checkout the Rails internals, but keep a reserved opinion. Then contrast it with other things. From a framework/library perspective look at Sinatra or other web frameworks that that a completely different philosophy. Try to understand the advantages and disadvantages to many approaches.
Again, I want to stress that my intent is not to be critical of Rails (heck it provides the bulk of my paycheck and I'm very grateful it exists!). My intent is really to say not to be so hung up about finding good code, but rather take a long term view of comparing different approaches and thinking through for yourself what you think is good. People who have a different view point than mine, shed light in corners that I won't look. That's always a good thing.
Have a look at underscore js source:
https://github.com/jashkenas/underscore/blob/master/undersco...
I really loved it! Especially those _ functions are small, concise and easy to understand as well. Very good codebase. (very good example of functional programming concepts)
There's an annotated version available here, which might be a little easier on the eyes: http://underscorejs.org/docs/underscore.html
Underscore's codebase has grown some warts and wrinkles over the years, as optimizations and browser edge cases find their way in ... but the guiding principle is still to keep it as svelte as we can manage.
Not only does it contain great code snippets but it also covers repeatable techniques that will ease your life as a ROR programmer immensely.
[1] http://cacm.acm.org/magazines/2008/7/5379-kode-vicious-beaut...
For things to read, these books are a little old now but I liked them . https://www.manning.com/books/the-well-grounded-rubyist-seco...
// Get a reference to the canvas
canvas = document.getElementById("canvas");
// Set the canvas size
canvas.width = 512;
canvas.height = 512;
And then missing when they could be useful (or a more clear data structure should have been used, e.g. an object with colors as keys): var colorMap = [
255,0 ,0 , // Initial symbol color
0 ,0 ,0 , // Black
255,255,255, // White
0 ,255,0 , // Green
0 ,0 ,255, // Blue
255,255,0 ,
0 ,255,255,
255,0 ,255,
];- Ruby Tapas: https://www.rubytapas.com/ - Destroy all Software: https://www.destroyallsoftware.com/screencasts/catalog - looks like it is a bit more expensive than it used to be, but there is a lot of good stuff in those first 5 seasons.
Therefore, for starters,
For scripting language such as Ruby, check out Satish Talim's Ruby tutorials (URL: http://rubylearning.com/satishtalim/tutorial.html)
For compiled language such as Java, check out a recent version of 'Big Java' from your local library.
It's been a good to refresh my memory about concurrency in Ruby, and Michael Grosser is probably the most responsive maintainer I've ever worked with. Really good reviews and suggestions on my PRs.
Reference http://www.dpdk.org and https://github.com/freebsd/pkg
Since you mentioned Ruby, start by reading Rails itself. For all the hate people have for it, I believe it really is a solid exemplar of above-average code. Reading through the ActiveRecord source just after Rails 3, and seeing the way it was semantically organized by feature via included modules, was an inspiring moment for me as a coder. It was probably the first time I'd seen code that was simultaneously practical, modular, and readable.
You should never trust people's statements about what techniques are good and bad in a language. It's called "code smell" because you can judge it for yourself without having others dictate a judgment for you. Just like you can decide for yourself whether something smells bad or good.
The same source can produce compilable code, or formatted comments.
A single file running both in python 2.7 and 3.
Nothing groundbreaking, just basic OOP code, but it was unique in that I started reading the source code and understood it quickly.
I assume that as a developer you are interested in solving (business?) problems through the act of writing software?
It isn't much different than being a painter I guess. To be able to be a good painter (or to be considered a good painter) you first need to have a good grasp on how to use the brush and how to handle paint (e.g. oil paint), i.e. you need to learn the technique. The more versed you become with the technique the better you will become at painting, or, over time you will become better at painting what you intent to paint, to paint what's in your minds-eye because you don't have to think about the brush and paint anymore.
When it comes to software you first need to have a good grasp on programming. This means you will need to spend time practising the act of programming. Using two languages that are very different from each other might be good. E.g. learn an imperative and functional language. In your case this might e.g. Ruby and Lisp. Your programs will need to interact with other systems so you probably need to learn about operating systems, databases, queues, networking, etc. You probably don't have to be an expert in everything but being a good all-rounder will certainly be beneficial.
Over time you will see that it becomes easier to think in solutions of the bat rather than focusing on how you're going to solve a problem. This is basically what is being referred to as experience.
So, to be a good developer you need to put in the effort and you need to put in the time. There usually aren't any short cuts. I've been doing this professionally for over 20 years and I'm still learning every day.
It hardly sounds like he is looking for a shortcut