6 ms·
Ask HN: What's a small example of some of the best code ever written?
I want to be able to hold some smallish number of lines of code and say "it is generally agreed that this code is amongst the best examples of programming that there is".
Does anyone have any suggestions for such examples? Any language is fine. As long as there's some way to say "look, here is where people say this is great code".
- theflyingelvis 4y ago10 print “hello world”
- belltaco 4y ago"Best" is relative, but here's an example of "clever" code that actually shipped in a very popular game, it's just 8 lines. https://betterexplained.com/articles/understanding-quakes-fast-inverse-square-root/ https://betterexplained.com/articles/understanding-quakes-fa... Also a lot of 4k demo scene have some great looking videos rendered purely by a small amount of code. https://en.wikipedia.org/wiki/Demoscene https://en.wikipedia.org/wiki/Demoscene https://www.youtube.com/watch?v=W58r7oycUrA https://www.youtube.com/watch?v=W58r7oycUrA
- comprambler 4y agoWhat the demoscene have been able to do with 8088 based (4.77mhz) systems is crazy: https://m.youtube.com/watch?v=-xJZ9I4iqg8 https://m.youtube.com/watch?v=-xJZ9I4iqg8
- ozten 4y agoAlan Kay has famously cited the half page of code on page 13 of the Lisp 1.5 manual as the "Maxwell's Equations of Software" https://www.gnu.org/software/mes/manual/html_node/LISP-as-Maxwell_0027s-Equations-of-Software.html https://www.gnu.org/software/mes/manual/html_node/LISP-as-Ma...
- p-e-w 4y agoThat's extremely clever code, yes, and the implementation is "elegant" in the sense that it compresses a concept down to its essence, and casts that essence in code, using a language that is uniquely suited to expressing the structure of the underlying idea. It's terrible code from a software engineering perspective though. The readability is roughly that of x86 Assembly. The density obfuscates what is actually happening. If someone opened a pull request containing one of these function implementations, I would probably assume they're trying to insert a backdoor somehow. Either way, I'd never accept code like this. Great code is simple and clear in a human sense, not just minimal in a conceptual or computational sense.
- WheelsAtLarge 4y ago"Great code is simple and clear in a human sense, not just minimal in a conceptual or computational sense." Old time programmers can't get past the low resources of old systems so they continue to prefer clever and tight code over simple and clear code. Last I was in school many of my teachers preferred clever code so that's the coding style we strived to copy. I suspect that's still the gold standard. But I agree, simple and clear in a human sense, is much better. Specially in a team environment where we need to read other's code. Having to explain your code is just wasted effort and time.
- wanderingstan 4y agoAs an old time programmer myself, I anecdotally notice that junior developers seem more prone to use dense/clever code, while more experienced devs prefer clear and easy to maintain code.
- waste_monk 4y agoThey're probably being taught by academics who were adapted to the old school low-resource style of programming, and have been out of industry long enough that they never adapted to modern best practice. And assignments tend to praise cleverness over readability and long-term maintainability, because who cares if it's read-only code when your assignment only spans a few weeks and then never matters again - you just need to impress the professor (or TA who does the actual grading) and move on. The university system does sometimes result in students having strange ideas that are a bit divorced from industry best practices (and in some cases reality), due to the attitudes of their teachers rubbing off on them. I had one professor who continually insisted we were on the verge of a major resurgence of semantic web technologies and strict XHTML, and a friend who took a dev tools course (mostly focusing on git, makefiles, etc.) and was told tools like Maven would never take off and you're better off managing dependencies by hand (this was around ~2017). I don't want to be harsh on academics / the tertiary education system in general, but I think it's kind of an unavoidable consequence. Maybe "boot camp" students fare better?
- hoofhearted 4y agoI believe this is an early proof of Stripe. You could charge a credit card with just 7 lines of code. https://github.com/benweissmann/dev-payments https://github.com/benweissmann/dev-payments
- solardev 4y agoDoesn't this just use their "stripe" lib to do the heavy lifting...?
- bitwidget 4y agoprint("Hello World") /s But I've heard good things about the Fast Inverse Square Root Calculation algorithm in the Doom 3 source code. https://www.youtube.com/watch?v=p8u_k2LIZyo https://www.youtube.com/watch?v=p8u_k2LIZyo
- verdverm 4y agoWe have a small bash script to retry commands if they fail, mainly used in CI. It may not fit the typical version of "best" but it saves uncountable numbers of hours and frustration when builds fail because 3rd party services return flakey errors.
- mmillin 4y agoOne of my favorites is Peter Norvig's spelling corrector in less than 30 lines of python https://norvig.com/spell-correct.html https://norvig.com/spell-correct.html
- bmitc 4y agoIt may just be me, but I find Python nearly unreadable at times. Everything is just so ... slippery? Is this well written? w for w in words if w in WORDS There's just two concepts there, w and words, doing a whole lot. I mean, that's literally a filter, but Python refuses to embrace these things because they're supposedly confusing or hard. In F#, that would be: List.filter (fun word -> List.contains word WORDS) words I would of course rename WORDS and words to be something distinct rather than just differ by capitalization. The Python is confusing because the way to trace this comprehension is by starting with the w in the middle, then the w at the end, and then the w at the beginning (i.e., 2-3-1 sequence). Also, I highly dislike using lines of code as some sort of ultimate measurement. The program is what it is, and then requires a page 5 times the length of the program to explain the program. The program should be clearer or more comments added to it or both. The program also uses Python's "feature" of evaluating default arguments once when the function is defined as a sort of global variable, because the P function is never used by passing in a value for N. Seems clever, which is the problem with it. Lastly, function names should be more clear. "known", "P", and honestly the others are not good function names.
- p-e-w 4y agoI much prefer the Python code here. The only confusing part is `words` and `WORDS` being used as identifiers, with different semantics. Other than that, the list comprehension syntax looks both clean and clear.
- seanhunter 4y agopython has a built-in filter() that works exactly as your List.filter does. It's possible Peter Norvig just prefers list comprehensions, but it's not a weakness of the language or whether the Python community embraces filters per se. filter(lambda x: x in WORDS, words) would I think do pretty much the same as what he wrote, and then depending on how you use the output, you may want to wrap that in list() or something. If you are going to iterate over it, it's gtg as-is. There are much more idiomatic and clear (imo) ways of definining a function-static block (which gets evaluated just the first-time a function is called) than that default arg trick.
- gaze 4y agoIt's a simple one but freebsd's <sys/queue.h> is short, well designed, and really useful.
- MikeOfAu 4y agoThe InterViews library, written by John Vlissides, was for writing GUIs in C++ under X11. It came out in the early 90s. (Yes, I'm an ancient programmer) He was one of the Gang of Four who wrote Design Patterns, but he wrote this library years before the book came out. It always seemed to me that he invented all the main patterns in the Interviews library before they were subsequently (nicely!) documented in the book (which went on to become a smash hit). I've since realised that I much prefer functional programming (Clojure!) over OO, BUT, oh my goodness, what a truly groundbreaking and beautiful bit of work it was for its time. I read every line of code in that library, and I became a much better programmer for it.
- AtlasBarfed 4y agoHow many amazing GUI libraries and codebases have been discarded over the years? So much wasted human-centuries of software labor. I think of things like the PowerBuilder datawindow widget, something that HTML+JS couldn't touch for 15 years until I started to see things like ExtJS and jquery. And it ran on 486s and pentiums. As for the original question, practically all the superuseful UNIX utils that had to be performant on ancient MHz-class hardware is amazing stuff.
- akkartik 4y agoI kinda dislike the premise of your question, but https://www.amazon.com/Beautiful-Code-Leading-Programmers-Practice/dp/0596510047 https://www.amazon.com/Beautiful-Code-Leading-Programmers-Pr... has some good candidates. Chapter 1 for example is a regular expression matcher that appeared on HN recently: https://news.ycombinator.com/item?id=32589311 https://news.ycombinator.com/item?id=32589311
- sslayer 4y agoThe best code is code that is never written.
- nuc1e0n 4y agoAin't that the truth. But the absence of something is not something that can be shown easily.
- jfghi 4y agoI like sqlite although technically there’s quite a bit of code there. But overall it seems pretty straightforward to determine what does what and why.
- nuc1e0n 4y agoYeah SQLite's code is pretty good
- _8j50 4y agoI am not a programmer by profession but some of the data structure code in Linux I really liked and thought it was the best implementation I have seeen: https://github.com/torvalds/linux/blob/master/include/linux/list.h https://github.com/torvalds/linux/blob/master/include/linux/...
- accountinhn 4y agoFor me the EICAR Antimalware test file, simple 68bytes, does something elegant. https://www.eicar.org/download-anti-malware-testfile/ https://www.eicar.org/download-anti-malware-testfile/
- bmitc 4y agoHonestly, I've never seen a codebase that has blown me away (including my own). The GLFW project is very well documented for users of the API, and the code looks pretty clean. GLFW has impressed me because it makes something very complex just work and the documentation is really top notch. When I've peaked inside the F# and Elixir codebases (the codebases of the language itself), things look pretty good.
- seanhunter 4y agoI remember being truly shocked when I first read the source code to Dan Bernstein's qmail and djbdns. I had been programming in C forever at that point, but it was so different to anything I had seen before it was a real paradigm shift. Extremely idiosyncratic, but rich with ideas for ways to make software more reliable and secure. For example, because old-school C strings are the source of so many bugs, he created his own string library (stralloc[1]) which was incredibly straightforward to understand and use and avoided all the many many footguns that C strings are prone to. [1] https://cr.yp.to/lib/stralloc.html https://cr.yp.to/lib/stralloc.html
- deleted 4y ago[deleted]
- hyperman1 4y agoI'd say: Hello world. And not as a joke, as someone below dud. The C 'Hello, world!' program documented the style of a whole programming language in 5 lines of code. Every computer engineer who sees it can now recognize C code. Even non -programmers understand vaguely what's going on. Just about every programming language today starts with the same example. That's how wildly succesfull it became as demo.
- abrudz 4y agoFrom http://archive.vector.org.uk/art10500390 http://archive.vector.org.uk/art10500390 In the year 2033 Earth was discovered by Survey Fleet MCXII of the Galactic Empire. The Emperor ordered Earth to send a representative to the court, with strict instructions to “bring something beautiful”. Emperor: What beautiful things does Earth have? Earth Representative: Your excellency, our mathematician Euler proved in our year 1737 that +/(1+⍳∞)*-s ←→ ×/÷1-(⍭⍳∞)*-s Emperor: What is the ⍭ symbol? Earth Rep.: ⍭i is the i-th prime. Emperor: And what is ∞? Does it do anything useful? Earth Rep.: It denotes infinity, your excellency. Emperor: (ponders equation for a minute or two) Respect! Emperor: Neat notation you have there. Tell me more. Earth Rep.: Your excellency, it’s called APL. It was invented by the Canadian Kenneth E. Iverson…
- abrudz 4y ago* is exponentiation ⍳ is range 0…n–1 ÷ is reciprocal of everything to its right ×/ is product of everything to its right +/ is sum of everything to its right
- greenbit 4y agoHow long do you have to rewrite every such expression with pencil on paper, before you start to be able to apprehend these things directly? I'm not trying to bring this down, clearly it's very concise, just curious what the learning curve is with that.
- warrenm 4y agoThe learning curve is a backwards-leaning cliff of oiled ice a mile high ...until/unless you know it, then it's like sailing an iceboat At least, that's how my CS prof 20+y ago described it to us :)
- abrudz 4y agoThe winner of this year's APL Problem Competition only started learning APL a year ago. And lots of people never handwrite APL, though many do, but not to understand — to simply do certain maths in a better way.
- ncmncm 4y agoAnything by Justine (justine.lol) will be a serious contender for the title.
- nuc1e0n 4y agoThis is probably not a popular opinion, it is now wholly unnecessary and was often abused but I would say jQuery's source code. It took a language previously considered as a toy with different implementions that were inconsistant and unwieldy and made something immensely powerful and consistent with it. It brought lisp style functional programming to many who had never seen it before. Within a matter of months everyone working on the web was using it.
- suprjami 4y agomusl libc - https://musl.libc.org/ https://musl.libc.org/ This isn't just a small implementation of the C standard library, it's an absolute joy to read and usually every easy to understand. It takes real talent to write code which is both this legible and efficient. Often when I'm trying to understand what glibc is doing I'll read the musl version of a function and that will give me an indication of what the glibc source is trying to communicate.
- rozenmd 4y agohttps://github.com/kelseyhightower/nocode https://github.com/kelseyhightower/nocode