Ask Slashdot: What Makes Some Code Particularly Good? 298
itwbennett writes: When developers talk about what makes some source code particularly 'good,' a handful of qualities tend to get mentioned frequently (functional, readable, testable). What would you add to this list?
Obviously (Score:5, Funny)
When it's mine.
Re: (Score:2, Insightful)
What makes an article a click whoring waste of time? I don't know, I didn't read past the first for 9 impression generating lazily written dreck, but being posted on slashdot is becoming a good indication.
Re: (Score:3)
Yes, that is a regrettable trend I've seen lately. Yes, code should be readable, and should be easy to maintain. But there is a huge amount -- maybe even majority -- of time when efficiency should be considered before readability or beauty.
Re: (Score:3)
I have personally seen code essential to execution time, which was neat and canonical, made literally more than 100 times more efficient in the sense of time and CPU cycles, by using methods that were a little less readable.
And I mean via testing, not just subjective impression.
TFA has its priorities skewed.
Re:Obviously (Score:5, Funny)
Tell that to your six-months-ago self, who wrote the mess you've been debugging all week. :-)
Re:Obviously (Score:5, Funny)
I hate it when I have to debug some other asshole's code.
I hate it more when the asshole is six-months-ago-me.
Re: (Score:2)
Re:Obviously (Score:4, Insightful)
The door wings both ways though. Sometimes six-months-ago-me is a pretty cool guy.
Like that time I was searching for an answer to a problem on Stack Overflow. At first I thought "Ha, what a coincidence, the top rated answerer has the same name as me." It was not a coincidence... it was me.
Re:Obviously (Score:5, Insightful)
I am all over the place, I guess many programmers are.
Being a programmer is a trade in some parts, and you can get by with good craftsmanship.
In other parts it's a creative art, and you can't force creativity.
To write really good code, you need to both have the craftsmanship and the creativity.
chocolate. dark chocolate. (Score:3)
not to be confused with code that sorta looks like it, but surely doesn't smell like it...
Re: (Score:3)
When it's mine and I am the only one who understands it and so therefore have a cash cow until retirement :)
Because it's mine! (Score:4, Insightful)
How many managers does it take to reach a decision to begin a study to determine whether a light bulb should be replaced?
GOTO (Score:4, Funny)
Re: (Score:3)
Agreed for "self important developers".
"Good" developers know that they probably missed things or could have done some parts of it better (and know that unless there is a functionality issue, to not go back and try to fix them).
myke
Re: (Score:2)
Depends. Have they just finished it, or are they coming back to it a month later?
Re: (Score:2)
Doesn't every self important developer think that their own code is the best?
Isn't that the definition of 'self important'?
must fail (Score:4, Insightful)
Re: (Score:2)
Yep. I've had C++ coders who were not building general purpose libraries, but still insisted on throwing exceptions in cases of fatal errors (because 'that's what you do'?). The caller would then catch the exception and then call a routine to log the error and core dump for later debugging. But dumping at the site of the caller discards all the detailed information and variables that would've been available in the core dump if the damn app just logged and dumped at the site of the error instead of throwi
Re: (Score:3)
It is good practice to throw exceptions for even fatal errors. What they've missed however is to add information to the exception about the error (the stuff you propose they should log).
Somewhere way up the call stack you have a catch all exception handler, which is responsible for logging the exception -- so it is not necesarilly the caller who logs this. If the caller cannot handle the exception, it should just leave it and let it bubble up.
This way there's no need to duplicate logging code in every sma
When you go back to it several months later (Score:5, Insightful)
And say "thank you, my past self for making this so easy to understand and versatile!".
Re: (Score:2)
Indeed there's no such thing as a "do what i mean" function , but generally within the context of the application, its good when you run into a function that is "future proof" enough to not need to heavily hack it or rewrite it whole to do something slightly different.
Easy to change (Score:2)
Code that you can change, and the change does what you expected and did'nt ruin something else in a seemingly unrelated place.
Doesn't matter if the code is otherwise butt ugly, as long as you can do this, the code is good enough to be workable.
Re: (Score:3)
a few heuristics (Score:4, Insightful)
Good code feels obvious and self-evident, as though its design springs directly from the problem, rather than from the cleverness of the developer.
Good code is free of regret; regardless of how much it's been modified and refactored, it feels as though it was written in a single sitting, by a developer who somehow knew the right way to do it already.
Good code is not just readable, but inviting. It feels as though there is no wrong place to start reading it.
Good code doesn't have a single goddamn class named "Manager".
Re: (Score:2)
I would say that good code is code that's as simple as possible for its task.
Re:a few heuristics (Score:4, Informative)
Good code is boring and bland, lacking excitement and surprises.... and mostly goes unnoticed.
Re: (Score:2)
Re: (Score:2)
I'm not sure if it's just a semantics thing, but what's wrong with having a class called XManager that provides a set of safe functions to deal with a particular object or whatever it may be?
What would you add to this list? (Score:4, Insightful)
Re: (Score:2)
Re: (Score:3)
To paraphrase Torvalds:
If it compiles, it's good. If it runs, ship it.
When it works. (Score:2)
When it works.
No, seriously, that's the prime criteria. I'll take crap code over good code anytime, it it works and the "good" code needs some arcance and/or bizar setup procedure that I have to put up with to perhaps get it running.
Point in case: WordPress, a PHP driven Web CMS that today runs about 20% of all websites, is a huge pile of typical PHP spagetti. And don't even get me started on the data model ... the WP crew probably doesn't even know what that is. Anyway, just the other day I spent two hours
Re: (Score:2)
Whether it works is orthogonal to quality. Good code can be fixed easily, so good code is always a short distance from "it works". Bad code can quickly go from "it works" to "it doesn't work and I don't know why" with just a simple change in requirements.
One of my rules is that the customer is the judge of whether is works or not, but the team is the judge of whether it is good or not. If the only person to evaluate the product is the customer, then you are pretty much guaranteed to have bad code. Code qual
Re: (Score:2)
Whether it works is orthogonal to quality.
I'd say that if it doesn't work, it's of pretty poor quality.
Re: (Score:2)
If it has gotten through "design reviews, code reviews, standards, pair programming, etc..." and doesn't work when it gets to test, you have a problem.
... and your problem is a completely broken development process. Code should be tested as it is written [wikipedia.org]. You should never waste time reviewing code that has not passed unit tests, functional tests, regression tests, etc. Hallway usability testing [wikipedia.org] should be done even before the design review.
Testing is an integral part of every development step, not something you tack on the end.
Re: (Score:2)
Testing is an integral part of every development step, not something you tack on the end.
Good thing you know that we don't do unit testing... otherwise where we we learn that we were doing it wrong? Are you also going to assuming we don't do everything else I don't mention? I re-read my post and I can't find any part of it that could be used to infer that unit testing isn't part of our process.
Also, if you leave code review until after the product has passed all testing phases, then you have two problems. First, if you change anything after the code review, then you're not done testing, so the
Re: (Score:2)
I have to agree. If it has gotten through "design reviews, code reviews, standards, pair programming, etc..." and doesn't work when it gets to test, you have a problem.
in these cases, "doesn't work" is a matter of interpretation. It's usually a defect or omission in the spec.
Personally? (Score:2)
Personally, I like speed. It must be fast, you can comment out a nice readable version, but the one to be compiled must be fast.
Re: (Score:2)
Re: (Score:2)
If you focus on fast, you should definitely do a profile-first-optimize-last approach so you're actually optimizing code that the computer spends most of it's time running.
If you're optimizing fringe functions, then it better
Comment removed (Score:5, Funny)
Rhyming variable names (Score:4, Funny)
If you have no rhyming variable names, then your code sucks. 1 stars
If you have one or two, it is barely acceptable. 2 stars
Half rhyme, then 3 stars.
If most, but not all, rhyme, 4 stars.
If every single variable rhymes with at least one other variable, you have a great job, 5 stars.
To get the coveted 6 stars, all the variable names have to rhyme with each other.
Re: (Score:2)
https://www.youtube.com/watch?... [youtube.com]
Define "Good" (Score:2, Informative)
This type of article comes up continuously on /. and without some concrete defining attribute asking what model/version/etc. of "X" is "Good" is going to turn into a poll.
I would consider "Good" code to have the following attributes:
1. Runs under all operating systems and platforms
2. Source code is readable (note, this does not mean "Well Commented")
3. Takes up the minimum amount of space
4. Operations execute either apparently instantaneously or provides a progress bar for the user
5. Installs quickly
6. It's
Re: (Score:2)
Nothing like starting out of the gate with impossible to achieve goals.
diversity! (Score:4, Funny)
I like eligant code (Score:3)
That is... as brief as it can possibly be to accomplish the stated goal. Very simple.
I also like it when the code is commented properly so that every operation is broken down and and annotated to explain what it is doing.
This lets me go through the whole program and see what it is doing and the way it is doing it very quickly.
The code that makes me crazy is the rube goldberg code that does some thing very simple in the most elaborate way possible, has no annotations so I have no idea what the actual point of the code is, and then to make things worse various parts of the code will randomly switch between doing different things for no reason.
THAT code I hate. I see that shit and I delete it and write over myself.
Part of the problem is that people don't know how to do somethings. They understand the language but they haven't memorized the really short code snippets that are the ideal way of getting from point A to point B. And that's just something a programmer should either have memorized or stored somewhere for recall.
Using those code snippets tends make the code far more elegant and much more readable because you can see beyond the annotations what they're doing because you recognize that snippet.
If they never use them, that is fine too... just so long as they don't make their code look like that breakfast making machine from Chitty Chitty bang bang. If they do that, I will murder them all. :-D
I'd start with (Score:2)
Time (Score:4, Insightful)
After 5 years you can still read it and understand what it was supposed to accomplish, and it does so.
Re: (Score:2)
Scrolled down for this. I would add, "time and testing" and "testing" usually involves wide distribution. Yes, JPEG, PNG and Open Source compression libraries have had bugs, sometimes very serious ones. I still consider it some of the best code out there. I don't think being able to read the code matters. That's a red herring, unless you need to work on it. If everybody needs to work on it, it's too unfinished to be particularly good code. The only thing I've read in some of these libraries is the he
Simple (Score:4, Insightful)
I would definitely add "simple". Everybody can write complex code but it takes experience and great knowledge to be able to choose the best fit for the implementation. More experience and knowledge you have more options to choose from. Beginner will usually go with the first hunch that will get complex sooner or later as he will meet challenges he didn't expect...
So yeah, simple, readable, documented, functional, consistent...
Vowels (Score:2)
Seriously. Good, readable names for everything make code far more self-documenting than otherwise, don't cost the compiler a single cycle, and make it far easier to understand when someone comes across it five years down the road.
Other than that, I'd add methods that only perform one action, with no side effects, and that only work at one level of abstraction.
Finally, code that matches its method name - don't say "if thing.checkValues()", say "if thing.isValid()" - and if isValid() does anything like trimm
It's not that hard. (Score:4, Interesting)
no hungarian notation! (Score:2)
I don't care how bad or tangled the logic but as long as it's not using Hungarian notation [wikipedia.org], It's good.
Re: (Score:2)
Hungarian notation was fabulous for its intended purpose: code that mixed C and assembly language.
Sadly it escaped.
It's good if they don't code like 90s C++ devs (Score:5, Interesting)
Their whole mindset still makes me want to puke.
Obfuscated crap. Techno-machismo teens playing games trying to get their code into the least number of characters and the least amount of memory. I've had to fix or test so much of this junk and it's still just plain stupid.
The *human* part of the system is what *matters* and that includes the code interface. First, I want comments not about *what* is happening. I can read that. I need to know *why* it was done, so I don't undo it, or I can do something different safely. Comments should be one liners, limited to "why" and sometimes "how".
If adding a variable aids readability, add the fucking variable! Shove all the results into a meaningful, readable variable name and then shove *that* into your function argument, not some long series of nested function. It's not the 90s. You don't have to save memory! Memory is there to make your code readable. Use it!
Ok, rant over. I'm going back to work now.
Re: (Score:3)
Techno-machismo teens playing games trying to get their code into the least number of characters and the least amount of memory.
Given how many programs I've used over the past decade that have required unreasonably high amounts of RAM, and/or were subsequent releases of software that solved a particular problem in earlier iterations but required 1/10th the memory to do it, I wouldn't mind a handful of these guys getting their desks back. Adobe is a great place to start.
I've had to fix or test so much of this junk and it's still just plain stupid.
I'm by no means a programmer, but from the handful of times I've seen what you're talking about, I'll say this: if it's possible to save 10% of RAM by shifting the ea
Editable (Score:2)
One of the most important criteria is that good code be easy to modify. Readability, testability, elegance, and simplicity all lead back to that. When you change code, you should be assured that it will do what you expect. Bad code produces surprising side effects when you change it. Good code warns you (possibly through unit tests attached to the code) when you are doing something questionable. If you have to run the code to determine what it does, then that's not good code.
Needs evolve and change ove
Good? (Score:2)
Spaghetti code is good.
With lots of meatballs.
Not a single answer (Score:2)
Slashdot Friday brought to you by ... (Score:2)
The Wayback Machine...
Or, see the Slashdot article, "Beautiful Code Interview [slashdot.org]" that discusses an entire book about the very topic.
Short modules / Clear variable naming (Score:2)
MOST IMPORTANT (Score:2)
Code has to be AVAILABLE - this is the most important. That means it must be OPEN SOURCE.
If it is CRAPPY code, it can be MADE BETTER if it is open source.
If it is INEFFICIENT code, it can be REWRITTEN if it is open source
If it is HARD TO UNDERSTAND code, it can be COMMENTED if it is open source.
So any code that is OPEN SOURCE, even if it is crappy, inefficient and hard to understand, can be improved.
But any code that is CLOSED is absolutely useless in my opinion.
Here's what good code is to me.... (Score:2)
Plan B (Score:2)
... functional, readable, testable ...
From the maintenance perspective, when you can't make the code meet some standard, comments describing what you missed and why (time, spec conflicts, didn't care enough) are helpful. This hints to the next maintainer that modifying a piece of code that missed some good-practices target has additional considerations or hidden pitfalls, or that it can be fixed/extended/replaced with impunity.
Edge cases (Score:2)
Good code has comments for edge cases, I mean "why the fuck are you checking if foo is less than bar?" with "//checking if foo will not overflow because ..."
Edge cases are by definition very unlikely, usually the code that handles them are bugfixes. Too many times I come across code that is full of bugfixes for those edge cases but no comments whatsoever, to me those kind of comments are more important than method comments (aka javadoc).
Elegance. (Score:2)
Good Code Metircs (Score:2)
There are several metrics which can help you to identify code which is not bad. One is cyclomatic complexity. Another are connectivity metrics going over the graph your code spans. For cyclomatic complexity there are good boundaries available. However, it is a complexity metric. And complexity is not the only thing which affects code quality. Other elements are labeling operations, such as methods, functions, and procedures. There is plenty of lit. available in the area of code comprehension.
Solving real problems without excessive complexity (Score:2)
If the code has a useful function and exposes it with an interface that is no more complex than absolutely necessary, it doesn't matter how ugly it is inside. It will be used and, in time, there will be resources to clean it up. UNIX system calls, libraries and command line tools are a good example. There is not much in common between original code and various modern implementations, but code written on top of these over decades still works and both developers and users are able to leverage their experience
Compactness / infimum (Score:3)
A designer knows he has achieved perfection not when there is nothing left to add, but when there is nothing left to take away.
-- Antoine de Saint-Exupéry
Do not add anything to the list (Score:2)
Code needs to be easy to understand, that's all. You can't keep a long list of priorities in your head, that simply doesn't work at all. Just keep one: easy to understand.
Of course it needs to work, but that's obvious so not really worth stating - testable is part of this obviousness, if you need to test it, and you can't, well, then it doesn't work.
Sometimes code needs to be performant, but often this is only the case for small parts of it, so it's better not to think about it or it will tend to compete wi
Depends on the requirements (Score:3)
The best piece of code I ever wrote in my life was nearly 100x faster than the next best algorithm ever written to do that problem. That took the expected run time down from a few days to an hour.
It was not a particularly well-commented piece of code. If it were, it would have been even better.
It was not a particularly obvious algorithm for solving the problem. If it were more obvious why one would choose to do it this way, it would have been even better.
If the primary concern is runtime (because it normally takes days to run), and you literally make it orders of magnitude faster, that's good code. It could be better if it were also better commented and easier to maintain, but those aren't *always* the primary concern (yes, sometimes they are. That's the point -- criteria differ!)
[TMB]
Re: (Score:2)
Cumbered (Score:2)
And this is why closed source combined with black-box development is so much safer than open source. Sigh.
I really don't mind -- actually, I think I'd be kind of of flattered -- if people were able to look at my code, go "hey, I can use that" and then proceed to use it. And in fact, I've written a fair bit of code I think would fall into that vein. I think I could write something book-length in the line of "cool coding stuff" and quite a few programmers would find it quite useful. I've been doing this since
Not being a metric ton of bit rot (Score:2)
Fast; efficient; not bloated; not buggy; respectful of the user's privacy; hardened with regard to hacking if that's relevant; not encumbered by dependencies; adequately featured; well supported; well documented for the end user.
As far as I'm concerned, if you can't hit those 00001000 or 00001001 targets, you should be looking for different line of work.
Of course it is lovely if it's easily read code, well commented, well structured -- but if the former list is covered, I'll give the 00000011 latter a pass.
Re: (Score:2)
PHP can be good or bad, like any other code. Lately it's getting better.
As an example, do you think this looks bad? Looks pretty good to me.
https://github.com/symfony/sym... [github.com]
I have some awful, unreadable examples I could share in Java, PHP, Javascript and even C, but chosen language no longer forces you to write bad code. Maybe Perl, but I haven't seen it lately.
Re: (Score:2)
perl -e 'print $i=pack(c5,(41*2),sqrt(7056),(unpack(c,H)-2),oct(115),10);'
Re: (Score:2)
Does that manual encourage bad code ?
Re: (Score:2)
Any manual that encourages Perl encourages bad code.
Re: (Score:2)
-Meaningless boilerplate comments. Comments on property getters and setters is pure noise.
-Questionable OO design. Why are this class keeping references to serviceReferenceGraph and loggingFormatter which it doesn't use for anything?
-Needless vertical scrolling. Given the triviality of this class, there is no reason for it not to be a one-pager.
-It's in the DependencyInjection namespace, but... doesn't use dependency injection!
-php pretending to be java. WTF is up with th
Re: (Score:2)
Dominance where exactly? A helluva lot of Windows development is still done in C/C++. Java still has massive penetration in the enterprise. I'll admit that .NET is a big player in the Windows world, but considering the Windows market appears to be at best static, and as a platform, compared to other computing devices (enterprise computing, mobile computing, etc.) is in absolute terms possibly even declining, I'd say .NET could hardly be described as dominant.
Re: (Score:2)
Re: (Score:2)
On PC platforms perhaps. Not on server platforms.
Re:It's not polite to talk with your mouth full (Score:4, Insightful)
FACT: The PC to Server ratio is MILLIONS to 1 alone
This does not stand to even 5 ms of thinking. I am living in a country with 5 million people. You are claiming we have 5 servers or something like that.
Or if you are an american: How many cities do you have with more than 5 million people? How many cities with more than 5 servers? ...
Or ... there are about 7 billion people on the earth. Lets assume that each have a PC (many don't). You are claiming there are only 7000 servers on earth.
Re: (Score:2)
You want me to prove there are 7 billion people on earth?! You are more stupid than a kid in first grade.
Re: (Score:2)
A guy whose evidence is "I've seen stats", without linking to them shouldn't be lecturing about hard evidence.
Re: (Score:2)
From the very beginning, .NET was made for brownfield app development - never for speed.
Makes sense. Why would they try to make another C++?
.NET is by no means slow though, as you seem to be implying.
Re:Good code (Score:5, Interesting)
For newly written code, things like readability, testability, and maintainability all can come in to whether it is "good" or not
For legacy stuff, Good code is code that works. Who cares how easy it is to read or test as long as it works?
The second one should also include "immutable". If it's hard to understand it will evolve easily to non working, and time spent on improvements can start to creep up very fast.
I have worked in very clever, solid code, but not easy to read. It was then maintained and extended by average, but competent programmers down the road, and turned into a big mess, only because it was so hard to understand.
In my experience, good code is easy to read, above all. That will make it easy to extend it coherently, find bugs and stuff. Also, if it doesn't work OK, it's easy to find out why. The single metric that saves time, money, and improves quality down the road is readability. Eveything else should be suject to that.
And, about the last point in the "article", "efficient", it's nonsense. Premature optimization is the root of all evil. You should _always_ follow the second rule of optimization (see http://c2.com/cgi/wiki?RulesOfOptimization [c2.com] ).
Re:Compactness and Readability (Score:5, Insightful)
It communicates clearly what it is trying to do.
It doesn't, actually. Looking at that as someone who doesn't know what a CRC32 is I have no idea why it's doing what it's doing. Some actual useful comments might be nice.
Re: (Score:2)
Over-commenting is a very real problem, and CRC32 is CS101. If I was reviewing code which described what CRC32 was, I would remove the comments.
Re: (Score:2)
If I was reviewing code which described what CRC32 was, I would remove the comments.
Well, you are Doctor Evil.
Re: (Score:2)
Re: (Score:2)
Well in this case I'd say there's Google and Wikipedia, use them. The source code is not the right place to teach someone about what CRC32 is or when, where or why you might want to use it. It's almost as bad as comments that try to teach you the programming language you're in. If you're implementing something that's not in an RFC or standard of some sort, I'd agree with you.
Re: (Score:3)
Some actual useful comments might be nice.
Well, when the function is named calculate_crc32()...
Re: (Score:2)
_When_ was the last time you actually needed a different CRC function from the standard 32-bit one?
When trying to create unique crcs to use as hashes for 8 billion pieces of data daily so as to find them quickly. 32 bits isn't enough. 64 bits is way more than enough.
Re: (Score:2)
If you need a 64 bit hash, write a special 64 bit hash function. It's only going to take a few lines, and removes dependencies on bizarre external code, like 64 bit CRC that nobody ever uses.
Besides, CRC functions aren't very good for hashing, as CRC(x) XOR CRC(y) = CRC(x XOR y)
Re: (Score:2)
Good code does one thing well:
It communicates clearly what it is trying to do.
Personally, I'd say that good code does what it is trying to do. Great code will do that and communicate what it is doing clearly.
Re:Well commented. (Score:5, Funny)
Re: (Score:2)
CS is only practical by accident, but that's okay (Score:2)
Computer Science is [a] a misnomer, and [b] more properly a subset of mathematics. I might characterize it more as giving you tools to reason about code rather than teaching coding practices. It is not generally meant to be a practical education. There is always time to learn the practical stuff, and the practical stuff changes often enough that it's not necessarily worth teaching.
I'm in the opposite camp: I'm self taught, and know a bunch about deployment and the intricacies of source control, and refactor