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.
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/)
Agreed. I'll allow javadoc-like comments that help to document a public interface, but if you write comments to explain an algorithm, you're probably making a mistake.
Slashdot social media options: AIM, ICQ, Yahoo, Jabber and Mobile Text. Why no MySpace?
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.
but in the pictured code, it should be def are_connected(...): return self.filter(...) or self.filter(...)
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.
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...
I was intentionally overstating it a bit.
There are of course cases where comments are warranted, and properly justified optimizations may be just such a case. The others also usually fall under the broader umbrella of "exceptions" to how things might normaly be done. Just don't use it as an excuse to make the code less clear than it could be given the perfomance constraints, and beware of premature optimisation, which is a prime cause of brittle and unreadable code, with frequently no real benefit to offset the cost.
And always consider if you could say some of it with code too.
As a general rule, though, I still think it is wise to keep in mind that since the comment is not executed, there is no guarantee that it reamains correct, if ever it was.
I sometimes make a hobby out of trying to find at least one error in every comment I see. It doesn't always pan out, but tre percentagewhere it does is both staggering and frightening - I warmly reccommend the practice to everyone.
sudo ergo sum
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.
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
Almost always better to use a loop, a good compiler can unroll the loop if doing so would be beneficial and unless your targeting a single specific device, what's most efficient will depend on the hardware - eg a large unrolled loop might be slower if the loop is too big to fit in the cpu cache, and the unrolled loops increase the memory usage of the program which may be detrimental depending on the speed and quantity of memory etc.
http://spamdecoy.net - free throwaway anonymous email - avoid spam!
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.
... to learn with the PRO: http://www.cs.cmu.edu/~dst/DeC...
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.
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
lisp
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..
(loop (print (eval (read))))
Don't complain about syntax, grammar, or spelling. There is no.hell like input on android.
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.
or just a nice shirt, if it's casual code day
...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
Normally a lookup table would be the way to go. There's always a why -- in this case it was a slow microcontroller with 16KByte of codespace, which was already cramped. Table won't fit.
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.
That's the stupidest thing I've read all year.
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;
Low-complication implementations of functionality are typically more elegant.
-- Erich
Slashdot reader since 1997
Most of the essays like this one here: http://www.jsoftware.com/jwiki... .
just saying
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.
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.)
Most compilers these days will do this automatically.
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
If your code needs a lot of comments, then your code is not easy to read by definition. Code should be written to be easily read with small functions with names that are self explanatory as to what the code is doing. Comments are great for those little exceptions and cases where the code looks daft but has a legitimate purpose that you don't want someone else to remove, but if your code is 20% or more comments, then they are either completely unnecessary or your code is not well written.
There is no memory shortage. yes I have heard of XFCE. Go away.
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"?
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.
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.
The best comments I've seen have explained why a particular string hashing algorithm was used; the algorithm used is not obvious. Or rather it's so obvious that programmers tend to think "it can't be that simple!" and go off and use a different one. Which has the same sorts of weaknesses and is slower, or avoids the weaknesses at a massive performance cost in normal deployments; the comment explains that this has already been tried and warns future programmers that repeating this particular blunder isn't worth it. (And yes, I didn't believe it the first time I read it, but I was cautious enough to performance check the code against all the "industry best practice" hashing algorithms I could find; they really are slower on our typical sample data and have the same sorts of problems.)
Another great comment I saw was just a reference to the academic paper that the implemented algorithm had been cribbed from. Some algorithms in multi-precision arithmetic and image processing are sufficiently complicated to be things that properly qualify as Non-Obvious; you need to read the literature to comprehend what's going on.
"Little does he know, but there is no 'I' in 'Idiot'!"
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.â
> Why would you have to overhaul a CRC generator?
Gee, maybe the naive implementation is SLOW; Specifically the default algorithm only processes 1 byte at a time -- if could process 4 or 8 bytes at a time we might be able to increase its throughput.
create.stephan-brumme.com/crc32
It is not obvious how you go
From:
// same as previousCrc32 ^ 0xFFFFFFFF // same as crc ^ 0xFFFFFFFF
uint32_t crc32_bitwise( const void* data, size_t length, uint32_t previousCrc32 = 0)
{
uint32_t crc = ~previousCrc32;
unsigned char* current = (unsigned char*) data;
while (length--) {
crc ^= *current++;
for (unsigned int j = 0; j > 1) ^ Polynomial;
else crc = crc >> 1;
}
return ~crc;
}
To:
uint32_t crc32_1byte( const void* data, size_t length, uint32_t previousCrc32 = 0)
{
uint32_t crc = ~previousCrc32;
unsigned char* current = (unsigned char*) data;
while (length--)
crc = (crc >> 8) ^ crc32Lookup[(crc & 0xFF) ^ *current++];
return ~crc;
}
Lastly, the problem with crc32 is that you can NOT split your data into N partitions, feed each blocks to your 4+ core machine and get a single CRC32 for all the blocks; you have to process EVERY byte linearly. Crc32 is not a multi-core / multi-threaded algorithm. Maybe the OP has a variation that IS designed for multi-core.
Fixed link:
Fast CRC32
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.
I disagree with you 100%, you should have a comment almost every line or a block comment every section. I work on tons of embedded code where smart ass developers decide to not comment there code and use piss poor structure. Comments are used so everyone else can read and understand your code, if it takes me more then 1 minute to figure out what you did then you wrote bad code period.
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.
If your developers didn't write shitty code you wouldn't need the comments. Comments are extremely useful for explaining edge cases that aren't apparent just by looking at the code so some other developer doesn't remove your changes thinking they are incorrect or explaining a configuration of an object or external service that other developers might not be familiar with. If every single line of code is unintelligible or it isn't obvious what it's doing you have way bigger problems.
There is no memory shortage. yes I have heard of XFCE. Go away.
Well not really, for instance it could take you 20 lines to initialize a device on a port. In that case it would be a benefit to have a block comment above the section explaining what it`s for, also it would be helpful to comment each line to explain what each value or step is for. Putting in comments doesn`t mean you write bad code, it means you want to understand it when you come back to it in a year or 10.
In fact, APL is the epitome of elegance in computer programming languages: http://sharonhines.com/interne... (one random, recent example of many).
One simple example: some languages have a way to do matrix multiplication but it's often a clunky function call or an odd, non-standard piece of notation (I'm looking at you, Matlab). APL doesn't just do matrix multiply but generalizes the very concept of it so that you can do a generalized inner product that reduces to matrix multiply when the functions supplied to it are multiplication and addition.
Ignorance of the language, common and widespread though it is, is not the same as an actual reason for dismissing it.