How do you write code that is easily read by other people and who have had no hand in writing any part of it?
This seems an excessively vague question. Remember questions should be as precise as possible and ideally have an objective answer.
Can you fill your question out with some examples of what you mean or the programming context you're in?
Jeffs post "When Understanding means Rewriting" highlights some good points.
Keep code nice, clear and simple. Don't comment what you're doing when it's obvious (for instance I know what a foreach or if does, I don't normally need an explanation).
Code tricks (such as auto properties) that make simple things take up fewer lines are good too.
Probably the most important point is to keep your syntax consistent. I would also have a look at the design guidelines for the language you are writing in.
The best way to ensure that others can read your code is to make sure that it is clear and concise. Namely,
- Use self documenting names for variables, functions, and classes.
- Comment complex algorithms so that the reader doesn't have to spend to long figuring out what it does.
- Ensure that tabbing and line breaks are constant throughout the code.
Beyond that you start to get in to the areas that might be a bit subjective, most people should agree on these items.
Dear Flubba
What I mean is when I am writing code in any language, how should I code so that it is easily readable by other people who have not written it.
Codeslayer
- Document the code as to why it does what it does.
- Make sure that all variables functions etc. are named consistently and descriptively
- Use white space to group logical portions of code together, so it flows while reading.
- Place the functions/methods etc. in a logical order.
- (this one is my personal preference) Make sure that code can easily be read on the screen without having to scroll horizontally (some people say vertically too, but this doesn't seem to bother me).
This question is subjective, and should be avoided on StackOverflow, as per the FAQ
What kind of questions should I not ask here?
Avoid asking questions that are subjective, argumentative, or require extended discussion. This is a place for questions that can be answered!
The short answer would be:
Avoid excessive commenting:
// add one to the count: i++;
Use good variable and method names:
int x = i + j; int runSum = prevSum += newValue;
Use coding shorthand where available:
if (x == y) { z = a; } else { z = b; } z = (x == y) ? a : b;
Buy & read Code Complete 2. There's loads of stuff in there about writing easy to read / maintain code.
@Rob Cooper - I disagree that this question is too subjective for the site. Code readability is definitely something that is subjective, but it is also something that all developers are affected by and need to be mindful. Plus, there are also some generally accepted guidelines that everyone tends to agree upon so it's not completely subjective (i.e. specific to the individual).
Edit
@Rob Cooper - I think that marcio managed to capture my thoughts better than I did. The question itself is very broad with broad picture guidelines being something that people tend to agree upon, but the fine grained guidelines being subjective. Make more sense? As such, because the broad area of this question is relevant to everyone, I don't think it is in appropriate for the site.
@Rob - Don't really understand what you are saying since the question is subjective. I think perhaps my wording was not good enough, corrected. Sorry for any confusion.
I don't think it's a subjective question, but it's too broad! It's not just about commenting and giving good variables names. It deals with how humans comprehends code. So your system must be implemented in a way that the reader can easily construct a mental model of its design in two way:
Top-down: assuming the user knows the system domain, he tends to make assumptions on how it would be implemented, so he'll scan the system packages and classes looking for entities he can identify. Giving good names to your classes and properly modularizing it would help very much.
Bottom-up: once the user reaches a portion of code he'll start navigation from there, building chunks of knowledge. If your system has low cohesion and lots of implicit dependencies the user will be lost.
Kent Beck adopts three principles: Communication, Simplicity and Flexibility. Of course, sometimes you'll have to trade simplicity for flexibility, and vice-versa.
This could go on and on. The answer to this question fits in a large book. As @rmbarnes suggested, buy and read Code Complete 2. I also suggest Implementation Patterns by Kent Beck - its highly related to your question.
From being a developer with serveral years under the belt, this used to be a real question for me. I couldn't even say how many hours I passed thinking about this and trying different things in my code. The above answers are very nice too. I just want to add a thing or two.
We each have different things that make our reading different than the others. Something that you find easy to read, might really be hard for somebody else to read.
Cleanliness of your code is a very important aspect. Soon as it gets too cramped just forget about it.
Most important: You are you own teacher. No matter what style you follow, you will want to change a thing or two based on your experience. As months pass and you have to go back to your old for fixes or documentation, you will have the "I can't believe I wrote code that reads like that" effect. Take notes of what was bugging you with the code readability and make sure not to write like that again.
Since everyone else said pretty much what I'm thinking when I read this question, I'll just share two books related to this subject that you might be interested in reading. These books use open source code examples to explain how to read and write high quality code. In addition to Code Complete, I think they are valuable resources when you want to write good code in any language.
I am most likely in the minority, but I don't mind whitespace. I LOVE WHITESPACE. Since the compiler takes it out and HD space being so cheap I like to have white space in my code.
For example I like:
int total = 10;
int sum = 0;
for (int i = 0; i < total; i++)
{
sum += i;
}
// Next coding statement is a space below the bracket
return sum;
I do not like:
int total = 10;int sum = 0;
for (int i = 0; i < total; i++)
{
sum += i;
}
return sum;
What I also put in Brackets even though technically they are not needed. The best example is the if statement. I find it greatly helps readability.
if(true)
// some action
if(true)
{
// Some action
}
The best code to me, is one that as simple as possible. With the least comments as possible, and most importantly works.
My rules:
- Give everything a meaningful name, and call it what it is. Avoid using "x" and "y" for variables.
- Don't abbreviate ANYTHING. I don't care how long the variable name is, don't abbreviate, even with comments. Interpretation of abbreviations is subjective. Does Cmp mean computer? Computer? Company? Compliment? Make it a strong rule, no exceptions, and its easy to follow.
- Don't put multiple statements on the same line. Each line performs a single action.
- Avoid Hungarian Notation like the plague. Or is it ntHungarian?
- Use brackets even for single-line (if, for) substructures. Indentation differences are too easy to lose.
You may want to take a look at Clean Code by Robert C. Martin. It offers up a lot of useful practices for ensuring your code is readable.
Additionally, if your code is supported by a number of unit tests that thoroughly test your code, it offers a way for your user to understand the code by looking at what the tests are doing. You will also find that if you follow the Test Driven Development process, and you write tests for each bit of functionality, your functions tend to be small, do one thing only and do it well, and tend to flow more like a story than simply a large complex web of "stuff".
Tests tend to stay up-to-date more than comments. I often ignore comments anymore due to simple fact that they become obsolete very quickly.
A lot of good answers here, I would like to add something from the perspective of an engineer who likes the big picture. I frequently found that getting a high level overview, in terms of class diagram or a package level overview (diagram/comments etc), heck if nothing exists a 10 line header comments in a file to help me a lot. We can use Doxygen/Javadocs to generate them, or spend 10-15 minutes to just jot down something in comments section.
They dont have to be 100% accurate, and I doubt the overall structure of classes/packages will change without a complete rewrite.
I personally found this kind of big picture overview very helpful and am sure there are others who feel the same.