More comments in code or just simple, readable, maintainable code suffices? [closed] - comments

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Sometimes its really difficult to decide on when exactly you have written enough comments for someone to understand your intentions.
I think one needs to just focus more on writing readable, easy to understand code than on including a large number of lines of comments explaining every detail of whats happening.
What are your views about this?

Comments aren't there to explain what you're doing. They're there to explain why you're doing it.

The argument is based on a false dilemma: Either your code is a horrible abomination and you write tons of comments to explain every statement and expression, or your code is beautiful poetry that can be understood by your grandmother with no documentation at all.
In reality, you should strive for the latter (well, maybe not your grandmother but other developers), but realize that there are times when a couple of comments will clear up an ambiguity or make the next ten lines of code so much more plain. People who advocate no comments at all are extremists.
Of course, gratuitous comments should be avoided. No amount of comments will help bad code be more understandable. They probably just make it worse. But unless you're only coding trivial systems, there will be times when comments will clarify the design decisions being made.
This can be helpful when catching bugs. Literate code can look perfectly legitimate while being completely wrong. Without the comments, others (or you six months later) have to guess about your intent: Did you mean to do that, or was it an accident? Is this the bug, or is it somewhere else? Maybe I should refer to the design documentation... Comments are inline documentation, visible right where you need it.
Properly deciding when the need for comments actually exists is the key.

Try to make the code self-explaining. One of the most important things is to use meaningful names for classes, functions, variables etc.
Comment the sections that aren't self-explaining. Trivial commenting (e.g. i++; // Add 1 to i) makes the code harder to read.
By the way - the closer to pseudocode you can work, the more self-explaining your code can become. This is a privilege of high-level languages; it's hard to make self-explaining assembly code.

Not all code is self-documenting.
I'm in the process of troubleshooting a performance issue now. The developer thought he discovered the source of the bottleneck; a block of code that was going to sleep for some reason. There were no comments around this code, no context as to why it was there. We removed the block and re-tested. Now, the app is failing under load where it wasn't before.
My guess is someone had previously run into a performance issue and put this code in to mitigate the problem. Whether or not that was the right solution is one thing, but a few comments about why this code is there would now be saving us a world of pain and a whole lot of time...

Why you need comments. The name of the method should be clear enough that you don't need comments.
Ex:
// This method is used to retrieve information about contact
public getContact()
{
}
In this case getContact doesn't need the comments

Aim for code that needs no comments, but don't beat yourself up too much if you miss.

I think commenting enough so that you could understand it if you had to review your code later in life should be sufficient.
I think there would a lot of time wasted if you commented for everyone; and going this route could make your code even harder to understand.
I agree that writing readable code is probably the most important part, but don't leave out comments. Take the extra time.

Readable code should be the number 1 priority. Comments are, as Paul Tomblin already wrote, to focus on the why part.

I try to avoid commenting as much as possible. Code should be self explanatory. Name variables and methods properly. Break large code blocks in methods which have a good name. Write methods that do one thing, the thing you named them for.
If you need to write a comment. Make it short. I often have the feeling that if you need to elaborate long on why this code block does this and that you already have a problem with the design.

Only comment when it adds something.
Something like this is useless and definitely decreases readability:
/// <summary>Handles the "event" event</summary>
/// <param name="sender">Event sender</param>
/// <param name="e">Event arguments</param>
protected void Event_Handler (object sender, EventArgs e)
{
}

Basically, putting aside a good but possibly brief comment at the beginning of a class/method/function declaration, and - if necessary - an introductory comment at the beginning of the file, a comment would be useful when a not-so-common or not-so-clearly-transparent operation is coded.
So, for example, you should avoid commenting what's obvious (i++; on a previous example), but what you know is less obvious and/or more tricky should deserve some clear, unconfusing, brilliant, complete line of comment, which naturally comes along with a Nobel prize for the clearest code in history ;).
And don't underestimate the fact that a comment should be also funny; programmers read much more gladly if you can intellectually tease them.
So, as a general principle tend to not be overwhelming with comments, but when you have to write one, be sure about it to be the clearest comment you could write down.
And personally I'm not a big fan of self-documenting code (a.k.a. code w/o a single damn slashstar): after months you've written it (it's just days for my personal scale) it's very likely you couldn't tell the true reason for choosing such design to represent that piece of your intelligence, so how could others?
Comments are not just that green stuff among code lines; they are the part of code which your brain is better willing to compile. Qualifying as braincode (laughing) I couldn't affirm comments are not part of the program you're writing. They're just the part of it which is not directed to the CPU.

Normally, I'm a fan of documentation comments that clearly spell out the intent of the code you're writing. Spiffy tools like NDoc and Sandcastle provide a nice, consistent way in which to write that documentation.
However, I've noticed a few things over the years.
Most documentation comments don't really tell me anything I can't really glean from the code. That assumes, of course, that I can make heads or tails out of the source code to begin with.
Comments are supposed to be used to document intent, not behavior. Unfortunately, in the vast majority of cases, this isn't how they're used. Tools like NDoc and Sandcastle only propagate the incorrect use of comments by providing a plethora of tags that encourage you to provide comments that tell the reader things that he should be able to discern from the code itself.
Over time, the comments tend to fall out of synch with the code. This tends to be true regardless of whether or not we're using documentation software, which purports to make documentation easier because it puts the documentation closer to the code it describes. Even though the documentation is right there next to the method, property, event, class, or other type, developers still have a hard time remembering to update it if and when the intrinsic behavior changes. Consequently, the documentation loses its value.
It's worth noting that these problems are, by and large, due to the misuse of comments. If comments are used solely as a means of conveying intent, these issues go the way of the dodo, since the intent of any given type or its members is unlikely to change over time. (If it does, a better plan is to write a new member and deprecate the old one with a reference to the new one.)
Comments can have immense value if they are used properly. But that means knowing what they are best used for, and constraining their use to that scope. If you fail to do that, what you end up with is a plethora of comments that are incorrect, misleading, and a source of busywork (at increased cost) since you now have to either remove them or somehow get them corrected.
It's worth it to have a strategy for using comments in a meaningful way that prevents them from becoming a time, energy, and money sink.

Studies have stated that optimal readability happens when you have about 1 line of comments for 10 lines of code. Of course, that's not to say that you need to keep your ration at 1/10 and panic if you go over. But it's a good way to give you an idea of how much you should be commenting.
Also remember that comments are a code smell. That is to say that they may be indicative of bad code but aren't necessarily so. The reason for this is that code that is more difficult to understand is commented more.

Related

What are the different code comment practices?

Reading up on code commenting, there seems to be a general support for comments that do not explain anything the code itself can explain. All the sources (not that many, but a few still) I have looked up say that the comments should be explaining the code on a higher level of abstraction.
However, experts in the field I socialise and work with are supporting that more comments are better than not enough, that even if the comments explain something that the reader/coder can decipher from the code, there are different levels of this, and some people may decipher the code faster than others, so to be safe it would be better to comment code whose meaning is not painfully obvious; after all,
"it will help you, as a coder, when you don't have to read the actual code, and can understand what a function does in English, rather than try and decipher code. Sometimes, it might even help writing the function out in comments and pseudocode before coding it; It will help as a constant reminder of what this function is supposed to do."
These two are quite different schools of thought as far as comments go. Which begs the question:
What are the different schools of thought about code commenting, and what are the most popular (so as to avoid asking about the best ones, as that is subjective) sources I can read up on about code commenting practices?
This is a fairly sharp write-up called The Fine Art of Commenting over at ic#code. It's not perfect (Hungarian notation is horrible and should not be inflicted on developers), but it is still fairly interesting.
The author correctly notes that there are different things you may want to use comments for, and splits them into 3 classes:
Documentary comments, for example copyright information, authorship, and version and changes information.
Functional comments, which are your various "TODO" and "BUG" comments signaling out areas of code that may require further attention.
Explanatory comments, which explain what the code does.
The third category is obviously the interesting one being discussed here. In my opinion, comments should describe why the code does why it does, and not how. For example, if your codes sorts a list, you should explain why the list has to be sorted in the first place - that the list is being sorted is (or should be) obvious from the code.
Finally, the most important thing about comments is that they are not compiled and have no effect on the behavior of the program. This may seem obvious. The consequence of this is that during the maintenance phase of the software, bugs in the code may be fixed, but the comments often remain unchanged, and may document behavior that is no longer observed. As wrong documentation is even less useful than non-existent documentation, it is very important to fix bugs in the comments as well as in the actual code.

How much duplicated code do you tolerate? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
In a recent code review I spotted a few lines of duplicated logic in a class (less than 15 lines). When I suggested that the author refactor the code, he argued that the code is simpler to understand that way. After reading the code again, I have to agree extracting the duplicated logic would hurt readability a little.
I know DRY is guideline, not an absolute rule. But in general, are you willing to hurt readability in the name of DRY?
Refactoring: Improving the Design of Existing Code
The Rule of Three
The first time you do something, you
just do it. The second time you do
something similar, you wince at the duplication, but you do the duplicate
thing anyway. The third time you do something similar, you refactor.
Three strikes and you refactor.
Coders at Work
Seibel: So for each of these XII calls you're writing an
implementation.
Did you ever find that you were accumulating lots of
bits of very similar code?
Zawinski: Oh, yeah, definitely. Usually by the second or third time
you've cut and pasted
that piece of code it's like, alright, time to stop
cutting and pasting and put it in a
subroutine.
I tolerate none. I may end up having some due to time constraints or whatnot. But I still haven't found a case where duplicated code is really warranted.
Saying that it'll hurt readability only suggests that you are bad at picking names :-)
Personally, I prefer keeping code understandable, first and foremost.
DRY is about easing the maintenance in code. Making your code less understandable in order to remove repeated code hurts the maintainability more, in many cases, than having some repeated lines of code.
That being said, I do agree that DRY is a good goal to follow, when practical.
If the code in question has a clear business or technology-support purpose P, you should generally refactor it. Otherwise you'll have the classic problem with cloned code: eventually you'll discover a need to modify code supporting P, and you won't find all the clones that implement it.
Some folks suggest 3 or more copies is the threshold for refactoring. I believe that if you have two, you should do so; finding the other clone(s) [or even knowing they might exist] in a big system is hard, whether you have two or three or more.
Now this answer is provided in the context of not having any tools for finding the clones. If you can reliably find clones, then the original reason to refactor (avoiding maintenance errors) is less persausive (the utility of having a named abstraction is still real). What you really want is a way to find and track clones; abstracting them is one way to ensure you can "find" them (by making finding trivial).
A tool that can find clones reliably can at least prevent you from making failure-to-update-clone maintenance errors. One such tool (I'm the author) is the CloneDR. CloneDR finds clones using the targeted langauge structure as guidance, and thus finds clones regardless of whitespace layout, changes in comments, renamed variables, etc. (It is implemented for a number a languages including C, C++, Java, C#, COBOL and PHP). CloneDR will find clones across large systems, without being given any guidance. Detected clones are shown, as well as the antiunifier, which is essentially the abstraction you might have written instead. Versions of it (for COBOL) now integrate with Eclipse, and show you when you are editing inside a clone in a buffer, as well as where the other clones are, so that you may inspect/revise the others while you are there. (One thing you might do is refactor them :).
I used to think cloning was just outright wrong, but people do it because they don't know how the clone will vary from the original and so the final abstraction isn't clear at the moment the cloning act is occurring. Now I believe that cloning is good, if you can track the clones and you attempt to refactor after the abstraction becomes clear.
As soon as you repeat anything you're creating multiple places to have make edits if you find that you've made a mistake, need to extend it, edit, delete or any other of the dozens of other reasons you might come up against that force a change.
In most languages, extracting a block to a suitably named method can rarely hurt your readability.
It is your code, with your standards, but my basic answer to your "how much?" is none ...
you didn't say what language but in most IDEs it is a simple Refactor -> Extract Method. How much easier is that, and a single method with some arguments is much more maintainable than 2 blocks of duplicate code.
Very difficult to say in abstract. But my own belief is that even one line of duplicated code should be made into a function. Of course, I don't always achieve this high standard myself.
Refactoring can be difficult, and this depends on the language. All languages have limitations, and sometimes a refactored version of duplicated logic can be linguistically more complex than the repeated code.
Often duplications of code LOGIC occur when two objects, with different base classes, have similarities in the way they operate. For example 2 GUI components that both display values, but don't implement a common interface for accessing that value. Refactoring this kind of system either requires methods taking more generic objects than needed, followed by typechecking and casting, or else the class hierarchy needs to be rethought & restructured.
This situation is different than if the code was exactly duplicated. I would not necessarily create a new interface class if I only intended it to be used twice, and both times within the same function.
The point of DRY is maintainability. If code is harder to understand it's harder to maintain, so if refactoring hurts readability you may actually be failing to meet DRY's goal. For less than 15 lines of code, I'd be inclined to agree with your classmate.
In general, no. Not for readability anyway. There is always some way to refactor the duplicated code into an intention revealing common method that reads like a book, IMO.
If you want to make an argument for violating DRY in order to avoid introducing dependencies, that might carry more weight, and you can get Ayende's opinionated opinion along with code to illustrate the point here.
Unless your dev is actually Ayende though I would hold tight to DRY and get the readability through intention revealing methods.
BH
I accept NO duplicate code. If something is used in more than one place, it will be part of the framework or at least a utility library.
The best line of code is a line of code not written.
It really depends on many factors, how much the code is used, readability, etc. In this case, if there is just one copy of the code and it is easier to read this way then maybe it is fine. But if you need to use the same code in a third place I would seriously consider refactoring it into a common function.
Readability is one of the most important things code can have, and I'm unwilling to compromise on it. Duplicated code is a bad smell, not a mortal sin.
That being said, there are issues here.
If this code is supposed to be the same, rather than is coincidentally the same, there's a maintainability risk. I'd have comments in each place pointing to the other, and if it needed to be in a third place I'd refactor it out. (I actually do have code like this, in two different programs that don't share appropriate code files, so comments in each program point to the other.)
You haven't said if the lines make a coherent whole, performing some function you can easily describe. If they do, refactor them out. This is unlikely to be the case, since you agree that the code is more readable embedded in two places. However, you could look for a larger or smaller similarity, and perhaps factor out a function to simplify the code. Just because a dozen lines of code are repeated doesn't mean a function should consist of that dozen lines and no more.

Are you concerned about the aesthetics of your code? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 8 years ago.
Improve this question
I don't know if I'm the only person in the world which gets a bad feeling in my stomach if my code isn't "pretty". For example if I get a assignment that another person has been doing before me. I can't help it to clean the code and make it look "pretty". I don't know if it's some kind of OCD.
It's like I see the code as some kind of art that has be perfect in my own code convention to look good. I don't know if you understand what I'm trying to explain here.
But are you like me, trying always to make my code look good in a aesthetical point of view even though it won't make the code better?
Yes, I care about code aesthetics.. Code that is aestheticly pleasing is easy to read and therefore easy to understand.
No, I stopped trying anymore. You can't defeat an army of code monkeys.
Only with my personal project I'm aspired to make it perfect.
I think Robert Martin described it best in his Book Clean Code:A Handbook of Agile
Software Craftsmanship
It’s not enough to write the code
well. The code has to be kept clean
over time. We’ve all seen code rot and
degrade as time passes. So we must
take an active role in preventing this
degradation.
The Boy Scouts of America have a
simple rule that we can apply to our
profession.
Leave the campground cleaner than you
found it.
If we all checked-in our code a little
cleaner than when we checked it out,
the code simply could not rot. The
cleanup doesn’t have to be something
big. Change one variable name for the
better, break up one function that’s a
little too large, eliminate one small
bit of duplication, clean up one
composite if statement.
Can you
imagine working on a project where the
code simply got better as time passed?
Do you believe that any other option
is professional? Indeed, isn’t
continuous improvement an intrinsic
part of professionalism?
If you mean identation, I think it is essential.
If you mean readable (which for me is different from aesthetically pretty), it is also essential.
If you want what's written to look like flowers and birds flying, then no. I'm not concerned. :P
I hate that my collegues always write one letter variables, short named methods that start with underscores and generally ugly code. It seems to be the standard practice around these parts.
I always make my code look good. It's a visual representation of who I am, so I have to maintain it nice and neat, and properly indented.
I'm not so much concerned with whether or not it looks nice as much as with how readable it is. It just so happens that "prettier" code is usually easier to read and maintain.
Formatting code is one way (and possibly the most bang for your buck way at that) to make your code readable. Being confronted with readable code makes stepping through your program easier (whether in a debugger or code review). The same goes for sensible variable names and thinking about variable scope.
If, however, you're spending all of your time changing some perfectly acceptable notation for fields, locals, pointers etc. into some very personal Ancide-notation, then I'd be inclined to say that isn't really necessary.
I too find myself in such a position. Since clean code is easy to read and maintain, I always try to clean up and style my code.
I do that as well. I find that making the code look good makes it easier to read and understand.
Yes, I like to make the code look better, because it makes easier to maintain and it looks like people are concerned on making a good system.
When the code looks ugly, you don't feel yourself motivated to keep it cool.
And I feel i'm so concerned that i think my co-workers hate me =P
I make very good use of the build-in code formatter within Visual Studio. In Delphi, I even use an add-in that allows me to format my Delphi code. I also try to keep each source file below the 1000 lines of code, although I'm not worried if some files are becoming longer. I use descriptive variable names and occasionally add some additional comments when I suspect that the code (and names for fields, classes and parameters) isn't clear enough for the next one reading my code.
The result is very rewarding since I once had to maintain a piece of code that I wrote 5 years earlier. It's readability made my own pieces of code in the project still very readable. Others have been more careless, though. It gave me an easy trick to recognize my own code from the garbage that was added by some inexperienced semi-programmer/manager who was only capable of writing macro's in Word and Excel...
"Pretty" and "code aesthetics" are sort of proxy words - those terms sound trivial, but (at least to me) really mean "clearly and logically expressed ideas". Clearly and Logically expressed ideas matter.
Tidy code is more maintainable. Your brain is able to do amazing automated pattern matching on code, so you will often find that you spot bugs and problems in code just because it is the wrong "shape". I find tidiness so important I wrote a VS addin (AtomineerUtils) for adding and formatting doc comments to minimise the work I need to go to in order to keep my code tidy.
Of course, that's no reason to reformat someone else's code - you'll only upset other programmers if you change their code to your style for aesthetic reasons, not to mention you're spending a lot of time that could be put into new code, and every line of code you change is another potential bug that needs to be re-tested. So try to stop yourself going "too far".
I wouldn't go so far as to make things look aesthetically good purely for the aesthetic value, but I do think it's really important to write code that's readable and easily understood at a glance. Especially when writing things like XML/HTML, things like proper nesting and indentation can really make it easy to quickly get a sense of the structure and allow you to spend your time zeroing in on the areas that you care about. A short, well-organized method that's easy to read visually will save time and energy vs. something that takes ten minutes to understand.
Yeah, I have to have the code indented with spaces and tab 4 spaces wide and if it is C/C++/Java code put curly brace in its own line, Emacs macros do the rest :-)
Yes, I do. And because "you can't [indeed] fight an army of monkey" (if I may borrow this from one answer), I tend to try making this less painful and to automate what can be automated, e.g. performing cosmetic checks during the build (that will break if necessary). Another option would be to format code automatically on commit but I prefer the first one.
PS: I'm using Jalopy and Maven for this when doing Java.
Define "aesthetics." I think it means different things to different people.
The absolute most important thing to me about any code that I write (despite hasty code samples posted here) is that it works as intended. Once it works as intended, then, and only then, do I worry about the aesthetics.
Aesthetics are subjective. I may spend labor to make my code a work of art in my eyes, and someone else may come behind me and labor to change it to conform to their sense of what constitutes "beautiful code." After all, do you include design patterns, coding standards, naming conventions, and who-knows-what-else in that? Or is it a simple matter of indentation, curly brace alignment, type-alignment in variable declaration, and so forth?
No two developers will completely agree on what constitutes aesthetically pleasing code. That's not to say that you shouldn't strive to create it; but it should not be your number one priority. Writing working, maintainable code should be your number one priority. If it happens to be aesthetically pleasing as a result of that, so be it.
So your the guy making merging a complete nightmare? Undoing all the formatting that is aesthetically pleasing to me, the writer and primary maintainer of that code you just checked in?
Yes, I am shamelessly trying to acquire StackOverflow karma with silly questions.

What does a good programmer's code look like? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I am a hobbyist programmer (started with VBA to make excel quicker) and have been working with VB.NET / C#.NET and am trying to learn ADO.NET.
A facet of programming that has always frustrated me is what does 'good' look like? I am not a professional so have little to compare against. What makes a better programmer?
Is it:
They have a better understanding of
all the objects / classes / methods
in a given language?
Their programs are more efficient?
The design of their programs are much
better in terms of better
documentation, good choice of names
for functions etc.?
Put another way, if I were to look at the code of a professional programmer, what is the first thing that I would notice about their code relative to mine? For example, I read books like 'Professional ASP.NET' by Wrox press. Are the code examples in that book 'world class'? Is that the pinnacle? Would any top-gun programmer look at that code and think it was good code?
The list below is not comprehensive, but these are the things that I thought of in considering your question.
Good code is well-organized. Data and operations in classes fit together. There aren't extraneous dependencies between classes. It does not look like "spaghetti."
Good code comments explain why things are done not what is done. The code itself explains what is done. The need for comments should be minimal.
Good code uses meaningful naming conventions for all but the most transient of objects. the name of something is informative about when and how to use the object.
Good code is well-tested. Tests serve as an executable specification of the code and examples of its use.
Good code is not "clever". It does things in straightforward, obvious ways.
Good code is developed in small, easy to read units of computation. These units are reused throughout the code.
I haven't read it yet, but the book I'm planning to read on this topic is Clean Code by Robert C. Martin.
The first thing you'd notice is that their code follows a consistent coding-style. They always write their structure blocks the same, indent religiously and comment where appropriate.
The second things you'd notice is that their code is segmented into small methods / functions spanning no more than a couple dozen lines at the most. They also use self describing method names and generally their code is very readable.
The third thing you'd notice, after you messed around with the code a little is that the logic is easy to follow, easy to modify - and therefore easily maintainable.
After that, you'll need some knowledge and experience in software design techniques to understand the specific choices they took constructing their code architecture.
Regarding books, I haven't seen many books where the code could be considered "world-class". In books they try mostly to present simple examples, which might be relevant to solving very simple problems but aren't reflective of more complex situations.
Quoting Fowler, summizing readability:
Any fool can write code that a computer can understand.
Good programmers write code that humans can understand.
'nough said.
Personally, I'll have to quote "The Zen of Python" by Tim Peters. It tells Python programmers what their code should look like, but I find that it applies to basically all code.
Beautiful is better than ugly. Explicit is better than
implicit. Simple is better than complex. Complex is better
than complicated. Flat is better than nested. Sparse is
better than dense. Readability counts. Special cases
aren't special enough to break the rules. Although practicality
beats purity. Errors should never pass silently. Unless
explicitly silenced. In the face of ambiguity, refuse the
temptation to guess. There should be one-- and preferably only
one --obvious way to do it. Although that way may not be obvious
at first unless you're Dutch. Now is better than never.
Although never is often better than right now. If the
implementation is hard to explain, it's a bad idea. If the
implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!
Code is poetry.
Start from this point of logic and you can derive many of the desirable qualities of code. Most importantly, observe that code is read far more than it is written, hence write code for the reader. Rewrite, rename, edit, and refactor for the reader.
A follow on corollary:
The reader will be you at time n from the code creation date. The payoff of writing code for the reader is a monotonically increasing function of n. A reader looking at your code for the first time is indicated by n == infinity.
In other words, the larger the gap of time from when you wrote the code to when you revisit the code, the more you will appreciate your efforts to write for the reader. Also, anyone you hand your code off to will gain great benefit from code written with the reader as the foremost consideration.
A second corollary:
Code written without consideration for the reader can be unnecessarily difficult to understand or use. When the consideration for the reader drops below a certain threshold, the reader derives less value from the code than the value gained by rewriting the code. When this occurs the previous code is thrown away and, tragically, much work is repeated during the rewrite.
A third corollary:
Corollary two has been known to repeat itself multiple times in a vicious cycle of poorly documented code followed by forced rewrites.
I've been programming for 28 years and I find this a tough question to answer. To me good code is a complete package. The code is cleanly written, with meaningful variable and method names. It has well placed comments that comment the intent of the code and doesn't just regurgitate the code you can already read. The code does what it is supposed to in an efficient manner, without wasting resources. It also has to be written with an eye towards maintainability.
The bottom line though is that it means different things to different people. What I might label as good code someone else might hate. Good code will have some common traits which I think I've identified above.
The best thing you can do is expose yourself to code. Look at other people's code. Open Source projects are a good source for that. You will find good code and bad code. The more you look at it, the better you will recognize what you determine to be good code and bad code.
Ultimately you will be your own judge. When you find styles and techniques you like adopt them, over time you will come up with your own style and that will change over time. There is no person on here that can wave a wand and say what is good and that anything else is bad.
Read the book Code Complete. This explains a lot of ideas about how to structure code and the the reasons for doing so. Reading it should short-circuit your time to aquiring the experience necessary to tell good from bad.
http://www.amazon.com/Code-Complete-Practical-Handbook-Construction/dp/0735619670/ref=pd_bbs_sr_1?ie=UTF8&s=books&qid=1229267173&sr=8-1
Having been programming for nearly 10 years now myself and having worked with others I can say without bias that there is no difference between a good programmer and an average programmers code
All programmers at a competent level:
Comment Correctly
Structure Efficiently
Document Cleanly
I once overheard a co-worker say "I've always been very logical and rational minded. I think that's why I enjoy developing"
That in my opinion, is the mind of an average programmer. One who sees the world in terms of rules and logic and ultimately obeys those rules when designing and writing a program.
The expert programmer, understands the rules, but also their context. This ultimately leads to them coming up with new ideas and implementations, the mark of an expert programmer. Programming is ultimately an art form.
Succinctly put, a good programmer's code can be read and understood.
In my opinion, a good programmer's code is language-agnostic; well-written code can be read and understood in a short amount of time with minimal thinking, regardless of the programming language used. Whether the code is in Java, Python, C++ or Haskell, well-written code is understandable by people who don't even program in that particular language.
Some characteristics of code that is easy to read are, methods that are well-named, absence of "tricks" and convoluted "optimization", classes are well-designed, to name a few. As others have mentioned, coding style is consistent, succinct and straight-forward.
For example, the other day, I was taking a look at the code for TinyMCE to answer one of the questions on Stack Overflow. It is written in JavaScript, a language that I've hardly used. Yet, because of the coding style and the comments that are included, along with the structuring of the code itself, it was fairly understandable, and I was able to navigate through the code in a few minutes.
One book that was quite an eye-opener for me in the regard of reading good programmer's code is Beautiful Code. It has many articles written by authors of various programming projects in various programming languages. Yet, when I read it, I could understand what the author was writing in his code despite the fact that I've never even programmed in that particular language.
Perhaps what we should keep in mind is that programming is also about communication, not only to the computer but to people, so good programmer's code is almost like a well-written book, which can communicate to the reader about the ideas it wants to convey.
Easy to read
easy to write
easy to maintain
everything else is filigree
Good code should be easily understood.
It should be well commented.
Difficult parts should be even better commented.
Good code is readable. You'd have no trouble understanding what the code is doing on the first read through of code written by a good professional programmer.
Rather then repeat everyone else's great suggestions, I will instead suggest that you read the book Code Complete by Steve McConnell
Essentially it is a book packed full of programming best practices for both functionality and style.
[Purely subjective answer]
For me, good code is a form of art, just like a painting. I might go further and say that it's actually a drawing that includes characters, colors, "form" or "structure" of code, and with all this being so readable/performant. The combination of readability, structure (i.e. columns, indentation, even variable names of the same length!), color (class names, variable names, comments, etc.) all make what I like to see as a "beautiful" picture that can make me either very proud or very detestful of my own code.
(As said before, very subjective answer. Sorry for my English.)
I second the recommendation of Bob Martin's "Clean Code".
"Beautiful Code" was highly acclaimed a couple of years ago.
Any of McConnell's books are worth reading.
Perhaps "The Pragmatic Programmer" would be helpful, too.
%
Just wanted to add my 2 cents... comments in your code -- and your code itself, generally -- should say what your code does, now how it does it. Once you have the concept of 'client' code, which is code that calls other code (simplest example is code that calls a method), you should always be most worried about making your code comprehensible from the "client's" perspective. As your code grows, you'll see that this is... uh, good.
A lot of the other stuff about good code is about the mental leaps that you'll make (definitely, if you pay attention)... 99% of them have to do with doing a bit more work now to spare you a ton of work later, and reusability. And also with doing things right: I almost always want to run the other way rather than using regular expressions, but every time I get into them, I see why everybody uses them in every single language I work in (they're abstruse, but work and probably couldn't be better).
Regarding whether to look at books, I would say definitely not in my experience. Look at APIs and frameworks and code conventions and other people's code and use your own instincts, and try to understand why stuff is the way it is and what the implications of things are. The thing that code in books almost never does is plan for the unplanned, which is what error checking is all about. This only pays off when somebody sends you an email and says, "I got error 321" instead of "hey, the app is broke, yo."
Good code is written with the future in mind, both from the programmer's perspective and the user's perspective.
This is answered pretty well in Fowler's book, "Refactoring", It's the absence of all the "smells" he describes throughout the book.
I haven't seen 'Professional ASP.NET', but I'd be surprised if it's better than OK. See this question for some books with really good code. (It varies, of course, but the accepted answer there is hard to beat.)
This seems to be (should be) a FAQ. There is an ACM article about beautiful code recently. There seems to be a lot of emphasis on easy to read/understand. I'd qualifier this with "easy to read/understand by domain experts". Really good programmers tend to use the best algorithms (instead of naive easy to understand O(n^2) algorithms) for any given problems, which could be hard to follow, if you're not familiar with the algorithm, even if the good programmer gives a reference to the algorithm.
Nobody is perfect including good programmers but their code tend to strive for:
Correctness and efficiency with proven algorithms (instead of naive and adhoc hacks)
Clarity (comment for intent with reference to non-trivial algorithms)
Completeness to cover the basics (coding convention, versioning, documentation, unit tests etc.)
Succinctness (DRY)
Robustness (resilient to arbitrary input and disruption of change requests)
i second the recommendation for uncle bob's "clean code". but you may wish to take a look at http://www.amazon.com/Implementation-Patterns-Addison-Wesley-Signature-Kent/dp/0321413091 as i think this deals with your specific question a bit better. good code should leap off the page and tell you what it does/how it works.
Jeff Atwood wrote a nice article about how coders are Typists first reference:
http://www.codinghorror.com/blog/archives/001188.html
When being a typist you always need to be elegant in your work, having strucutre and proper "grammar" is highly important. Now converting this to "programming"-typing would catch the same outcome.
Structure
Comments
Regions
I'm a software engineere which means during my education i've come across many different languages but my programming always "feel" the same, as my writing does on fekberg.wordpress.com, i have a "special" way for typing.
Now programming different applications and in different languages, such as Java, C#, Assembler, C++,C i've come to the "standard" of writing that i like.
I see everything as "boxes" or regions and each region has it's explaining commenting. A region might be "class Person" and inside this Region i have a couple of methods for properties, which i may call "Access Methods" or such and each property and region has it's own explaining commenting.
This is highly important, i always see my code that i do, as "being a part of an api", when creating an API structure and elegance is VERY important.
Think about this. Also read my paper on Communication issues when adapting outsourcing which explains in rough, how bad code can conflict, Enterpret as you like: http://fekberg.wordpress.com/2008/12/14/communication-issues-when-adapting-outsourcing/
Good code is easy to understand, easy to maintain, and easy to add to. Ideally, it is also as efficient as possible without sacrificing other indicators.
Great code to me is something that is simple to grasp yet sophisticated. The things that make you go, "wow, of course, why didn't I think of it that way?". Really good code is not hard to understand, it simply solves the problem at hand in a straight-forward way (or a recursive way, if that is even simpler).
Good code is where you know what the method does from the name. Bad code is where you have to work out what the code does, to make sense of the name.
Good code is where if you read it, you can understand what it's doing in not much more time than it takes to read it. Bad code is where you end up looking at it for ages trying to work out wtf it does.
Good code has things named in such a way as to make trivial comments unnecessary.
Good code tends to be short.
Good code can be reused to do what it does anywhere else, since it doesn't rely on stuff that is really unrelated to its purpose.
Good code is usually a set of simple tools to do simple jobs (put together in well organised ways to do more sophisticated jobs). Bad code tends to be huge multi-purpose tools that are easy to break and difficult to use.
Code is a reflection of a programmer's skills and mindset. Good programmers always have an eye on the future - how the code will function when requirements or circumstances are not exactly what they are today. How scalabale it will be? How convenient it will be when I am not the one maintaining this code? How reusable the code will be, so that someone else doing similar stuff can reuse the code and not write it again. What when someone else is trying to understand the code that I have written.
When a programmer has that mindset, all the other stuff falls in place nicely.
Note: A code base is worked on by many programmers over time and typically there is not a specific designation of code base to a programmer. Hence good code is a reflection of all the company's standards and quality of their workforce.
(I use "he" below because this is the person that I aspire to be, sometimes with success).
I believe that the core of a good programmer's philosophy is that he is always thinking "I am coding for myself in the future when I will have forgotten all about this task, why I was working on it, what were the risks and even how this code was supposed to work."
As such, his code has to:
Work (it doesn't matter how fast code gets to the wrong answer. There's no partial credit in the real world).
Explain how he knows that this code works. This is a combination of documentation (javadoc is my tool of choice), exception handling and test code. In a very real sense, I believe that, line for line, test code is more valuable than functional code if for no other reason than it explains "this code works, this is how it should be used, and this is why I should get paid."
Be maintained. Dead code is a nightmare. Legacy code maintenance is a chore but it has to be done (and remember, it's "legacy" the moment that it leaves your desk).
On the other hand, I believe that the good programmer should never do these things:
Obsess over formatting. There are plenty of IDEs, editors and pretty-printers that can format code to exactly the standard or personal preference that you feel is appropriate. I use Netbeans, I set up the format options once and hit alt-shift-F every now and then. Decide how you want the code to look, set up your environment and let the tool do the grunt work.
Obsess over naming conventions at the expense of human communication. If a naming convention is leading you down the road of naming your classes "IElephantProviderSupportAbstractManagerSupport" rather than "Zookeeper", change the standard before you make it harder for the next person.
Forget that he works as a team with actual human beings.
Forget that the primary source of coding errors is sitting at his keyboard right now. If there's a mistake or an error, he should look to himself first.
Forget that what goes around comes around. Any work that he does now to make his code more accessible to future readers will almost certainly benefit him directly (because who's going to be the first person asked to look at his code? He is).
It works
It has unit tests that prove that it works
The rest is icing...
The best code has a certain elegance that you recognise as soon as you see it.
It looks crafted, with care and attention to detail. It's obviously produced with someone with skill and has an art about it - you could say it looks sculpted and polished, rather than rough and ready.
It's consistent and reads easily.
It's split into small, highly cohesive functions each of which do one thing and do it well.
It's minimally coupled, meaning that dependencies are few and strictly controlled,
usually by...
Functions and classes have dependencies on abstractions rather than implementations.
Ironically the better the programmer the less indispensable he/she becomes because the code produced is better maintainable by anyone (as stated by general consent by Eran Galperin).
My experience tells the opposite is also true. The worse the programmer the more difficult to maintain his/her code is, so more indispensable he/she becomes, since no other soul can understand the riddles produced.
I have a good example :
Read GWT (google web tookit) Source code, you will see that every fool understand it (some english books are harder to read than this code).

How do you tell someone they're writing bad code? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Closed 10 years ago.
Locked. This question and its answers are locked because the question is off-topic but has historical significance. It is not currently accepting new answers or interactions.
I've been working with a small group of people on a coding project for fun. It's an organized and fairly cohesive group. The people I work with all have various skill sets related to programming, but some of them use older or outright wrong methods, such as excessive global variables, poor naming conventions, and other things. While things work, the implementation is poor. What's a good way to politely ask or introduce them to use better methodology, without it coming across as questioning (or insulting) their experience and/or education?
Introduce questions to make them realise that what they are doing is wrong. For example, ask these sort of questions:
Why did you decide to make that a global variable?
Why did you give it that name?
That's interesting. I usually do mine this way because [Insert reason why you are better]
Does that way work? I usually [Insert how you would make them look silly]
I think the ideal way of going about this is subtly asking them why they code a certain way. You may find that they believe that there are benefits to other methods. Unless I knew the reason for their coding style was due to misinformation I would never judge my way as better without good reason. The best way to go about this is to just ask them why they chose that way; be sure to sound interested in their reasoning, because that is what you need to attack, not their ability.
A coding standard will definitely help, but if it were the answer to every software project then we'd all be sipping cocktails on our private islands in paradise. In reality, we're all prone to problems and software projects still have a low success rate. I think the problem would mostly stem from individual ability rather than a problem with convention, which is why I'd suggest working through the problems as a group when a problem rears its ugly head.
Most importantly, do NOT immediately assume that your way is better. In reality, it probably is, but we're dealing with another person's opinion and to them there is only one solution. Never say that your way is the better way of doing it unless you want them to see you as a smug loser.
Start doing code reviews or pair programming.
If the team won't go for those, try weekly design reviews. Each week, meet for an hour and talk about a peice of code. If people seem defensive, pick old code that no one is emotionally attached to any more, at least at the beginning.
As #JesperE: said, focus on the code, not the coder.
When you see something you think should be different, but others don't see it the same way, then start by asking questions that lead to the deficiencies, instead of pointing them out. For example:
Globals: Do you think we'll ever want to have more than one of these? Do you think we will want to control access to this?
Mutable state: Do you think we'll want to manipulate this from another thread?
I also find it helpful to focus on my limitations, which can help people relax. For example:
long functions: My brain isn't big enough to hold all of this at once. How can we make smaller pieces that I can handle?
bad names: I get confused easily enough when reading clear code; when names are misleading, there's no hope for me.
Ultimately, the goal is not for you to teach your team how to code better. It's to establish a culture of learning in your team. Where each person looks to the others for help in becoming a better programmer.
Introduce the idea of a code standard. The most important thing about a code standard is that it proposes the idea of consistency in the code base (ideally, all of the code should look like it was written by one person in one sitting) which will lead to more understandable and maintainable code.
You have to explain why your way is better.
Explain why a function is better than cutting & pasting.
Explain why an array is better than $foo1, $foo2, $foo3.
Explain why global variables are dangerous, and that local variables will make life easier.
Simply whipping out a coding standard and saying "do this" is worthless because it doesn't explain to the programmer why it's a good thing.
First, I'd be careful not to judge too quickly. It's easy to dismiss some code as bad, when there might be good reasons why it's so (eg: working with legacy code with weird conventions). But let's assume for the moment that they're really bad.
You could suggest establishing a coding standard, based on the team's input. But you really need to take their opinions into account then, not just impose your vision of what good code should be.
Another option is to bring technical books into the office (Code Complete, Effective C++, the Pragmatic Programmer...) and offer to lend it to others ("Hey, I'm finished with this, anyone would like to borrow it?")
If possible, make sure they understand that you're critizising their code, not them personally.
Suggest a better alternative in a non-confrontational way.
"Hey, I think this way will work too. What do you guys think?" [Gesture to obviously better code on your screen]
Have code reviews, and start by reviewing YOUR code.
It will put people at ease with the whole code review process because you are beginning the process by reviewing your own code instead of theirs. Starting off with your code will also give them good examples of how to do things.
They may think your style stinks too. Get the team together to discuss a consistent set of coding style guidelines. Agree to something. Whether that fits your style isn't the issue, settling on any style as long as it's consistent is what matters.
By example. Show them the right way.
Take it slow. Don't thrash them for every little mistake right off the bat, just start with things that really matter.
The code standard idea is a good one.
But consider not saying anything, especially since it is for fun, with, presumably, people you are friends with. It's just code...
There's some really good advice in Gerry Weinberg's book "The Psychology of Computer Programming" - his whole notion of "egoless programming" is all about how to help people accept criticism of their code as distinct from criticism of themselves.
Bad naming practices: Always inexcusable.
And yes, do no always assume that your way is better... It can be difficult, but objectivity must be maintained.
I've had an experience with a coder that had such horrible naming of functions, the code was worse than unreadable. The functions lied about what they did, the code was nonsensical. And they were protective/resistant to having someone else change their code. when confronted very politely, they admitted it was poorly named, but wanted to retain their ownership of the code and would go back and fix it up "at a later date."
This is in the past now, but how do you deal with a situation where they error is ACKNOWLEDGED, but then protected? This went on for a long time and I had no idea how to break through that barrier.
Global variables: I myself am not THAT fond of global variables, but I know a few otherwise excellent programmers that like them A LOT. So much so that I've come to believe they are not actually all that bad in many situations, as they allow for clarity, ease of debugging. (please don't flame/downvote me :) ) It comes down to, I've seen a lot of very good, effective, bug free code that used global variables (not put in by me!) and great deal of buggy, impossible to read/maintain/fix code that meticulously used proper patterns. Maybe there IS a place (though shrinking perhaps) for global variables? I'm considering rethinking my position based on evidence.
Start a wiki on your network using some wiki software.
Start a category on your site called "best practices" or "coding standards" or something.
Point everyone to it. Allow for feedback.
When you do releases of the software, have the person whose job it is to put code into the build push back on developers, pointing them to the Wiki pages on it.
I've done this in my organization and it took several months for people to really get into the hang of using the Wiki but now it's this indispensable resource.
If you have even a loose standard of coding, being able to point to that, or indicating that you can't follow the code because it's not the correct format may be worthwhile.
If you don't have a coding format, now would be a good time to get one in place. Something like the answers to this question may be helpful: https://stackoverflow.com/questions/4121/team-coding-styles
I always go with the line 'This is what I would do'. I don't try and lecture them and tell them their code is rubbish but just give an alternative viewpoint that can hopefully show them something that is obviously a bit neater.
Have the person(s) in question prepare a presentation to the rest of the group on the code for a representative module they have written, and let the Q&A take care of it (trust me, it will, and if it's a good group, it shouldn't even get ugly).
I do love code, and never had any course in my live about anything related to informatics I started very bad and started to learn from examples, but what I always remember and kept in my mind since I read the "Gang Of Four" book was:
"Everyone can write code that is understood by a machine, but not all can write code that is understood by a human being"
with this in mind, there is a lot to be done in the code ;)
I can't emphasize patience enough. I've seen this exact sort of thing completely backfire mostly because someone wanted the changes to happen NOW. Quite a few environments need the benefits of evolution, not revolution. And by forcing change today, it can make for a very unhappy environment for all.
Buy-in is key. And your approach needs to take into account the environment you are in.
It sounds like you're in an environment that has a lot of "individuality" to it. So... I wouldn't suggest a set of coding standards. It will come across that you want to take this "fun" project and turn it into a highly structured work project (oh great, what's next... functional documents?). Instead, as someone else said, you'll have to deal with it to a certain extent.
Stay patient and work toward educating others in your direction. Start with the edges (points where your code interacts with others) and when interacting with their code try to take it as an opportunity to discuss the interface they've created and ask them if it would be okay with them if it was changed (by you or them). And fully explain why you want the change ("it will help deal with changing subsystem attributes better" or whatever). Don't nit-pick and try to change everything you see as being wrong. Once you interact with others on the edge, they should start to see how it would benefit them at the core of their code (and if you get enough momentum, go deeper and truly start to discuss modern techniques and the benefits of coding standards). If they still don't see it... maybe you'll need to deal with that within yourself (especially on a "fun" project).
Patience. Evolution, not revolution.
Good luck.
I don a toga and open a can of socratic method.
The Socratic Method named after the Classical Greek philosopher Socrates, is a form of philosophical inquiry in which the questioner explores the implications of others' positions, to stimulate rational thinking and illuminate ideas. This dialectical method often involves an oppositional discussion in which the defense of one point of view is pitted against another; one participant may lead another to contradict himself in some way, strengthening the inquirer's own point.
A lot of the answers here relate to code formatting which these days is not particularly relevant, as most IDEs will reformat your code in the style you choose. What really matters is how the code works, and the poster is right to look at global variables, copy & paste code, and my pet peeve, naming conventions. There is such a thing as bad code and it has little to do with format.
The good part is that most of it is bad for a very good reason, and these reasons are generally quantifiable and explainable. So, in a non-confrontational way, explain the reasons. In many cases, you can even give the writer scenarios where the problems become obvious.
I'm not the lead developer on my project and therefore can't impose coding standards but I have found that bad code usually causes an issue sooner rather than later, and when it does i'm there with a cleaner idea or solution.
By not interjecting at the time and taking a more natural approach i've gained more trust with the lead and he often turns to me for ideas and includes me on the architectural design and deployment strategy used for the project.
People writing bad code is just a symptom of ignorance (which is different from being dumb). Here's some tips for dealing with those people.
Peoples own experience leaves a stronger impression than something you will say.
Some people are not passionate about the code they produce and will not listen to anything you say
Paired Programming can help share ideas but switch who's driving or they'll just be checking email on their phone
Don't drown them with too much, I've found even Continuous Integration needed to be explained a few times to some older devs
Get them excited again and they will want to learn. It could be something as simple as programming robots for a day
TRUST YOUR TEAM, coding standards and tools that check them at build time are often never read or annoying.
Remove Code Ownership, on some projects you will see code silos or ant hills where people say thats my code and you can't change it, this is very bad and you can use paired programming to remove this.
Instead of having them write code, have them maintain their code.
Until they have to maintain their steaming pile of spaghetti, they will never understand how bad they are at coding.
Nobody likes to listen someone saying their work sucks, but any sane person would welcome mentoring and ways of avoiding unnecessary work.
One school of teaching even says that you should not point out mistakes, but focus what is done right. For instance, instead of pointing out incomprehensible code as bad, you should point out where their code is particularly easy to read. In the first case you are priming others to think and act like crappy programmers. In the later case you are priming for thinking like a skilled professional.
I have a similar senario with the guys i work with.. They dont have the exposure to coding as much as i do but they are still usefull at coding.
Rather than me letting the do what they want and go back and edit the whole thing. I usually just sit them down and show them two ways of doing things. Thier way and My way, From this we discuss the pro's and cons of each method and therefore come to a better understanding and a better conclusion on how should we go about programming.
Here is the really suprizing part. Sometimes they will come up with questions that even i dont have answers to, and after research we all get a better concept of methodology and structure.
Discuss.
Show them Why
Don't even think you are always right.. Sometimes even they will teach you something new.
Thats what i would do if i was you :D
Probably a bit late after the effect, but that's where an agreed coding standard is a good thing.
I frankly believe that someone's code is better when it's easier to change, debug, navigate, understand, configure, test and publish (whew).
That said I think it is impossible to tell someone his/her code is bad without having a first go at having him / her explaining what it does or how is anyone supposed to enhance it afterwards (like, creating new funcionality or debugging it).
Only then their mind snaps and anyone will be able to see that:
Global variables value changes are almost always untrackable
Huge functions are hard to read and understand
Patterns make your code easier to enhance (as long as you obay to their rules)
( etc...)
Perhaps a session of pair programming should do the trick.
As for enforcing coding standards - it helps but they are too far away from really defining what is good code.
You probably want to focus on the impact of the bad code, rather than what might be dismissed as just your subjective opinion of whether it's good or bad style.
Privately inquire about some of the "bad" code segments with an eye toward the possibility that it is actually reasonable code, (no matter how predisposed you may be), or that there are perhaps extenuating circumstances. If you are still convinced that the code is just plain bad -- and that the source actually is this person -- just go away. One of several things may happen: 1) the person notices and takes some corrective action, 2) the person does nothing (is oblivious, or doesn't care as much as you do).
If #2 happens, or #1 does not result in sufficient improvement from your point of view, AND it is hurting the project, and/or impinging on you enough, then it may be time to start a campaign to establish/enforce standards within the team. That requires management buy-in, but is most effective when instigated from grass roots.
Good luck with that. I feel your pain brother.

Resources