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 4 years ago.
Improve this question
Should I be writing Doc Comments for all of my java methods?
#Claudiu
When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a javadoc at least stating its obvious purpose.
#Daniel Spiewak
I thoroughly document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.
Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.
#Paul de Vrieze
For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter
/**
* Get the current value of the foo property.
* The foo property controls the initial guess used by the bla algorithm in
* {#link #bla}
* #return The initial guess used by {#link #bla}
*/
int getFoo() {
return foo;
}
And yes, this is more work.
#VonC
When you break a huge complex method (because of high cyclomatic complexity reason) into:
one public method calling
several private methods which represent internal steps of the public one
, it is very useful to javadoc the private methods as well, even though that documentation will not be visible in the javadoc API files.
Still, it allows you to remember more easily the precise nature of the different steps of your complex algorithm.
And remember: limit values or boundary conditions should be part of your javadoc as well.
Plus, javadoc is way better than simple "//comment":
It is recognized by IDE and used to display a pop-up when you move your cursor on top of one of your - javadoc-ed - function. For instance, a constant - that is private static final variable -, should have a javadoc, especially when its value is not trivial. Case in point: regexp (its javadoc should includes the regexp in its non-escaped form, what is purpose is and a literal example matched by the regexp)
It can be parsed by external tools (like xdoclet)
#Domci
For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. [...]
In short, comment logic, not syntax, and do it only once, on a proper place.
#Miguel Ping
In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.
If the method is, obviously self evident, I might skip a javadoc comment.
Comments like
/** Does Foo */
void doFoo();
Really aren't that useful. (Overly simplistic example, but you get the idea)
I thoroughly document every public method in every API class. Classes which have public members but which are not intended for external consumption are prominently marked in the class javadoc. I also document every protected method in every API class, though to a lesser extent. This goes on the idea that any developer who is extending an API class will already have a fair concept of what's going on.
Finally, I will occasionally document private and package private methods for my own benefit. Any method or field that I think needs some explanation in its usage will receive documentation, regardless of its visibility.
All bases covered by others already; one additional note:
If you find yourself doing this:
/**
* This method currently launches the blaardh into the bleeyrg.
*/
void execute() { ... }
Consider changing it into this:
void launchBlaardhIntoBleeyrg() { ... }
This may seem a bit obvious, but in many cases the opportunity is easy to miss in your own code.
Finally keep in mind that the change is not always wanted; for instance the behaviour of the method may be expected to evolve over time (note the word "currently" in the JavaDoc).
For things, like trivial getters and setters, share the comment between then and describe the purpose of the property, not of the getter/setter.
/**
* Get foo
* #return The value of the foo property
*/
int getFoo() {
return foo;
}
Is not useful. Better do something like:
/**
* Get the current value of the foo property.
* The foo property controls the initial guess used by the bla algorithm in
* {#link #bla}
* #return The initial guess used by {#link #bla}
*/
int getFoo() {
return foo;
}
And yes, this is more work.
No, do not comment every method, variable, class, etc..
Here's a quote from "Clean Code: A Handbook of Agile Software Craftsmanship":
It is just plain silly to have a rule that says that every function must have a
javadoc, or every variable must have a comment. Comments like this just clutter
up the code, popagate lies, and lend to general confusion and disorganization.
A comment should exist if, and only if, it adds important information for the intended user of the method, variable, class, etc.. What constitutes "important" is worth consideration and could be a reminder to myself when/if I come back to this method/class/etc., a consequence/side effect of the method, motivation for why the thing even exists (in the case where some code is overcoming a shortcoming/bug of some library or system), important information about the performance or when it is appropriate to call, etc..
What is not a good comment but indicates the code itself should be rewritten/modified is a comment explaining the details of a complex and obscure method or function. Instead, prefer shorter clearer code.
When I write code for myself - NO. In this case, java doccing is a waste of my time.
When I write code that others will use - Yes. Every method that somebody else can use (any public method) should have a java doc at least stating its obvious purpose. For a good test - run the javadoc creation utility on your code (I forget the exact command line now). Browse through the webpage it generates. If you would be satisfied using a library with that level of documentation, you're golden. If not, Write more javadocs in your code.
There is another reason you should use javadocs. In order to comment something, you have to understand it first. When you trying to comment a function, you are actually thinking of what the method/function/class does, and this makes you be more specific and clear in your javadoc, which in turn makes you write more clear and concise code, which is good.
simply put: YES
The time you need to think about whether you should write a doc,
is better invested in writing a doc.
Writing a one-liner is better than spending time for not documenting the method at all in the end.
For me, if somebody will see it or not doesn't matter - it's not likely I'll know what some obscure piece of code I wrote does after a couple of months. There are a few guidelines:
APIs, framework classes, and internal reusable static methods should be commented thoroughly.
Logic in every complicated piece of code should be explained on two places - general logic in javadoc, and logic for each meaningful part of code in it's own comment.
Model properties should be commented if they're not obvious. For example, no point in commenting username and password, but type should at least have a comment which says what are possible values for type.
I don't document getters, setters, or anything done "by the book". If the team has a standard way of creating forms, adapters, controllers, facades... I don't document them, since there's no point if all adapters are the same and have a set of standard methods. Anyone familiar with framework will know what they're for - assuming that the framework philosophy and way of working with it is documented somewhere. In this cases, comments mean additional clutter and have no purpose. There are exceptions to this when class does something non-standard - then short comment is useful. Also, even if I'm creating form in a standard way, I like to divide parts of the form with short comments which divide the code into several parts, for example "billing address starts here".
In short, comment logic, not syntax, and do it only once, on a proper place.
Java doc should not be relied on, as it places a burden on developers making changes to maintain the java doc as well as the code.
Class names and function names should be explicit enough to explain what is going on.
If to explain what a class or method does makes its name too long to deal with, the class or method is not focused enough, and should be refactored into smaller units.
I feel there should at least be comments regarding the parameters accepted and return types in term of what they are.
One can skip the implementation details in case the function names describes it completely, for eg, sendEmail(..);
I make it a point to write javadoc comments whenever it is non-trivial, Writing javadoc comments when using an IDE like eclipse or netbeans isn't that troublesome. Besides, when you write a javadoc comment, you are being forced to think about not just what the method does, but what the method does exactly, and the assumptions you've made.
Another reason is that once you've understood your code and refactored it, the javadoc allows you to forget about what it does since you can always refer to it. I'm not advocating purposely forgetting what your methods do but it's just that I prefer to remember other things which are more important.
You should probably be documenting all of your methods really. Most important are public API methods (especially published API methods). Private methods are sometimes not documented, although I think they should be, just for clarity - same goes with protected methods. Your comments should be informative, and not just reiterate what the code does.
If a method is particularly complex, it is advised that you document it. Some people believe that code should be written clearly so that it doesn't require comments. However, this is not always possible, so comments should be used in these cases.
You can automate the generation of Javadoc comments for getters/setters from Eclipse via the code templates to save on the amount of documentation you have to write. another tip is to use the #{$inheritDoc} to prevent duplication of code comments between interfaces and implementation classes.
Javadoc can be really useful for libraries and reusable components. But let's be more practical. It is more important to have self explaining code than javadoc.
If you imagine a huge legacy project with Javadocs - would you rely on that? I do not think so... Someone has added Javadoc, then the implementation has changed, new feature was added (removed), so the Javadoc got obsolete.
As I mentioned I like to have javadocs for libraries, but for active projects I would prefer
small functions/classes with names which describe what they do
clear unit test cases which give explanation what the
function/classes do
at a previous company, we used to use the jalopy code formatter with eclipse. That would add javadoc to all the methods including private.
It made life difficult to document setters and getters. But what the heck. You have to do it -- you do it. That made me learn some macro functionality with XEmacs :-) You can automate it even further by writing a java parser and commenter like ANTLR creator did several years ago :-)
currently, I document all public methods and anything more than 10 lines.
You can run javadoc against code that does not have javadoc comments and it will produce fairly useable javadocs if you give thoughtful names to your methods and parameters.
I try to at the very least document every public and interface property and method, so that people calling into my code know what things are. I also try to comment as much as possible in line as well for maintenance sake. Even 'personal' projects I do on my own time just for myself, I try to javadoc just because I might shelf it for a year and come back to it later.
Assumed in all the answers so far is that the comments will be good comments. As we all know that is not always the case, sometimes they are even incorrect. If you have to read the code to determine its intent, boundaries, and expected error behavior then the comment is lacking. For example, is the method thread safe, can any arg be null, can it return null, etc. Comments should be part of any code reviews.
This may be even more important for private methods since a maintainer of the code base will have to contend with issues that an API user will not.
Perhaps IDEs should have a feature that allows the use of a documenting form so that the developer can check off various properties that are important and applicable for the current method.
Related
I recently refactored some code which converted a public method that was only being used in conjure with another public method, into one call.
public class service() {
public String getAuthenticatedUserName() {
return SecurityContext.getName();
}
public getIdentityUserIdByUsername(String username) {
return db.getUser(username).getId();
}
}
which was being utilised in a few other classes as service.getIdentityUserIdByUsername(service.getUsername()), which seemed redudant. A new method was created combining the two calls.
public getIdentityUserId() {
return getIdentityUserIdByUsername(getUsername());
}
The getIdentityUserIdByUsername() is still being utilised in other classes without the need for getUsername(). However, the getUserName() method is no longer used in other classes.
My example is much simpler than the implementation, the method has test coverage that is a bit awkward to do (mocking static classes without Powermock and a bit of googling etc). In the future it's likely we will need the getUsername() method, and the method will not change.
It was suggested in code review that the getUsername() method should now be private due to it not being called anywhere else. This would require the explicit tests for the method be removed/commented out which seems like it would be repeated effort to rewrite or ugly to leave commented out code.
Is it best practice to change the method to private or leave it public because it has explicit coverage and you might need it in the future?
Is it best practice to change the method to private or leave it public because it has explicit coverage and you might need it in the future?
IMO, you are asking the wrong question. So called "best practice" doesn't come into it. (Read the references below!)
The real question is which of the alternatives is / are most likely to be best for you. That is really for you to decide. Not us.
The alternatives are:
You could remove the test case for the private method.
You could comment out the test case.
You could fix the test case so that it runs with the private version of the method.
You could leave the method as public.
To make a rational decision, you need to consider the technical and non-technical pros and cons of each alternative ... in the context of your project. But don't be too concerned about making the wrong decision. In the big picture, it is highly unlikely that making the wrong choice will have serious consequences.
Finally, I would advise to avoid dismissing options just because they are "code smell". That phrase has the same issue as "best practice". It causes you to dismiss valid options based on generalizations ... and current opinions (even fashions) on what is good or bad "practice".
Since you want someone else's opinion ("best practice" is just opinion!), mine is that all of the alternatives are valid. But my vote would be to leave the method as public. It is the least amount of work, and an unused method in an API does little harm. And as you say, there is a reasonable expectation that the method will be used in the future.
You don't need to agree with your code reviewer. (But this is not worth making enemies over ...)
References:
No Best Practices by James Bach
There is no such thing as "Best Practices": Context Matters. by Ted Neward.
It can make sense to want to test private methods. The industry standard way to do this, which has quite some advantages, is this:
Ensure that the test code lives in the same package as the code it tries to test. That doesn't mean same directory; for example, have src/main/java/pkg/MyClass.java and src/test/java/pkg/MyClassTest.java.
Make your private methods package private instead. Annotate them with #VisibleForTesting (from guava) if you want some record of this.
Separately from this, the entry space for public methods (public in the sense of: This is part of my API and defines the access points where external code calls my code) is normally some list of entrypoints.. if you have it at all. More often there is no such definition at all. One could say that all public methods in all public types implicitly form the list (i.e. that the keyword public implies that it is for consumption by external code), which then by tautology decrees that any public method has the proper signature. Not a very useful definition. In practice, the keyword public does not have to mean 'this is API accessible'. Various module systems (such as jigsaw or OSGi) have solutions for this, generally by letting you declare certain packages as actually public.
With such tooling, 'treeshaking' your public methods to point out that they need no longer be public makes sense. Without them... you can't really do this. There is such a notion as 'this method is never called in my codebase, but it is made available to external callers; callers that I don't have available here, and the point is that this is released, and there are perhaps projects that haven't even started being written yet which are intended to call this'.
Assuming you do have the tree-shaking concept going, you can still leave them in for that 'okay maybe not today but tomorrow perhaps' angle. If that applies, leave it in. If you can't imagine any use case where external code needs access to it, just delete it. If it really needs to be recovered, hey, there's always the history in version control.
If the method is a public static then you can leave it as is because there is no impact of it being public. It is aside effect free method, it being exposed will never cause any harm.
If it is a object level public method then -
1) Keep it if it is like an API. It has well defined input, output and delivers a well defined functionality and has tests associated with it. It being public doesn't harm anything.
2) Make it private immediately if it has side effects. If it causes others methods to behave differently because it changes the state of the object then it is harmful being public.
At the company I work for there's a document describing good practices that we should adhere to in Java. One of them is to avoid methods that return this, like for example in:
class Properties {
public Properties add(String k, String v) {
//store (k,v) somewhere
return this;
}
}
I would have such a class so that I'm able to write:
properties.add("name", "john").add("role","swd"). ...
I've seen such idiom many times, like in StringBuilder and don't find anything wrong with it.
Their argumentation is :
... can be the source of synchronization problems or failed expectations about the states of target objects.
I can't think of a situation where this could be true, can any of you give me an example?
EDIT The document doesn't specify anything about mutability, so I don't see the diference between chaining the calls and doing:
properties.add("name", "john");
properties.add("role", "swd");
I'll try to get in touch with the originators, but I wanted to do it with my guns loaded, thats' why I posted the question.
SOLVED: I got to talk with one of the authors, his original intention was apparently to avoid releasing objects that are not yet ready, like in a Builder pattern, and explained that if a context switch happens between calls, the object could be in an invalid state. I argued that this had nothing to do with returning this since you could make the same mistake buy calling the methods one by one and had more to do with synchronizing the building process properly. He admitted the document could be more explicit and will revise it soon. Victory is mine/ours!
My guess is that they are against mutable state (and often are rightly so). If you are not designing fluent interfaces returning this but rather return a new immutable instance of the object with the changed state, you can avoid synchronization problems or have no "failed expectations about the states of target objects". This might explain their requirement.
The only serious basis for the practice is avoiding mutable objects; the criticism that it is "confusing" and leads to "failed expectations" is quite weak. One should never use an object without first getting familiar with its semantics, and enforcing constraints on the API just to cater for those who opt out of reading Javadoc is not a good practice at all— especially because, as you note, returning this to achieve a fluent API design is one of the standard approaches in Java, and indeed a very welcome one.
I think sometimes this approach can be really useful, for example in 'builder' pattern.
I can say that in my organization this kind of things is controlled by Sonar rules, and we don't have such a rule.
Another guess is that maybe the project was built on top of existing codebase and this is kind of legacy restriction.
So the only thing I can suggest here is to talk to the people who wrote this doc :)
Hope this helps
I think it's perfectly acceptable to use that pattern in some situations.
For example, as a Swing developer, I use GridBagLayout fairly frequently for its strengths and flexibility, but anyone who's ever used it (with it's partener in crime GridBagConstraints) knows that it can be quite verbose and not very readable.
A common workaround that I've seen online (and one that I use) is to subclass GridBagConstraints (GBConstraints) that has a setter for each different property, and each setter returns this. This allows for the developer to chain the different properties on an as-needed basis.
The resultant code is about 1/4 the size, and far more readable/maintainable, even to the casual developer who might not be familiar with using GridBagConstaints.
I am starting to learn Android programming with Java, mainly from online Android documentation. I also looked through several books but they don't seem to address this issue: a feature of Java syntax which I have come across several times and which is a mystery to me. Here is just one example from about half-way through the Contacts Provider documentation at
http://developer.android.com/guide/topics/providers/contacts-provider.html
I have removed the comments to unclutter the code snippet:
op =
ContentProviderOperation.newInsert(ContactsContract.Data.CONTENT_URI)
.withValueBackReference(ContactsContract.Data.RAW_CONTACT_ID, 0)
.withValue(ContactsContract.Data.MIMETYPE,
ContactsContract.CommonDataKinds.Email.CONTENT_ITEM_TYPE)
.withValue(ContactsContract.CommonDataKinds.Email.ADDRESS, email)
.withValue(ContactsContract.CommonDataKinds.Email.TYPE, emailType);
This is all one statement, I think. What is confusing me is all those "dot operators" that look as though they belong in a Visual Basic "with clause". Where can I find out what all this means?
youre looking at a builder pattern, where the return value of each such with* method is the builder itself (or the object, if its not a builder exactly). theyre handly when you want to chain a lot of setters, or when there are a lot of constructors for the underlying object and you dont want people using it to get confused. or, as fge stated below, when you want the returned object to be immutable (so it cant have setters).
more specifically to your case, the return value of ContentProviderOperation.newInsert() is a ContentProviderOperation.Builder, all of who's methods return itself. usually such a chain of configuration calls will end in a call to build(), which will produce an operation.
This is an instance of so called fluent interfaces (link to wikipedia). There is noting special about it: the value returned from the previous call is being used as the target of the subsequent call.
API like this present a useful alternative to methods with lots of optional parameters, because the resulting code is much easier to read and understand. The code is somewhat more verbose, but in this case it is a good thing, because the parameters passed to constructors get better "tagging". This style is also preferable when you have multiple parameters of the same type (say, strings) next to each other, because it lets the readers avoid parameter counting.
each of those methods returns an ContentProviderOperation.Builder object that has been modified by the method. So you can chain together calls to methods like that and do everything in a more compact way. It's similar to how jQuery works in the javascript world.
It may clear things up a bit to look at the newInsert method on the Android documentation, then look at the documentation for the ContentProviderOperation.Builder class. note that all of the methods on that object also return ContentProviderOperation.Builder objects.
I have a project (related to graph algorithms). It is written by someone else.
The code is horrible:
public fields, no getters/setters
huge methods, all public
some classes have over 20 fields
some classes have over 5 constructors (which are also huge)
some of those constructors just leave many fields null
(so I can't make some fields final, because then every second constructor signals errors)
methods and classes rely on each other in both directions
I have to rewrite this into a clean and understandable API.
Problem is: I myself don't understand anything in this code.
Please give me hints on analyzing and understanding such code.
I was thinking, perhaps, there are tools which perform static code analysis
and give me call graphs and things like this.
Oh dear :-) I envy you and not at the same time..ok let's take one thing at a time. Some of these things you can tackle yourself before you set a code analyzing tool loose at it. This way you will gain a better understanding and be able to proceed much further than with a simple tool
public fields, no getters/setters
make everything private. Your rule should be to limit access as much as possible
huge methods, all public
split and make private where it makes sense to do so
some classes have over 20 fields
ugh..the Builder pattern in Effective Java 2nd Ed is a prime candidate for this.
some classes have over 5 constructors (which are also huge)
Sounds like telescoping constructors, same pattern as above will help
some of those constructors just left many fields null
yep it is telescoping constructors :)
methods and classes rely on each other in both directions
This will be the least fun. Try to remove inheritance unless you're perfectly clear
it is required and use composition instead via interfaces where applicable
Best of luck we are here to help
WOW!
I would recommend: write unittests and then start refactoring
* public fields, no getters/setters
start by making them private and 'feel' the resistance on compiler errors as metric.
* huge methods, all public
understand their semantics, try to introdue interfaces
* some classes have over 20 fields
very common in complex appilcations, nothing to worrie
* some classes have over 5 constructors (which are also huge)
replace them by by buider/creator pattern
* some of those constructors just left many fields null
see above answer
* methods and classes rely on each other in both directions
decide whether to to rewrite everything (honestly I faced cased where only 10% of the code was needed)
Well, the clean-up wizard in eclipse will scrape off a noticable percentage of the sludge.
Then you could point Sonar at it and fix everything it complains about, if you live long enough.
For static analysis and call graphs (no graphics, but graph structures), you can use Dependency Finder.
Use an IDE that knows something about refactoring, like IntelliJ. You won't have situations where you move one method and five other classes complain, because IntelliJ is smart enough to make all the required changes.
Unit tests are a must. Someone refactoring without unit tests is like a high-wire performer without a safety net. Get one before you start the long, hard climb.
The answer may be: patience & coffee.
This is the way I would do it:
Start using the code , e.g. from within a main method, as if it were used by the other classes - same arguments, same invocation orders. Do that inside a debugger, as you see each step that this class makes.
Start writing unit tests for that functionality. Once you have reached a reasonable coverage, you will start to notice that this class probably has too many responsibilities.
while ( responsibilities != 1 ) {
Extract an interface which expresses one responsibility of that class.
Make all callers use that interface instead of the concrete type;
Extract the implementation to a separate class;
Pass the new class to all callers using the new interface.
}
Not saying tools like Sonar, FindBugs etc. that some have already mentiones don't help, but there are no magic tricks. Start from something you do understand, create a unit test for it and once it runs green start refactoring piece by piece. Remember to mock dependencies as you go along.
Sometimes it is easier to rewrite something from scratch. Is this 'horrible code' working as intended or full of bugs? It is documented?
In my current project, deleting my predessor's work nearly in its entirety, and rewriting it from scratch, was the most efficient approach. Granted, this was an extreme case of code obfuscation, utter lack of meaningful comments, and utter incompetence, so your mileage may vary.
Though some legacy code might be barely comprehensible, still it can be refactored and improved to legibility in a stepwise fashion. Have you seen Joshua Kerievsky's Refactoring To Patterns book? -- it's good on this.
This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
Is it possible to write good and understandable code without any comments?
When coding often I hear that if comments are needed then it means that the code is too hard to understand. I agree that code should be readable but often the language itself makes the code hard to follow, because of "plumbing" and strange syntax. The languages I use most often are:
Java
Mootools
Ruby
Erlang
Any tips would be appreciated?
Thanks
Recommended reading: Clean Code by Robert C. Martin.
In brief, you should
use meaningful variable/method/class names,
keep your functions/methods short,
have each class and method do only one thing,
have the code in each method be on the same level of abstraction.
Don't fear of extracting even moderately complex expressions from if statements; which one is clearer to read, this
if (i >= 0 && (v.size() < u || d == e)) ...
or
if (foundNewLocalMaximum()) ...
(Don't try to find any meaning in the first code snippet, I just made it up :-)
Comments in clean code are almost never needed. The only exceptions I can think of is if you are using some obscure language feature (e.g. C++ template metaprogramming) or algorithm, and you give a reference to the source of the method/algorithm and its implementation details in a comment.
The main reason why any other kind of comments is not very useful in the long run is that code changes, and comments tend to not be updated alongside the changes in the corresponding code. So after a while the comment is not simply useless, but it is misleading: it tells you something (implementation notes, reasoning about design choices, bug fixes etc.) which refers to a version of the code which is long gone, and you have no idea whether it is relevant anymore for the current version of the code.
Another reason why I think that "why I chose this solution" is most often not worth documenting in the code, is that the brief version of such a comment would almost always be like either "because I think this is the best way", or a reference to e.g. "The C++ Programming Language, ch. 5.2.1", and the long version would be a three-page essay. I think that an experienced programmer most often sees and understands why the code is written like this without much explanation, and a beginner may not understand even the explanation itself - it's not worth trying to cover everyone.
Last but not least, IMO unit tests are almost always a better way of documentation than code comments: your unit tests do document your understanding, assumptions and reasoning about the code quite efficiently, moreover you are automatically reminded to keep them in sync with the code whenever you break them (well, provided you actually run them with your build...).
I don't think you can normally write code without comments.
Briefly, the code documents how. The comments document why.
I would expect the comments to indicate the conditions why the code has been written like that, limitations imposed by requirements or externalities, the impact that would result from changing the code, and other gotchas. The comments contain information that isn't contained within the code itself.
Comments along the code are supposed to tell you why you initially did something a certain way. It shouldn't mean the code is too hard to understand.
The most important things to follow are:
give your variables, methods, classes... meaningful names
write classes/ modules with a clean responsibility
don't mix up different levels of code (don't do bit shifting and high level logic inside of one method)
I think it is useful to write comments for USERS of your code - what the classes/methods/functions do, when an how to call it etc. In other words document the API.
If you need to comment how a method works for the benefit of maintainers then I think the code is probably too complex. In that case refactor it into simpler functions, as others have said.
I personally feel that having no comments at all is about as bad as having excessive commenting. You just need to find the right balance. About using long descriptive names for things this about sums it up for me: read this Also read Kernighan & Pike on long names.
You need to follow certain rules.
Give the entities (variable, classes, etc) readable and meaningful names.
Use design patterns extensively and name them accordingly, e.g. if it is a Factory name it FooFactory.
Have the code formatted properly, etc.