Lurker News
I am rather fond of the concepts described in "Clean Code" by Robert Martin but it seems that in real life, a really high-quality codebase is hard to come by.

While I am asking myself this question, the only one that popups to my mind would be Laravel: https://github.com/laravel/laravel (PHP)
One could think that a codebase as popular as React (https://github.com/facebook/react) would be a perfect example of "clean code" but with a glance, I personally don't find it very expressive.
This may all be very subjective but I would love to see examples of codebases that member of this community have enjoyed working with

Comments (269) 82 threads

Earlier comments
jihadjihad2 replies#
For canonical C code, without a doubt I would say Redis and Postgres. Redis is written and annotated in a way that even someone with a cursory knowledge of C can understand what's going on.

For Python, I really like how SQLAlchemy is written and designed.
For Rust, ripgrep stands out as a sterling example of how to write a powerful low-level utility like that.

dataflow2 replies#
I just opened up server.c in Redis (not familiar with Redis and never seen it before) and at first glance it seems... alright, but I'm not sure what's particularly outstanding about it, and it could definitely be better. Some of the logic seems questionable (exit() in a signal handler? [9] also what about thread safety?), and more superficially (but annoyingly) I see: names like "sdscatprintf" [1] which are a little cryptic, lack of attention to spacing (too little [2] or too much [3] or inconsistent [4] [8]), lack of braces for single-line blocks (which at least I consider bad) [5], irritatingly inconsistent line breaks [6], etc.

Overall it's still definitely on the more readable side compared to other C code I've seen, I like the thorough comments, and it's generally decent, but I'm not particularly coming away from it in awe like everyone else seems to have.
[1] https://github.com/antirez/redis/blob/unstable/src/server.c#...
[2] https://github.com/antirez/redis/blob/unstable/src/server.c#...
[3] https://github.com/antirez/redis/blob/unstable/src/server.c#...
[4] https://github.com/antirez/redis/blob/unstable/src/server.c#...
[5] https://github.com/antirez/redis/blob/unstable/src/server.c#...
[6] https://github.com/antirez/redis/blob/unstable/src/server.c#...
[7] https://github.com/antirez/redis/blob/unstable/src/server.c#...
[8] https://github.com/antirez/redis/blob/unstable/src/server.c#...
[9] https://github.com/antirez/redis/blob/unstable/src/server.c#...

MiroF#
sdscatprintf is just mimicking the C style for a lot of string manipulation functions that have -printf suffixed. My guess would be the function just concatenates the data onto some sort of "SDS" string
antirez1 reply#
Redis code quality could be improved significantly, but you picked the wrong file to evaluate it: the first file created, and the one that for the nature of system software will be the less "overall designed", because it is the place where we call almost everything else sequentially. Still, if I had more time, I could improve it and other parts a lot. However to see how modern Redis was coded check the following:

* hyperloglog.c
* rax.c
* acl.c (unstable branch, the Github default)
* even cluster.c
Everything you'll pick will likely be a lot better than server.c
Other things you mentioned are a matter of taste. For instance things like:

    if (foo) bar();
Is my personal taste and I enforce it everywhere I can inside the Redis code, even modifying PRs received.

The line breaks are to stay under 80 cols. And so forth. A lot of the things you mentioned about the "style" are actually intentional. The weakness of server.c is in the overall design because it is the part of Redis that evolved by "summing" stuff into it in the course of 10 years, without ever getting a refactoring for some reason (it is one of the places where you usually don't have bugs or alike).

mehrdadn#
Ah I see. I didn't realize it was old, I just picked server.c since it just sounded like it'd have a decent mix of stuff. I think the only 'taste' things I mentioned is the lack of braces and possibly the function name, which I'm happy to ignore. But the rest were just inconsistencies, regardless of which way anyone's tastes lean -- the spaces after commas are entirely inconsistent (although I would argue if you took the stance that there shouldn't be a space at all, that's bordering on just being wrong, not merely a matter of taste!), and some lines are far longer than 80 columns [1] and some are broken at really inconvenient points just to fit them into 80 columns, which gets you the worst of both worlds.

Thankfully, like you said, the other files do seem better. :) However, they do have the same problems I just pointed out above: spaces are inconsistent everywhere (after commas, after 'while', after casts, etc.) and lacking in awful places (honestly, how am I supposed to read a function call with eight identifiers and zero spaces? [2]) and some lines are broken and others longer than 80 [3][4].
A couple other immediate issues I have on syntactic things (semantic analysis would take me a long time so it's hard to give me feedback on that):
- One comment I have that some others would vehemently disagree with me on is: I would cut down on the early returns. Personally, I really hate them, for multiple reasons -- the most practical one of which is that they prevent you from inserting a single breakpoint in a debugger (or printf(), or whatever you feel like doing) and being able to see what the function returns easily. Instead, you have to hunt through the entire function and place a dozen breakpoints to make sure you didn't miss any return path. And it becomes the most confusing thing in the world when you inevitably miss one. To me that's bad enough, but some people still insist on them. But if you're going to do that, I would at least make it easier for people to debug them. On my first reading, for example, I completely missed the return on line [5] -- because it's right after the if condition and visually blends in. That also makes it hard if not impossible to put a breakpoint on it, which wouldn't be an issue if it were on a separate line. (Maybe you don't do that because you don't want to forget braces, but you know my opinion on that too. :P) That makes it even more painful to debug this function.
- I'm not a fan of the liberal macro usage. I'm not saying you should never use macros -- I know that sometimes it's outright impossible not to (especially in C), and sometimes they're the perfect tool (code deduplication) -- but you shouldn't be using them to use them to define constants and perform normal function calls. [6] [7] Not only is it often possible to break them because of their textual nature, and not only do they lack type information that would be extremely useful, but they also make it harder to debug, since you can't just type them into a debugger at runtime and get their values. And you can't step through them like normal code either.
Hope some of this is helpful. All of it said though, they're pretty minor things overall, and the code does seem good quality, at least as far as I can tell in in this timespan. The fact that it's in C does always leave me with this nagging feeling that there's always going to be some resource leak somewhere (especially with early returns!), which I wouldn't have in most other languages, but that's not really an indictment of the code but of the language. And I love, love, love the comments. I don't leave comments nearly that good myself, and I will almost certainly refer back to them later.
[1] https://github.com/antirez/redis/blob/583933e2d6b4c2721554ab...
[2] https://github.com/antirez/redis/blob/unstable/src/rax.c#L10...
[3] https://github.com/antirez/redis/blob/unstable/src/rax.c#L50...
[4] https://github.com/antirez/redis/blob/unstable/src/rax.c#L45...
[5] https://github.com/antirez/redis/blob/unstable/src/rax.c#L13...
[6] https://github.com/antirez/redis/blob/unstable/src/hyperlogl...
[7] https://github.com/antirez/redis/blob/unstable/src/quicklist...

massimo-nazaria#
> Redis is written and annotated in a way that even someone with a cursory knowledge of C can understand what's going on.

Strongly agree with this one about Redis.

rsweeney215 replies#
The Windows operating system.

Windows is quite an engineering achievement. We didn't prioritize readability or "clean code". All the variables used hungarian notation, so you had horrible names like lpszFileName (lpsz = long pointer to a zero terminated string) or hwndSaveButton (window handle). You also had super long if(SUCCEEDED(hr)) chains that looked like your code was spilling down a staircase. Oh yeah, and pidls (pronounced "piddles" and short for "pointer to an id list") used for file operations.
What made the code base beautiful was the extreme lengths we went to to be fast and keep 3rd party software working. WndProcs seem clunky, but they are elegant in their own way and blazingly fast. All throughout the code base you would find stuff like "If application = Corel Draw, don't actually free the memory for this window handle because Corel uses it after sending a WM_DESTROY message."
The fact that thousands of people worked on the code base was mind boggling.

cryptica3 replies#
The Windows API was very ugly... not to mention unnecessarily complicated. It does not belong in this thread.
holy_city1 reply#
Personally, COM gives me the heebie-jeebies. I get why it exists and think it's a cool idea. Under the hood it's just RTTI across shared library boundaries, and it's cool that it "just works" with the way that compilers generate vtables from pure virtual base classes.

But hell did it take me awhile to figure out how that worked because it's so poorly documented and auto-magical. Reverse engineering a COM DLL just to find out how the hell it has a stable ABI is not fun.

inlined1 reply#
Also the whole point of COM was interface composition which led to the diamond problem (multiple inheritance) in any real C++ object that implemented two interfaces (which each had to inherit IUnknown if all implementations were to be COM compatible). Virtual inheritance was a hack fix to a platform whose primary language fought its primary purpose.

Continue this thread — 1 reply

mehrdadn#
Some parts are ugly, some are beautiful. You can't really lump it into one bucket.
c-smile3 replies#
I have quite opposite opinion backed by real life experience.

As an author of Sciter Engine that works on Windows, MacOS and Linux/GTK I have first hand experience working with all three API sets.
Windows API is the most logical, complete and stable API among all others.
It has everything that you really need to create performant and manageable UI.
MacOS is good but less good. It uses reference counting (which is not bad by itself) but in very strange manner. Name of the function determines need of [obj retain] / [obj release] and not all names that they use are consistent in that respect. Yet Apple changes API quite frequently and dramatically.
GTK, while is built on top of quite reliable Glib foundation is a mess to be honest. You have GtkWindow and GdkWindow, you have gtk_window_resize(), gtk_window_set_default_size() and 6 more functions that should allow to set size of the window but they may or may not work in particular situations.

tempguy99991 reply#
IIRC there were three different kinds of handles, the documentation was a crock, the api did minimal checking, it was horrible. Fast maybe, but delphi succeeded so well because it hid all the awfulness. MS just didn't get it for years.

Continue this thread — 1 reply

mehrdadn#
> GTK, while is built on top of quite reliable Glib foundation is a mess to be honest. You have GtkWindow and GdkWindow, you have gtk_window_resize(), gtk_window_set_default_size() and 6 more functions that should allow to set size of the window but they may or may not work in particular situations.

You know, even as a guy who loves Windows, this example makes my head explode. We have MoveWindow, SetWindowPos, SetWindowPlacement, DeferWindowPos, ShowWindow, ShowWindowAsync etc. all of which overlap in functionality. Similarly SetActiveWindow and SetForegroundWindow, etc...

astrange3 replies#
macOS has had automatic retain counting for the last decade. You have to remember your weak/strong for cycles but that's all.

It's preferable over garbage collection because there are no unexpected pauses/memory scans and it's deterministic.

Continue this thread — 3 replies

criddell#
The number of cycles that have been wasted checking for Corel Draw must be astounding. I wonder if an environmental cost could be calculated for something like that.
tempguy99993 replies#
I'm mega curious about this

> ...like lpszFileName (lpsz = long pointer to a zero terminated string)
I remember those.
AIUI hungarian gives you some kind of typing. The typing is done by humans using the names. The humans have to get it right; they are the typecheckers.
The first thing I'd do is offload the typechecking onto an automatic framework - the idea of letting people do a computer's job is madness. It would not have been too hard to do (relatively very cheap for a large codebase like an OS), I think, and would have allowed the hungarian prefixes to be dropped because they'd become redundant, and strengthened and speeded up typechecking. So where is the flaw in my thinking?
(aside: one of my first contract jobs was working in pascal (delphi actually). The company I worked for had coding standards cos you need standards, don't you. It was to prefix every integer with i_, every float with f_, every int array with ai_, et cetera. As pascal was strongly typed this was totally pointless).

tempguy99991 reply#
Would whoever downvoted this please explain why. I laid out my thoughts for critiquing by others, but learn nothing unless I'm told why it's wrong.
inlined#
I’ll save you with an upvote. Hungarian notation also helps avoid collisions that lead to confusingly similar names:

pArray (array pointer) ecArray (element count of array) bcArray (byte count of the full array)

MagnumOpus2 replies#
> So where is the flaw in my thinking

The codebase has 34 years worth of code written already, 100 million LOC or more if you count Office, VS etc. The cost of typechecking is trivial but the cost of rewriting this much code to be consistent with any new convention is in the hundreds of millions of dollars. This legacy cost then of course becomes higher every year...

inlined#
I’ll do it for only 50 million dollars. Remove it with repeated regexes like s/^wec//g (remove all word prefixes for element counts). Of course, you’ll need another convention for all the collisions that Hungarian notation fixes like IFoo (Foo’s test fake-able interface) and CFoo (the concrete class)
tempguy9999#
Oh hell. Where did I say anything about it having to be rewritten? I did not. I said "allowed the hungarian prefixes to be dropped", not required. And all I meant was "in subsequent work", of course changing existing code would be idiotic.

And this absolutely misses the vital point that typechecking can be offloaded from the human to an automated typechecker, so why wasn't it?
"The cost of typechecking is trivial" - not if it's done by humans.

breck#
I once tried to add a feature to Windows (back in the sd days), and it was a nightmare. I was in the C&E org so it was a side project thing, and I eventually postponed it (but then left MS so never got it finished). I imagine it's gotten much better since then, in large part from the shift to git alone. It certainly was super impressive feat for the shear scale and longevity. I have a lot of respect for the folks who make that beast work. And there are bits of it that are brilliant. But it was an ugly beast.
inlined#
I worked on Windows for 3.5 years and hated most the code I touched:

1. I think I counted 5 string implementations in active use and code at the boundary had to convert between them all.
2. The SUCCEEDED macro is a mask against HRESULT but who the hell actually uses non-zero HRESULTS to communicate domain-specific success codes? And don’t forget that posix APIs return 0-for-non-error ints and COM APIs can use S_TRUE (0 to be a non-error) and S_FALSE (1) so you have to flip them for real bools. Or have if (bResult == S_TRUE)
3. Nobody wanted to touch old codebases. I fixed an assert in Trident layout code because a whole library used upper-left, lower-right input (and params called ul, lr) but one function (contrary to docs) used upper-left, width, & height. When I fixed the library and 2/3 call sites I was called arrogant, to revert changes in the library, and change the last 1/3 to also have the inverse bug in its call-site.
4. Another Trident API (written by an intern) had a tree where fastInsert() could only be called after slowLookup() but nothing in the api enforces this
5. Every COM object decides whether it’s faster or thread-safe by whether the refcount uses atomic ops or just —/++
6. Saw parallel arrays in files where a struct held an object which might have suffered the slicing problem in insert. Another struct field held an into the index of the sliced part array. Users rehydrated. This wouldn’t happen with an object pointer, but indirection was unacceptable because the author didn’t trust the small allocation heap’s locality.
7. My codebase included a while c++ runtime because my core-OS team didn’t trust msvcrt.dll because the shell team wrote it.

sea6ear1 reply#
I really liked the Go standard library (or at least from around 1.4-ish, it might have gotten more complicated now).

I liked that it was actually possible to read it and understand what was going on.
In a similar vein, P. J. Plauger's version of the The Standard C Library is nice because even if it might not be especially optimized(?), you can actually read the code and understand the concepts that the standard library is based on.
Software Tools by Kernighan and Plauger would also be great except that you have to translate from the RatFor dialect of Fortran or Pascal to use the code examples.
Even so, I used its implementation of Ed, to create a partial clone in PowerShell that let me do remote file editing on Windows via Powershell when that was the only access that was available.
So even over 4 decades and various operating systems removed, there are still concepts in there that are useful.
Jonesforth is also a great and mind blowing code base although I'm not sure where the canonical repository is currently.

quadcore5 replies#
it seems that in real life, a really high-quality codebase is hard to come by

I think a common misconception amongst mid-experienced programmers is that they confuse look with quality. Reading clean written code gives you a feeling of control and also the feeling that someone must have thought about that program. It's reassuring. You have in front of you a code that gives you trust.
When in fact, that code can be complete garbage.
The look of the code doesn't matter, what matters is the program. In the abstract meaning of the term. You don't judge a code by reading it, but by running it in your head. Granted you have to understand it in order to do that. Once you understand the code, you run it in your head and that's when quality enter the scene because running it in your head is what you do all day when you code. Some says that you spend most of your time reading code. That's simply not true, the effort is definitely not in reading but in running the code in your head. Basically what I'm describing is a 2 by 2 matrix where there is one column for look bad, one for look good, one row for runs badly in the head and one for run smoothly in the head. Granted, the best may be when both the code looks right and runs right, but don't be mistaken, the real important and difficult part is whether or not it runs well in the head.
A poor quality program may look good, but don't run well in the head. It's too complex or too confusing (in terms of logic, not in terms of presentation) or convoluted or simply wrong in terms of what it's supposed to do. On the other hand good quality code is code that surprises you by the way it runs. It's beautiful in terms of simplicity, it delivers a lot, it's small so that it fits well in the coder's head. And it may look like garbage which is not so important.
You may wonder how to know very quickly the quality of a code base. Run part of it in your head. Contemplate the machinery. Try not to think to much about the language and how it's constructed in this language, try instead to contemplate it in an abstract manner. Be critic, and critic your critics.

Yajirobe#
dont u mean a 2x2 matrix
Izkata3 replies#
> by running it in your head.

I have encountered far too many people who don't even realize this is a thing. I figure they must be doing it in some limited form and just aren't recognizing it as a skill that can be trained up, otherwise I'm not sure how they can do any development, but...

penguat#
I don't always run the code in my head exactly - i do something more important, which is consider the set of possible situations the code can be in, and look for problems.
fiddlerwoaroof#
I generally intentionally avoid running the program in my head because that requires too much context: I prefer to think about the change I want to make and the minimal set of preconditions that make the change valid.
ThisIs_MyName1 reply#
Running non-trivial code in your head is far too tedious for daily use. I'd much rather add debug checks for invariants when I want to confirm that the code works the way I expect it to.
AtlasBarfed1 reply#
The human brain has, what, about 7 registers in medium term memory?

Continue this thread — 1 reply

namelosw#
> by running it in your head

This is probably related to a factor named 'local reasoning', procedural programing tried to encourage this through procedure, OO tried to encourage this through encapsulation, and FP encourage this through purity.
Basically the goal is when anyone look into a function, the reader can easily make sense of the code without moving around.
For pure functional programming, to make sense of a function is to make sense of the branch under the acyclic calling tree of the function. The caller and sibling branches are always completely irrelevant.
So that it will be much easier to run in people's head.

dfischer#
I love this description. Thank you.
0mbre1 reply#
I'd be curious to see an example of code that looks bad but yet is easy to grasp mentally. I do think these 2 features that you describe "easy to run mentally" and "look good" are correlated.
quadcore#
At least, I may agree with the following: bad program infers bad presentation but bad presentation does not infer bad program.

In my career, I've seen many times peer programmers laugh at me when looking at my code and subsequently keep laughing, but in the other direction, as we were rolling over our competitors. Once, at a FANG, I've had the perfect setup where our team was doing the same project than another team. We did it in 12 month with 8 people, it took them 4 years with 18. Both projects started from scratch.
Follows an example of code of my own. This is the perfect example because it looks like complete utter garbage and you will think I'm a beginner and I've never seen any good designed code. You are gonna laugh. While it is certainly not flawless, I'm pretty sure you would like to be on my team with that code if you'd knew more. All the features, to the tiniest nice subtlety are there, it has almost no bug and it's dead simple. Really dead simple. Please note that I code with sublime text which has multi cursor making duplicated code not so bad. So there is a lot of duplicated code. Again, I'm not saying the following code is flawless, I'm saying that despite its flaws, or even because of them, from my experience you'd prefer to be in my team.
https://github.com/IndieRobert/example_code/blob/master/src/...

Load more comments