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.
http://www.computerhistory.org/atchm/macpaint-and-quickdraw-source-code/
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.
For another example of a well written large project, try gcc.
I consider code elegant if I can read it and understand it on the first try, personally.
As a teenager I had a copy of 'The Complete Spectrum Rom Disassembly' which, as you'd expect, was commented Z80A code for the Sinclair ZX Spectrum. It was a fascinating example of elegant and optimised code. Shame I lost the book (and it seems to be out of print).
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
To me elegant code is code that has constant execution time, is readable at a glance and accomplishes it's function with little to no side effects. The last part seems to be almost impossible for most modern programmers, understandable when they never drop any farther than an abstraction on top of an abstraction.
I find 'elegant code' and 'finished project' to be mutually exclusive.
http://www.gpstk.org/bin/view/...
http://www.rtklib.com/
http://gnss-sdr.org/
Next time do your own google search.
Seriously. If you comment well (things that others will understand easily, not just ways to remind yourself of what the code does) it doesn't matter how "elegant" the code is.
Also, sometimes "elegant" code is worse performance wise. It might be considered more elegant to use a for loop, but faster to merely paste the results of the loop directly into the program so it doesn't have to run the loop every time it runs. (Of course, this does increase the size of the program though, so there are always trade-offs.)
To summarize - Comment, comment well, and write efficient code. The end result is what matters? not the elegance of the code, and if someone does have to continue your project, the comments will make it possible.
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.
Mel.
Ideally, with the OP satellite example, you think one loop would be gathering a list of satellites objects (or structs) and then in a different loop there would calculations for the various attributes of each satellite, ideally with descriptive variable names being initially declared 'double longitude =0" and brief comments above for loops such as "//Determines individual satellites per unique GPS frequency However, I've come to accept that people are just different, people are going to code in the manner they are accustomed to, with very few comments. I've come to accept that reading others people's code is just going to suck. If I know the intent of the class and the variables/functions are self-descriptive, I'll be fine. If some names their variables "a1" "a2" "b1", and they are all different data types... then I'm going to have a bad time. But again, I've accepted this. What I can't accept is people coding inefficiently. I'm not even worried about space complexity (within reason), I'm talking about run-time complexity. If you have 3 inner for loops for something that could be done in linear time, I'm going to be sad. If I fix it and try to use this chance as a teaching moment (we all should want to be better) and you shrug and tell me that correctness is all that matters... then I'll stab you. The best algorithm isn't always obvious, and while I don't expect many of us to employ dynamic programming concepts... if we can't get people to agree on a coding style (since that is preference), the least we can do is agree that we don't want our code to completely suck. I mean if you have a O(n^3) subroutine, you should ask yourself if that is really the best you can do, at least think about it. /rant over
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
There is only one programming language that actually makes the code really nice to read; hence making the code elegant: it's called Whitespace (http://compsoc.dur.ac.uk/whitespace/)
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.
All of my code is elegant and bug-free, but proprietary, so I can't share it with you.
Malbolge.
Modula-2 first compiler source code: http://www.cfbsoftware.com/modula2/
but in the pictured code, it should be def are_connected(...): return self.filter(...) or self.filter(...)
Elegant code gets the job done with as little code as possible, also preceding individual lines to do as little as possible.
In general, the more your code does the harder it is to understand. So doing less leads to fewer bugs.
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.
Elegant code is code you can look at and understand what its doing and then audit easily.
That is the real point of elegant code. You ACTUALLY know precisely what it is doing. No guess work. The best code can be understood with a casual glance and any mistake in the code stands out brightly because the pattern and elegance of the code is beautiful in its way. And any imperfection is ugly.
I've decided to stop wasting my time responding to AC trolls/sockpuppets... so if you want a response from me... login.
Why should embedded code be elegant? It isn't written for people.
(defn sieve [s]
(cons (first s)
(lazy-seq (sieve (filter #(not= 0 (mod % (first s)))
(rest s))))))
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.
Linux Kernel is good, but huge... Doom3 seems more of a manageable. https://github.com/id-Software...
I find the source code for Paint .NET to be a good example of well written code (at least for a GUI driven application in a modern OO language).
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...
thanks again moms...
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
Unfortunately my employer thinks it belongs to the corporation, because they paid me something they call salary to me when I wrote it. They would not let me show it to you all. But this much I can tell you. The key to writing such wonderfully elegant code is to avoid exaggeration, stay away from bragging, and most importantly eschew snark.
sed -e 's/Chuck Norris/Rajnikant/g' joke > fact
Having written a lot of code, the key point is that real-world code handles exceptional conditions, platform bugs, hardware weirdness, language ad-hockery, third-party libraries and their quirks, and so on. Any code useful enough to do anything worthwhile isn't going to be elegant. Code is ugly because it's an accretion of handling weird and exceptional conditions. Plus there's all the strange logic you have to add for edge cases and weird conditions in your own business logic - do this 99% of the time, except when some weird thing happens, then do something else. Throw in multi-threading, and you add another layer of checking to see if objects are null. I think most Android code is "if this object is not null, do something" to deal with its insanity-inducing asynchronous nature. Or setting and checking flags so one asynchronous bit of code can flag a condition another method has to deal with when it is called asynchronously later. By the time you get through writing something that really works, it's a nightmare. I often can't figure out what my own code is supposed to do. I write a lot of comments that explain why code works the way it does.
Read a LISP textbook or something to see elegant code. Most elegant code is far removed from the real world.
10 PRINT "HELLO WORLD"
GOTO 10
See subject...........
[FUCK BETA]
exactly my thoughts as well.
all "code" is symbols arranged to communicated **instructions** to a machine
it's all instructions...the variation is the way the instructions are delivered
knowing this, and having some experience coding, elegant code will be understandable to even novices once the basic "language differences" are learned
Thank you Dave Raggett
I originally had a 7th generation photocopy of this. Simple sweet code, even with the infamous comment on line 2238 of slp.c "You are not expected to understand this", to do with swapped out process resuming.
Seconded, gcc is a throwback. Now LLVM, on the other hand ...
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.
Interesting. I can see that FORTRAN was once the computer language for mathematics, but it never occurred to me that GPS was old enough to be coded in it. But I see that GPS development started in 1973, and even then was based on some earlier work, so definitely during the time when FORTRAN was in common use.
Can't say I'm surprised that it tends to get ported rather than re-implemented. With something that's as complicated as that, with an implementation that has stood the test of time, better to stick with something that's not easily understandable than to have a new readable version with a whole new set of bugs.
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
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.
Yeah. If you want elegance, you should probably just go straight to the math. As soon as you put it into a computer with its pesky limitations of finite time and space, elegance goes right out the window.
Yo dawg, I heard you like the Ackermann function, so OH GOD OH GOD OH GOD
I'm sure this will seem controversial, but elegant code is not practical in a project sufficiently large enough to be useful. The problem is that for elegant code to stay elegant, you need really very high quality and disciplined programmers who are ALL following some established coding guidelines ALL the time. Even with the best intentions, this doesn't happen particularly during crunch and/or stressful times. In practice you need some level of flexibility and bending the rules in order to do what you want in a reasonable timeframe. Focusing on elegant code requires a non-trivial amount of extra effort for questionable benefit.
If you're only coding for yourself or are the sole programmer and don't have a pressing timeframe to fit into, then sure, be as elegant as you want. But it's not all it's cracked up to be. In the end you need to produce something that works, even if it involves various ugly hacks to deal with the imperfections of reality.
I can not stress enough how important it is to write readable code.
Keep it simple and be consistent.
Others will read your code and when they do they will most certainly scratch their heads in either amazement or frustration.
If you wrote readable code you will make their heads spin less, or your own head spin less when you revisit your own code.
And if you have been consistent it will be easier to review and update what already exists because it is going to be the same everywhere.
when the project is elegantly defined... the code has full opportunity to be elegant
elegant at least for being written in PHP
... to learn with the PRO: http://www.cs.cmu.edu/~dst/DeC...
Two letters: Qt
I've always considered elegant code to have a few criteria.
There is no unnecessary complexity in the code.
The code base is "clean" and consistent. That can be the file system layout, filenames, variable names and function naming. Also a non-consistent comment and white space convention is a personal irk of mine.
Where most programmers would write several hundred lines of dense code to solve a particular problem, the elegant coder will write a few simple lines instead as they really understood the problem.
10 Print "Hello World"
20 Goto 10
The C Programming Language is full of elegant, clean examples. :)
http://net.pku.edu.cn/~course/cs101/2008/resource/The_C_Programming_Language.pdf
I think the crux of it has been said above, but my $0.02:
Optimized
Well formatted
Commented in areas where reading the code isn't obvious to even the newest entrant into programming
Well supported by the author(s) or corporation that produced it
I will also admit that I don't write a lot of elegant code, because I usually don't have the time to fully optimize it. But most of my code is well formatted, commented and supported.
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
I've often com across this: if (b) return true; else return false;
-- Make America hate again!
I recommend you read The Architecture of Open Source Applications at http://aosabook.org/en/index.h... This book looks at many different open source projects, and can be a source of inspiration (and debate). You'll find some of what you're looking for in it.
John
Hear, hear! Well played. If only I had some mod points.
lisp
NetBSD.
from https://www.netbsd.org/about/system.html
>Probably the primary goal of the NetBSD project is emphasizing correct design and well written code.
QuickSort is elegant
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
;
That was difficult. Must be time for coffee..
int main()
{
}
The mistake is "read the code". If you want to evaluate the stability of an house you check the project documents, you don't check the walls!
#1 problem) Spaghetti code is the root of all evil. It is the biggest problem that I constantly run into.
1) New devs have a hard time getting up to speed.
2) Even the original dev starts having trouble mainting the app if they have to work with it after a two year hiatus.
3) Unit testing never happened and if it did, it is a poor excuse for unit testing that gets to 50% of the code if lucky.
4) Ya, go ahead, maintain those unit tests!
5) Those that are not the original developer have ahard time maintaining the code. Much like (2) above but it is much worse.
#2 problem)
No mentoring program for new devs.
I don't care how good you are out of college. You don't have real world experience. And all the little crap you do wrong doesn't get better on it's own. Mentoring (through peer reviews hopefully) will turn a good recent grad into an excellent software engineer. I've seen too many people not get mentored or properly mentored just to be half of what they should be 5 years later.
(loop (print (eval (read))))
Don't complain about syntax, grammar, or spelling. There is no.hell like input on android.
http://groups.engin.umd.umich.edu/CIS/course.des/cis400/c/hworld.html
/* Hello World program */
#include
main()
{
printf("Hello World");
}
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.
or just a nice shirt, if it's casual code day
Fortran is the best language to write mathematical formulas. It's a FORmula TRANslator, after all. Auto-converting elegant FORTRAN to C is the most stupid thing you could do, and probably that's why the vendors did it.
...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.
My stuff gets the job done.
I generally put enough notes in that someone could come behind me and see what's going on. And where I don't I try to use pretty obvious variable/function names. But it's usually not to pretty. And it's in PHP so most of yall would say it's not even actually CODE.
Do not meddle in the affairs of sysadmins, for they are subtle, and quick to anger.
Jut use punch cards and make the holes butterfly-shaped. The just add some curls and leaves with a pink marker on the margins.
Curiously yours, crip.
http://en.wikipedia.org/wiki/H...
To me, elegance at code level means succinct and readable code. Optimizing for performance usually comes at a lower level of readability.
Therefore, first write the code in the most elegant way.
Then, write an optimizer that optimizes that code. Of course, the optimizer itself should be elegant, but it need not be efficient.
For some reason, your comment reminds me of this:
https://github.com/mame/quine-...
Code doesn't get much more beautiful than:
https://github.com/mame/quine-...
this notation
Pretty much anything written in Ruby usually seems elegant to me. Ruby is one of the few languages that really encourages doing things in the most simple, direct way possible. And because Ruby has such a well thought out and consistent way of doing things, you rarely see obtuse, ugly solutions to problems, designed to work around the way the language is supposed to work. Ruby is the one language I have run across where I do not dread reading other peoples' code out of fear of having to decipher incomprehensible gibberish. With Ruby, I can usually understand another person's code as easily as my own. Unless of course, they are the type of coder that likes to be "clever" with the code they write, but situations like that are hopeless either way.
Take a look at MS-DOS source... that'll be elegant and bug free.
//TODO: create a signature
Programs must be written for people to read, and only incidentally for machines to execute. - H. Abelson
Also Zen of Python has a bunch of interesting points.
Forth is better. I've seen more mangled code from templates to get around all of the data casts. It's *GREAT FUN* to debug.
Oh yeah, that and systemd!
What I really want to see is good code that does certificate validation. The apple goto fail being an example of bad code.
http://www.catb.org/jargon/html/story-of-mel.html tells the best story I know regarding someone who best optimized code based on an intimate knowledge of the hardware (a machine with Drum memory) on which he was working.
Here's an excerpt:
Mel never wrote time-delay loops, either,
even when the balky Flexowriter
required a delay between output characters to work right.
He just located instructions on the drum
so each successive one was just past the read head
when it was needed;
the drum had to execute another complete revolution
to find the next instruction.
He coined an unforgettable term for this procedure.
Although “optimum” is an absolute term,
like “unique”, it became common verbal practice
to make it relative:
“not quite optimum” or “less optimum”
or “not very optimum”.
Mel called the maximum time-delay locations
the “most pessimum”.
Elegance should mimic somewhat elegance and simplicity as sought by the great physicists, Dirac in particular - that the rules of nature should be defined simply or elegantly.
For me
Elegant code = mimics at some level what it is actually representing. The algorithm's earlier brach, not the fork itself should be implicit. So you can clearly see that it's a sorting algorithm by just looking at it, and when you drill further you see the nuts and bolts. That's elegance for me.
So, for me:
Elegant code = grabs your attention as understandable + works efficiently, reliably and quickly.
At least that's what I'd strive for if I was still a programmer. Time to get back into the game.
means 209 different opinions.
Well, it looks like we're not all racist bastards.
-- Make America hate again!
Does anyone else hate the conditional operator. It replaces
if (a > b) {
max = a;
}
else {
max = b;
}
with
max = (a > b) ? a : b;
Code that is easily adaptable and modifiable to accommodate ever changing requirements and new functionality by a plurality of the coders expected to work on it.
Long term malleability and adaptability is what makes code and APIs great.
If it is hard to change or use, it is not elegant.
Code which is easy to reason about. Where each peace of code has a clear task, with as few special cases as possible.
Low-complication implementations of functionality are typically more elegant.
-- Erich
Slashdot reader since 1997
I allways enjoy scanning the pages of "THE C PROGRAMMING LANGUAGE" the original (or 2nd) by Dennis Ritchie. The world never gave him proper respect! RIP.
To me elegant code is code that's enjoyable to read!
Back in the dark ages (early in the first Reagan term) when I was studying CS at Washington University, one of my favorite professors offered the following definition.
"The elegant solution is the simplest one that completely satisfies the requirements."
These have been the words I have tried to code by for the past three decades. Most of what I would consider inelegant code comes from either not taking or having the time to simplify things or ignoring the "completely satisfies" part and figuring that a Pareto solution is good enough.
Generally, well written code with useful variable names does not need much documentation (how often have you found comments that don't quite match what the code actually does?). Where performance an optimization is critical (and developers often optimize the wrong things), good documentation is crucial (and good teaching opportunity) for explaining clever techniques that improve speed.
While it is bad to be dogmatic about this, the general rule that any module/routine should fit on a single printed page is a useful construct. Complex or repeated operations can usually be factored into their own routine so that each is kept small enough to be understandable and maintainable.
Unfortunately, to the great many programmers who specialize in terminology and syntax but can't solve actual problems, elegance is in complying with "best practices", "new technologies", buzzwords, terminology and pet methodologies. And most of it is impractical. The code they create is fractured, overly complex, and doesn't solve real-world problems on a schedule or on a budget.
An elegant solution is one that anyone can pick up and understand, and doesn't lock anyone into any particular technology unnecessarily. An elegant solution gets the job done with the least amount of technology, not the most. An elegant solution delivers what the client asked for, not what the resume benefits by.
Most of the essays like this one here: http://www.jsoftware.com/jwiki... .
Hey! I wrote some very early GPS computational code in 1971-1972 and it wasn't crap. FORTRAN was the default for engineers and mathematicians as it was the language we learned in college in the early 1960s and there weren't any real alternatives to it anyway. If some idiot in later years decided to let some bit of software automatically convert FORTRAN source to C source (given the syntactic, structural, and philosophical differences in the languages), blame him for the code being crap.
just saying
1972 is calling:
http://www.inwap.com/pdp10/hba...
The original architects, usually, don't work for themselves. They don't get to decide how much time is allocated to the project. While there is a negotiation, there is also a reality.
And time to market matters, a lot. Compare a maintainable-but-late product to a good-enough-right-now product in the open market and which one do you think will win? (hint, if you pick "A," you probably aren't the CEO of a successful business).
Perfect software is achievable, and prohibitively expensive. Good enough software has long-term maintainability costs, but it also has a long-term in which to pay those costs.
I'm not an expert on any compiler code, but I thought that gcc was actually comparatively new, as it used to be called "egcs", and was different from what used to be "gcc", and was a newer project. At some point, the gcc team decided to simply adopt egcs as the new gcc and dump the original as it was too old and crufty.
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.
Good code should be easy to follow with no function taking more than a minute to read and understand with meaningful names that can be trusted to do what they imply they do. Each function should ideally have 4 or less paths through the code with greater complexity being shoved into another method. Test Coverage is sexy. There is nothing that will make me hate a codebase more than when I have to dig deep down into a code base and find that one little variable that's getting set to null in some peripheral object instead of what it's supposed to be after hours of debugging.
There is no memory shortage. yes I have heard of XFCE. Go away.
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
Now /this/ is what I call elegant code.
Haven't found out what it does though....
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"
There, fixed that for you
(Unless I missed a use whoosh; here... don't think so because your post seems sincere.)
At the point where you're using Perl idioms to slurp an entire file into memory... is the array reference really the hard bit to understand here?
I'll grant you the point about not needing to be a reference at all because of function locality.
But my $x = [ ]; and my @x; both establish an array.
push is actually suggestive of what it does, unlike the input operator's ability here @x = <$fileHandle>; to return all lines in a file as a list context... That is as obscure as references; if your target audience is expected to know how that aspect of the input operator works I wouldn't be too hard on your coworker for expecting them to understand array references.
Oh so this!
I have had to tell cow-orkers to knock that crap off. They've got the job, and from this point on the only thing that will impress us is code that can be maintained by anyone else on the team, even if they have not set eyes on it in years.
Programmer did:
my $something = []; open my $filehandle, '<', $filename or croak "Can't read file"; push @$something, <$filehandle>; close $filehandle;
How about:
open(my $filehandle, '<', $filename) or croak "Can't read file"; my @something = <$filehandle>; close($filehandle);
Much more succinct, gets rid of a pointless use of an array reference (seriously, it was used as an array in that function only, never passed around or returned), and at the end of the day, is far more readable.
wc, cat, sort, head, tail, split et al. Source here.
I'm not an expert on any compiler code, but I thought that gcc was actually comparatively new, as it used to be called "egcs", and was different from what used to be "gcc", and was a newer project. At some point, the gcc team decided to simply adopt egcs as the new gcc and dump the original as it was too old and crufty.
If you call 1997 new, then yes it was new. Except that egcs was based on a gcc snapshot.
All I want is a secure system where it's easy to do anything I want. Is that too much to ask ~~ Randall Munroe
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.
No you don't. Trust me, you'll be very disappointed.
In the course of every project, it will become necessary to shoot the scientists and begin production.
that is easy to read.
No magic numbers, no overly clever recursion, consistent implementation and easy to read names.
The Kruger Dunning explains most post on
Elegant code is no code.
http://www.jsoftware.com/source.htm
See the parser in p.c.
Lisp's eval
It'll take you a while to get it. You'll have to be asking yourself the question, "What's all the fuss about Lisp?". You'll set it aside for a while. You could easily dismiss it for glossing over some details such as the actual (read) function; but when you "get it", you'll get it.
Stumbling blocks: prefix notation. A lot of people say it's the ()s that make Lisp hard to read; but it's really the prefix notation. Another stumbling block is the lame explanations for what (quote) does. People say it says "don't evaluate me" and while technically true, it doesn't answer the question. A better answer is, "returns a syntax tree ". A more detailed answer is "returns a list which serves the same purpose as a syntax tree. This is handy because every function in Lisp takes that same kind of tree as an argument, so it's handy for writing macros".
Like many people, I've never written a line of Lisp that runs anything, let alone an actual piece of professional code in Lisp. Also like many other people, I've found value in studying it and applying the concepts elsewhere.
Another person said "Forth" and they've also got a point. In some ways, Lisp is the dual of Forth. The postfix notation of Forth can cause just as much confusion as the prefix in Lisp; but that doesn't mean they aren't elegant in their own ways.
For all intensive purposes, "whom" is no longer a word. That begs the question, "who cares"?
As someone who got lost somewhere deep in a single sentence (which consumed three whole screen-width lines)
Stop reading on your cell phone, or turn off beta. For me it fits into less than two lines.
Is no code at all.
...was a program that kept a session alive in a modem pool. With the goal of essentially "reserving" a spot in that modem pool (sessions were routinely over-subscribed).
It had to use absolutely minimal resources, never draw attention to itself, have a basic user interface, and never crash or fill the command buffer. It did all that in 3 lines of code.
And no, I cannot post the code. The fundamental purpose of the program was, ah, "not officially sanctioned". We destroyed the program and never talked publicly about the program after. We had our reasons and agenda and the system gatekeepers had another. Sometimes that's just the way things are. But it was beautiful piece of code and truly elegant. Best I ever saw.
I'm all for writing awesome properly indented and commented code... speed, and the need to get most things done yesterday, leaves me satisfied with code that works and doesn't require some crazy "hack" to get around a problem I don't have time to solve the right way.
spaghetti code = job security
Maybe a bit longer that you want, but the UNIX 6th Edition source code, as presented in John Lions' commentary book is excellent reading. Clean, functional code with some well-documented "wow" moments.
What race is that? Please make sure to mention the caste system in your response.
In my opinion, elegant code is easy to read. Functions are short, you can look seem all function body on a 25x80 terminal. Function and variable names are coherent and self-explaining, style is uniform, and comment exist where they are needed.
I've been reading over the MooTools core recently and there are many interesting concepts and techniques going on there.
Most elegant though, it's got to be FORTH. That one is just inspiring by defining such a simple machine and the framework for calculations that can master any processing environment..
I wonder how many slashdotters browse all websites maximized. I'm sure a not-insignificant number use their monitor in portrait mode.
I don't do portrait mode, but I also rarely do maximized windows, since I multitask.
This pretty much sums up what I consider as elegant code.
Tom contemplated the boy a bit, and said: âoeWhat do you call work?â âoeWhy, ainâ(TM)t that work?â Tom resumed his whitewashing, and answered carelessly: âoeWell, maybe it is, and maybe it ainâ(TM)t. All I know, is, it suits Tom Sawyer.â âoeOh come, now, you donâ(TM)t mean to let on that you like it?â The brush continued to move. âoeLike it? Well, I donâ(TM)t see why I oughtnâ(TM)t to like it. Does a boy get a chance to whitewash a fence every day?â That put the thing in a new light. Ben stopped nibbling his apple. Tom swept his brush daintily back and forth â" stepped back to note the effect â" added a touch here and there â" criticised the effect again â" Ben watching every move and getting more and more interested, more and more absorbed. Presently he said: âoeSay, Tom, let me whitewash a little.â
Doom 3 Source
https://github.com/id-Software/DOOM-3-BFG
Code that I can come back to years later and understand how it works and how to interfaqce with it, or that I can hand off to someone else and they can understand how it works, or how to interface with it, with little effort.
Code that I can easily pull out and re-use along side other code, and in other projects.
Code that I find myself re-using and building upon over and over again.
Things that make code hard to work on or horrible to read and understand.
1. Over structured.
2. Over Abstracted.
3. Use of Object Oriented concepts.
4. Bad comments (99.999% of developers can't write comments to save there lives).
5. Complex loops to prevent using goto.
6. Using pointers over arrays because you can.
7. Using case statements in place of if's.
8. Single line if statements with out the brackets.
I could keep going but to sum it up quickly, all the standard "good coding" practices basically destroy code, so don't listen to your professor.
Many solutions posted there are masterful examples of elegance in programming. Some are so good they may change the way you think about code.
But to see them, you actually have to care enough to solve the problems yourself first.
I think elegance in coding deals a lot with how smartly do you accomplish the solution of the technical challenge. Remember, code is technology, and you can put all your art to the service of solving a problem - but the solution is not only in the code. Sometimes, digging out (or flushing out) the hidden business constraints makes up for an elegant solution as well. Leave alone readability, maintanability and error handling.
A GPS (and Galileo) software receiver in C++: http://gnss-sdr.org
You could do far worse and not much better than to look at Kernighan & Ritchie's book about C. Here is the URL to the PDF file:
http://zanasi.chem.unisa.it/download/C.pdf
Arthur