Ask Slashdot: What Do You Consider Elegant Code?
lxrslh writes: "Since the dawn of computing, we have read about massive failed projects, bugs that are never fixed, security leaks, spaghetti code, and other flaws in the programs we use every day to operate the devices and systems upon which we depend. It would be interesting to read the code of a well-engineered, perfectly coded, intellectually challenging program. I would love to see the code running in handheld GPS units that first find a variable number of satellites and then calculate the latitude, longitude, and elevation of the unit. Do you have an example of a compact and elegant program for which the code is publicly available?"
Duff's Device
Get thee glass eyes, and, like a scurvy politician, seem to see things thou dost not.--King Lear
The Linux Kernel is a fine example of public mammoth project with strict style guidelines, and ones that are quite elegant IMHO.
My weblog in spanish
or is the OP requesting us to hunt down a piece of code that fulfills his project specs (and does it elegantly, gosh darnit!)?
Is the OP's real name Tom Sawyer?
Writing code can be like explaining something or teaching. You can give an explanation that is logically correct but difficult for a human to follow. Programmers tend to neglect this in their code because it can be difficult to construct something that reads well and even if it doesn't read well, it can still be executed by a computer.
I like to think that if code is 'elegant', it can be read well after at most after brief explanation of how the algorithm is supposed to work, because code alone is sometimes difficult to interpret.
A lot of "real world" code out there has not been designed, it has grown, and that's part of the problem. Think of cities that have grown (London?) rather than be designed according to some grand master plan (New York?) and major reengineering exercises need to be undertaken (in the case of London, as one example, sewage pipes were fitted in underneath). Inevitably there's some shortcuts taken or real reasons that you could not quite do the best job.
Codewise, the oldest running code probably lives in the banking system or the telephony system. Typically code that has grown over time and can't just be shut down for an upgrade -- "what do you mean close the bank for a week?". Now whatever code runs there has been kept running (bodged?) for decades, but pretty it probably isn't.
Just like everyone else
Build a Man a Fire, and He'll Be Warm for a Day. Set a Man on Fire, and He'll Be Warm for the Rest of His Life.
I consider code elegant if I can read it and understand it on the first try, personally.
ftp://www.worldofspectrum.org/pub/spectrum/books/CompleteSpectrumROMDisassemblyThe.pdf
Most code will not fall into the "elegant" category. The reason is that real-life software has to deal with exceptions, language crocks, patches/modifications and bug-fixes. It is also subject to the constraints, limitations and ugliness of whatever it has to run on and interface with (no program is an island entire of itself Every program is a piece of the continent, A part of the main() [ John Dunne] ).
Therefore the only place you'll find elegant code is in a book about algorithms, where the idea is presented in isolation and not subject to the practicalities of real-world environments
politicians are like babies' nappies: they should both be changed regularly and for the same reasons
http://www.gpstk.org/bin/view/...
http://www.rtklib.com/
http://gnss-sdr.org/
Next time do your own google search.
I don't know if it counts as "elegant code", but I find it really useful that code is fully commented. Speaking for myself, it's useful to come back months or years after originally writing code, and knowing why I wrote such a routine the way I did, and what it does, making changes easier and quicker.
Take Nobody's Word For It.
http://www.ioccc.org/
The interactive way to Go -- http://www.playgo.to/iwtg/en/
IMO elegance comes with simplicity and duffs device actually makes the simple fairly complex, at least from a syntactic point of view. Mind you, compared to the unintelligable contorted rubbish calling itself C++ that I've had to debug over the years its a masterclass in clarity. Anyone who suggests building a framework for any project that is going to take less than a week should be shot on the spot.
You always have to keep in mind that code will be changed by serveal peopale, and your 'elegant' intention may not be understood or followed through by the next guy. So go for simple rules of thumb that not only keep your code readable and clear, but can accommodate future change while ramaining so.
My number one rule for keeping code both readable and robust is this: Reduce state.
I don't mean everything needs to be purely functional, but consider state a general liability to both correctness, readability, testability and maintainability. Less is more..
* Whatever state you have should be focused and serve to explain/model the actual problem domain, not just 'keep stuff for later'.
* Keep state as local as possible - most code is litered with instance variables that should have been locals and params.
* Just because an object _can_ bundle state with its functions doesn't mean it _should_.
* If it can be done in a static method and still make sense, do so.
sudo ergo sum
New code is always elegant at first. But invariably it doesn't work properly, and by the time you have got it to work, it's no longer elegant.
Maybe you've been lucky enough to have that once in a lifetime great teacher. The kind of teacher who somehow explains stuff in such a way that everything makes sense to you; things follow logically from one another and it all seems obvious when he explains it. (And you may not even realize it until he falls sick and the substitute trying to explain the exact same stuff leaves you confused and baffled.)
Elegant code has the same property of apparent obviousness. You read it and just nod because it makes sense and flows logically. There isn't one single way to achieve this, of course. It's not about functional vs. imperative vs. object oriented, but how you employ them for clarity.
Needless to say, such clarity is a very hard property to achieve, and a lifetime of experience will only let you approach it asymptotically. It's still worth the attempt, though.
-- B.
This sig does in fact not have the property it claims not to have.
I've written code that computes a CRC. It's been done before. The naive/reference implementation works but isn't fast. The optimized version, and how the heck that came about from the naive implementation to those magic few lines of code, looks nothing like it. Now rather than you glazing over "what the?", I figure that *if* you have to overhaul this code, you'd like to know *why* this code looks like it does. So I explained why. In the code. In a full page of comments.
The first thing I look at when looking at interview candidates code is their style. I don't care particularly if it's not the same as mine, but I do care if there's no consistency to their own style. I'm talking about hurried formatting, trying to squeeze everything into the least number of lines, mixed naming conventions, bad spelling in comments, even down to things like inconsistent spacing. Maybe I'm a prude but if I'm going to be looking at this person's coding output all day it better at least be readable. That Linux managed to maintain a consistent coding style with so many contributors is an admirable feat. As for beautiful algorithms, I quite like the simplicity of Dijkstra's shortest path.
Code that does the job in the simplest possible way. This means that the writer went through several prototypes before they settled on the code they liked instead of the normal..."it works SHIP IT!"
No obfuscated crap, it's clear simple and concise.
Do not look at laser with remaining good eye.
If you follow the principles and practices in Clean Code: A Handbook of Agile Software Craftsmanship: Robert C. Martin you won't go far wrong. It also includes a worked through example of refactoring a piece of bad code into clean code.
As someone who has a copyright assignment on file with the FSF for GCC and actually tried to write an implementation of the Visual C++ __declspec(thread) keyword for GCC-on-windows (i.e. proper OS-provided thread-local-storage support) and got lost somewhere deep in the code that actually converts the intermediate representation into assembler (I needed to do stuff to it so it would correctly access the thread-local-storage data when an access to a thread local variable was made) I question your statement that GCC is well-written, elegant or easy to understand...
The GPS code I've seen was horrible and I worked for one of the major GPS players for several years. Originally written in FORTRAN and later automatically converted to C. Utter crap basically. The mathematics behind GPS is really interesting and quite involved. The implementations are crap.
Saved me from writing the same thing. The GPS code I've seen, written by engineers and not programmers, was an incredibly hacked-together, barely-functional set of kludges to implement a lot of very elegant mathematics.
For another example of a well written large project, try gcc.
Another example that's at least as elegant as gcc is OpenSSL.
Code written to do one thing is inherently elegant.
No code ends up ever having to do one thing.
The job of requirements gathering is to determine what are the constants and what are the variables. In the case of, say, GPS, the constants should be the protocol of the satellites, the max and min # of sat's that can be found at any given time, the grid representation of the earth, and the system clocks.
Nice and easy, right?
Now change all of those to a variable: you have satellites speaking to you in different protocols based on their age. You end up with only one sat connection so no triangulation due to mountain or building blockage. The grid representation of the earth is inherently distorted at the north and south extremes (and whenever you're above 5,000 feet). Oh, and the you forgot to time-distort your own clock for the rotation of the earth, so a tiny offset is being caused by General Relativity.
Suddenly code that was nice and simple is now full of ifs and switch loops and complex adjustments and bits of guess work and comments that say "oh, well, we'll just have to ignore that last part...but we'll only be off by 30 feet or so".
The first bug in software happens when something that was presumed in the requirements to be a constant has to be changed into a variable. Every bug that follows is a result of trying to fix that first bug.
Because of that requirements problem, no working production code can ever be elegant.
"But remember, most lynch mobs aren't this nice." (H.Simpson)
-- Joe
As someone who got lost somewhere deep in a single sentence (which consumed three whole screen-width lines) that spent nearly 100 words on a dependent clause (which itself contained two parenthetical clauses) before even getting to the subject (I was starting to wonder if there would be one at all) I question the value of your comments on the topic of elegance...
Yo dawg, I heard you like the Ackermann function, so OH GOD OH GOD OH GOD
I'll take a guess that readability is no more important in your code style than your prose.
A complete highly extensible interpreted language with a built-in editor, macro assembler, etc in under 10k lines of code which did everything any modern scripting language does, except they all require at least 200KLOC to do it in.... This is the most elegant piece of software ever written, bar none. It isn't even a contest.
"Malo periculosam, libertatem quam quietam servitutem." -- Jefferson
Elegant code is...
There are also some languages that I view as inherently elegant, and others that I consider not to be so. C, Python, and Ruby all allow breathtaking elegance in their own way. C with its spartan manner of managing the machine, Python with its ridiculously readable pseudocode-like syntax, and Ruby with its pure object system and powers of abstraction. On the other hand, some other languages like C++, Java, Haskell, Javascript, PHP, BASIC, and Erlang will never be languages that lend themselves to true beauty and elegance. All of those languages either have serious flaws, or they do not allow programmers to express their ideas eloquently in code. In a good language, your ideas should pop out as the most important thing, not the language itself.
Systemd: the PulseAudio of init systems
As the purpose of comments is to explain *why* a part of code was created (and why it was written in that particular way), it not being executable shouldn't matter much, as completely repurposing a bit of code rarely happens. (Generalizing it yes; abandoning the original purpose of a routine or function is uncommon).
The best comments are those targeted for the programmer reading them, not the machine that must execute the code; and letting fellow programmers know why you needed that piece of code in the first time is invaluable, even if what the code does changes over time.
Singularity: a belief in the "God" idea with the "demiurge" relation inverted.
Most of your so called *elegant code* I have seen is either difficult to maintain or performs poorly due to the original developer trying to be a fancy pants. I can count the times on one hand that I have ever said "whoa" when looking at a piece of code.
...I'm not sure who they're trying to impress but it sure as hell isn't the poor maintenance coders a few years down the line.
I write simple code. I am primarily a C/C++ coder and in the "Obfuscated 'C' contest", I wouldn't even make the cut.
My code was described as very "simple" in a patronizing tone. My code works, has very very few bugs, it is done on time, and looking back at it after year, you can see exactly what it's doing - even without reading the many many comments.
I was treated as the dullard of the team. It's like if you don't use all the tricks and shortcuts, somehow you don't really know the language that you are programming. And if your code is too easy to understand, then you are not as smart or good.
I started in this business in 1992 and I have never been in a shop that did not have the attitude.
Take a look at MS-DOS source... that'll be elegant and bug free.
//TODO: create a signature
Well, it looks like we're not all racist bastards.
-- Make America hate again!
Does anyone else hate the conditional operator. It replaces six lines of code with one line...
My first boss complained that a page of my code was harder to read than a page of his code. I told him that one page of my code was a lot easier to read than the six pages of code he wrote to accomplish the same thing.
Fantasic example of code written in a procedural language (C) in an object-oriented way,with clear separation of responsibilities.
http://www.postfix.org/
The framework that Wietse created to structure Postfix is, from my perspective, a thing of beauty. I don't doubt that this has been done elsewhere, but Postfix is the first real example that I came across of a somewhat-large application structured in a very clean and understandable way.
Well worth spending some time perusing the code.
I'll recommend a tour guide in the form of John Bentley's Programming-Pearls-2nd-Edition.
His Programming Perls book does a nice job of putting interesting algorithms and design forces into context and helps the reader understand the pros & cons thereof. Part of the problem with just wandering around looking at things is you don't see the history and decisions that were made leading up to the result; understanding "what" isn't nearly as important as "why".
Also, the book isn't related the the Perl language; instead it uses Pearl as a metaphor for a small yet beautiful treasure.
Anyway, check out the Amazon reviews to see if it is worthwhile (I have no vested interest here; I just stumbled across this in a real book store some time ago and found it a satisfying read).
Since you are looking for an open source GPS application take a look a My Tracks android application for tracking, location, speed, altitude over time.
I can't speak to how well it's coded, but the application design is simple, and elegant
I have long said I preferred elegant to clever code. When I get a phone call on Friday, at 16:15, or 02:00 some night, I want to leave on time, or go back to sleep that night, *NOT* spend hours figuring out how this bit of cleverness is broken, or how someone's "the code's more compact!" is suitable for entry in the Obfuscated C contest.
But to write elegant code, you need to a) know what you're trying to accomplish; b) tell your manager, or whoever, that no, you can't make that kind of major change without their $$$ signoff on a change to the schedule, complete with specing out the change, and its affects on everything else; c) having the time to write, test, and debug the code, and this does *NOT* include drinking a six-pack of Mountain Dew a day, and doing 80+ hour weeks.
Yes, I *have* had jobs like that. And 70+ or 80+ hour weeks result in a *lot* less "productivity" than the old 40-hour week (and try looking up where that number came from... the name Ford may surprise you in that....).
mark "as opposed to managers w/ MBA, who think that you can point and click a good system"