Programmer’s Dozen – Programming Best Practices
Posted on Tuesday, 3rd March 2009 in Development by Simon
Take control of your code with these programming best practices from Kevlin Henney. At JAOO Aarhus 2008 Kevlin used a trash can, vampires, a train wreck, whiskey and much more to make you understand and remember his 13 constructive points (a programmer’s dozen) about programming and code smells.
The 13 points made by Kevlin were:
- 0. Prefer code to comments.
- 1. Follow a consistent form.
- 2. Employ the contract metaphor.
- 3. Express independent ideas independently.
- 4. Encapsulate.
- 5. Parameterize from above.
- 6. Restrict mutability of state.
- 7. Favor symmetry over asymmetry.
- 8. Sharpen fuzzy logic.
- 9. Go with the flow.
- 10. Let code decide.
- 11. Omit needless code.
- 12. Unify duplicate code.
You can see a video of Kevlin’s presentation on the JAOO website.
Although maybe not 100% relevant to ColdFusion, I agree with almost all of his points. I still use a Utils.cfc though, some methods are beyond classification :OD
“Prefer code to comments”, i agree with this. Code is one kind of comments, and also the best comment!
I keep seeing this “code over comments” come up again and again, with various justifications for what amounts to laziness, and, in general, it’s just plain wrong.
Commenting your code is absolutely NOT optional; I simply will not allow uncommented code to be checked-in; is’t sloppy, lazy and shows a general lack of consideration for other coders that will have to work with the code later.
At an ABSOLUTE BARE MINIMUM:
* Every class should have a header describing what it does.
* Every method should have a header describing what it does.
* Every member variable should be described at declaration.
The only time “code over comments” applies is within the actual functional body of a method where the code _should_ be clear enough to explain what is going on. However, code can only tell you WHAT, not WHY. Any time you have a piece of code that is not immediately intuituive it must be commented to explain why you are doing things a certain way.
Ian,
you’re very wrong with this statement: “code can only tell you WHAT, not WHY”.
An aptly named variable, method or class can very well express why it does what it does. Take this piece of code for instance:
public void prepareOrderForShipmentOrder (order) {
order.setStatus(OrderStatus.READY_FOR_TRANSPORT);
notificationManager.sendOrderReadyForShipment(order);
}
Shows exactly what’s going on in terms of the business need. The only comment you could add here would be a redundant repitition of the business process, which is already expressed more clearly in code. If the code said something like order.setStatus(2) and notificationManager.sendNotification11(order), then a comment could clear this up. But in that case the code should be made more clear, not the comment.