310 points · by _Microft · 9y ago · 148 comments
Goal is to learn something from excellent pieces of code, much like it is practised in art by studying Old Masters, pieces of literature or musical compositions.
PS: I admit to exaggeration in the headline / first paragraph ("should have") btw ;)
Every programmer should read the (presumably open source) code they depend on, but almost nobody does it. Some look at documentation, but not everyone even does that. What you may find is that some of the code you depend on is garbage, and may even motivate improvements.
This may be less feasible for giant messes such as most front-end tooling and frameworks that exist today.
Code is a valuable gemstone covered in layers of shit. Always aim to create diamonds, not CZ, and keep at least one face of that diamond shit free.
I always thought was a very pessimistic way to view code until I landed my first job. Algorithm exercises and toy projects for capstone can be shit free diamonds every time. Working with finicky clients, legacy code bases, and peers who don't care about quality quickly proved that sometimes you're destined to make topaz double-dipped in dung.
Dependencies are no exception to this. I've worked with a mapper that works pretty well out of the box. I ran into an issue with how Strings were mapped to boolean values. It turned out the default mapping values for those conversions were yes, no, y, n, and possibly some other variation of those String values. It didn't include true and false by default.
Basically it expects a parameter along the lines of
codecommit/RepoName/branchName
And then it splits the string and if there are more than 3 items as a result it returns from the function saying invalid value.
I had to correct it to use it myself but I found it fascinating since it suddenly made the somewhat mystical innards of aws seem a little more human. At least that's how I felt :D.
Python dependencies are source code, not compiled blobs, and the import syntax makes it very explicit where definitions come from.
If I'm unsure how to do something with the library I usually look at the source of the relevant module before looking up online docs.
Has this ever been beneficial? I generally just check if a library is popular and maintained and that's always been enough for me. If the code really is horrendous nobody is going to be using it and if you always read the hundred of thousands of lines of code you depend on you'd never get anything done.
You don't want to use a data serialization library that is so poorly written that it likely corrupts stuff sooner or later, do you? Or a crypto library that documents almost nothing and requires you to review x86 assembler to find how parameters are actually interpreted cough?
Taking at least a cursory glance at the code is one part of vetting dependencies before using them. Other activities would be:
checking use of best practices ("Your parser written in K&R C is probably fine without fuzzing and any tests"),
availability of documentation ("source is there, no?"),
checking for known vulnerabilities and bugs (First open issue: "Library segfaults when parsing long lines of []{}"),
maintainership ("Last commit: 2004") and
portability ("(void*)a + (int)5.7").
Python's CPickle comes to mind. There's a race condition in there somewhere, but I've never been able to reproduce it with a small program. [1] Using the version of Pickle written in Python works.
This sort of thing is why I'm somewhat negative on the argument that "if Python is too slow, write the important parts in C". It's too easy to break Python's memory model in C code.
If it corrupts data and has terrible documentation it wouldn't be popular. It's usually very obvious from the community around the library if it's got major problems or not.
Length is an important consideration and most never consider it, partly why software is notorious for getting bloated over time. At some point it would be easier to rewrite code from scratch with less complexity and overhead.
On the other hand, McDonald's is pretty reliable and you know you're getting something palatable that is probably safe to eat (in the short term, anyway). You don't need to pick the best-in-class library for everything.
There are some rare cases where that makes sense (Keyword: RARE), but most times I've seen developers take that stance, it leads to longer development times, less consistent code, more maintenance work, and generally pretty shitty outcomes.
Popularity is ABSOLUTELY an indicator of things other than just popularity. However you need to understand why the thing is popular and vet that against your needs.
Finally: McDonalds IS good. I don't eat there often, but they provide a consistently satisfactory experience for their customers. There's a reason you can find McDonalds nearly everywhere on the planet.
It's popular to diss on companies that have become large iconic chains, but they're large iconic chains for a DAMN good reason. Plus, they're solving supply chain issues you aren't even considering, much like large popular libraries are handling use-cases and problems you don't even know about.
Can I make a better burger? Sure. Can I make a better burger for the same that McDonalds charges, as consistently as McDonalds does? Fuck no.
The same probably applies to your software.
It doesn't make it good, but it does mean that it's unlikely to make you ill.
The difference between code and a burger is that anyone can consume a burger but code is consumed almost exclusively by professionals. A better comparison would be power tools where you'll often find that if a brand is popular, it tends to make solid, long lasting products.
I don't know how helpful reading source is for determining whether or not to use a dependency, but I find it very helpful to have at least a small understanding of how my dependencies work:
1. I find it useful for debugging. If a coworker or I have used a library incorrectly, understanding how the library works can help us figure out why it isn't doing what we wanted. Also, my IDE lets me do step-through debugging through dependency code as well, which can be helpful.
2. It helps with determining the capabilities of a library. If I know how a library works, then I can make reasonable guesses about what features the library has (or could easily add). I find myself thinking, "I'd like to do X, and from what I know of how library foo works, that seems like something it should be able to do." So I can go investigate that.
3. It helps with knowing the performance characteristics of the library. Just yesterday, I needed to implement some stats logic in java. I found an Apache Commons class that does exactly what I need, but by looking at the source code, I found that it uses an O(n) algorithm, which is fine for the cases they are probably targeting. In this case, I need more performance than that, and it's not hard to write this as O(log n). So I wrote my own instead. If my IDE (Intellij) didn't give me super easy access to dependency source code, this would have been more painful.
When you review a dependency, you answer why it should not be written THIS way. (Or why it's junk and shouldn't be used.)
If you want to write secure code it's necessary. Otherwise you just end up with PHP web apps that have remotely exploitable memory corruption bugs because the developer didn't understand that he absolutely has to sanitize all user inputs to certain functions.
>If the code really is horrendous nobody is going to be using it
This just makes it pretty clear that you haven't ever looked.
Do you check the source code for Apache, MySQL, PHP etc.?
If I'm picking a library for a component where its flaws would be high impact (e.g. security) and there isn't a strong community behind that library I'm going to be very cautious though.
Statically typed languages are much more likely to be self documenting, though occasionally, with Golang for example, they will return a structure with the same name as another structure in the program, and it's hard to figure out which of these is being returned.
I am assuming you are not a database expert but basing this on the look and organization of the code and not the data structures and design. If that is not true than please share your findings instead of teasing us.
I'm curious would you do the same with your editor (or IDE)? You should see the source code for those behemoths (with the exception of the rewrites like nvim) they are pretty nasty.
Are you going to pick a different editor just because Vim or Emacs (or whatever editor) has nasty code?
Guess what IDE has pretty clean code and is extremely modularized... Eclipse. I can tell you Eclipse is not a comfortable editor (and I use it all the time because I'm used to it not because the code is elegant).
Mature projects often have pretty ugly code but they are mature and stable. Ugly code also doesn't necessarily mean poor design (e.g. if your editor is single threaded and has nice looking code its still single threaded).
I wouldn't imagine it being controversial to prefer well engineered code over less so for bits you will need to depend on.
Mysql and PostgreSQL offer similar functionality, people use both systems for similar tasks. When you try to decide between the two, you find conflicting arguments all over the web. I think in such case looking at the quality of code can be a key signal to help you make a good decision.
I do agree that projects with ugly code can still be extremely useful and in many case an optimal choice, but such project will more likely become obsolete quicker and will cause problems more often than project with high quality code.
Looking over code would give you more than just an impression of its style; it would also give you a feel for the quality of the product. If most of the code you look at is of poor quality, it is very unlikely that the product, at a high level, will be any better.
Reading this code is probably most enlightening if you have already written networking protocols.
NB: this has nothing to do with OCaml, other comparable languages with ADTs (Scala, Rust, Haskell, F#) would be similarly suitable.
[1] https://github.com/mirage/mirage-tcpip
[2] https://github.com/mirage/mirage-tcpip/blob/master/lib/tcp/s...
Don't know OCaml but am learning Rust and I see what you mean about the universality of how types make this possible.
Thanks for pointing this out.
I've been looking for something beyond basic tutorial apps to get a real feel for OCaml.
I just can't recommend it enough. All the projects are open source, so you can review the source code and still be walked through the code by book. You'd learn why the programmers made certain trade offs and how the applications became better of for it
http://fabiensanglard.net/quake2/quake2_software_renderer.ph...
http://www.ieee.org/about/ieee_code_of_conduct.pdf
ACM Code of Ethics and Professional Conduct:
https://www.acm.org/about-acm/acm-code-of-ethics-and-profess...
The later book is "Artificial Intelligence A Modern Approach" which is written with pseudocode examples. The site includes other languages than lisp; python, java, js, scala, and c#.
PAIP lisp code: http://www.norvig.com/paip/README.html
AIAMA code: https://github.com/aimacode
These are very detailed, very well written articles from well-acknowledged developers about their OSS project.
Plenty of tricks to be learned there, as well as fantastic structure.
Is a hashlife by him on the web? The first page of google results only turned up an older comment by you.
Grr, nope :( That sucks.
Ok, so try this instead:
Not quite as satisfying but it gives you the general idea, his whole approach is elegant and super direct.
Realistically this is because it is in fact a big messy pile of 'at least it works'.
Still, it is worth studying as an example of a work that was architected to support open source contribution from thousands of developers.
I have contributed to device drivers a few times, for example. And I wouldn't really recommend this part of Linux for learning. Maybe they work but code readability is often neglected and it's not unusual to see whole functions without a single line of comment or files/modules without even a short explanation of what they are trying to achieve.
Maybe the core is better.
For anyone wondering why this is, here is a good explanation.[2]
[1]:https://www.libav.org/ [2]:http://blog.pkh.me/p/13-the-ffmpeg-libav-situation.html
Fang is a utility program for UNIVAC 1108 computers, written in 1972. UNIVAC's EXEC 8 had threads and async I/O for user programs, decades before UNIX. The machines were shared-memory multiprocessors. FANG uses those capabilities to parallelize copying jobs. The UNIVAC mainframes had plenty of I/O parallelism and many I/O devices, so this was a significant performance win.
See especially "schprocs". Those are the classic primitives from Dijkstra: P, V, and bounded buffers. That technology predates Go by 40 years. Here's Dijkstra's P function:
.
.
. DIJKSTRA P FUNCTION
.
.
. LA,U A0,<QUEUE>
. LMJ X11,P
. <RETURN> X5 DESTROYED
.
P* TS QHEAD,A0 LOCK THE QUEUE
LX X5,QN,A0 LOAD QUEUE COUNT (note: load)
ANX,U X5,1 BACK UP THE COUNT (note: Add Negative, i.e. subtract)
SX X5,QN,A0 REPLACE THE COUNT IN THE QUEUE (note: store)
TN X5 DO WE NEED TO DEACTIVATE HIM ? (note: Test Negative)
J PDONE NO. SKIP DEACTIVATION (note: Jump, i.e. branch)
ON TSQ=0 (note: this is an assembly-time ifdef)
LX X5,QHL,A0 LOAD BACK LINK OF QUEUE
SX X5,QHL,X4 PUT INTO BACK LINK OF ACTIVITY
SX X4,QFL,X5 CHAIN ACTIVITY TO LAST ACTIVITY
SA A0,QFL,X4 CHAIN HEAD TO NEW ACTIVITY
SX X4,QHL,A0 MAKE THE NEW ACTIVITY LAST ON QUEUE
CTS QHEAD,A0 RELEASE PROTECTION ON QUEUE HEAD
SCHDACT* DACT$ . DEACTIVATE PROCESS (note: system call)
OFF
ON TSQ (note: for later version of OS with alt wait fn)
C$TSQ QHEAD,A0 WAIT FOR C$TSA (note: system call)
OFF
J 0,X11 RETURN AFTER ACTIVATION
.
PDONE CTS QHEAD,A0 UNLOCK THE QUEUE (note: not a system call, just a macro. Stores 0.)
J 0,X11 RETURN
(Notes:Instruction format is
OPERATOR REG,OFFSET,INDEXREG
The "TS" instruction is "Test and Set". That's atomic. If the flag is already set, an interrupt occurs and the OS does a
thread switch. CTS just clears the flag. Later versions of the
OS support C$TSQ and C$TSA, where the OS queues waiting test
and set operations.X4 is the "switch list", the local data for the thread.)
In that regard Donald Knuth's work in the fictional assembler MIX for TAOCP is worth reading - it's at one remove from any real system. Knuth's TeX source is also quite unique.
Typically if I don't know how to solve a problem / use a library, I'll go onto github and search out projects either by their dependencies or structures I know must be present in the code I want. Then I'll pick out 20-30 projects and compare and contrast. Funnily enough, I read most all of the source code to Etsy's 'Artsy' iPhone app because I wanted to get a sense of how a professional shop structured their iPhone code.
As for the understanding the code, the author is very correct in that it's tough to implicitly understand what's happening in the code. But to that point I use Reveal to peek inside iPhone apps, or node-nightly + chrome devtools to walk through js code. Since my goal isn't to understand the whole of a program, rather parts I'm interested in, it's worked out quite well.
I've always wanted to read code for very secure applications (like Signal or SecureDrop), but I fear I don't understand crypto/infosec enough to understand the context the code was written in.
We should read source code sometimes (maybe) to deepen an understanding of how someone might think about the problem differently. In the link, Donald Knuth says he enjoyed the challenge of exploring a piece of software that had no documentation in order to figure it out.
In light of this, my answer to "what code should people read" is that you should read (really, decode) the source code of libraries competing to solve the same problem. This would lead to the greatest yield in terms of uncovering core shared concepts and core unique concepts.
You could compare Vue and React to understand how two different parties thought about componentizing the front-end. Or you could compare Django and Flask to see how a batteries-included MVC framework compares to a lighter alternative.
Not to sound pedantic, but did you mean "While you're at it:"?
One source code I look into from time to time is Three.js: https://github.com/mrdoob/three.js/ to discover more details over the documentation.
https://en.wikipedia.org/wiki/Fast_inverse_square_root#Overv...
https://hg.icculus.org/icculus/lugaru/file/97b303e79826/Sour...
Even if you hate c#/java an amazing book on how to write solid clean code.