With apologies to Strunk and White ...
Elements of Programming Style
I have been thinking about writing my own blogging software for a while now, but since that will take some time to come (and will be built on some bleeding edge technologies) I have decided to write blog of mine for the time being at TypePad.
A few days back I gave a presentation on "Elements Of Programming Style"
Why Bother?
•A program is a sort of publication. It is meant to be read by the programmer, another programmer (perhaps yourself a few days, weeks or years later), and lastly a machine.The machine doesn't care how pretty the program is - if the program compiles, the machine's happy - but people do, andthey should.
--Rob Pike
This is a short list of notes from me on what should be the elements of well written programs
Typography
•Consistent Indentation
•Consistent use of braces
Comment the Code
•Prologue
•Epilogue
•Every Logical Block
Functions And Variables
•Names conveys Semantics, not data types
•Names should not be too short, or too long
•Initialize ALL variables to default values
Constants
•Never hardcode constants in the code
•Separate them out in a file or class
Single Return Statement
•Leads to more optimized code
•Avoids subtle bugs
•Easier to maintain code over time
Error Handling
•Use Meaningful Exceptions
•Stick with one type of error handling
Resource Management
•Use garbage collectible (GC) resources
•Finally block to dispose non-GC resources
Refactoring
•Continuously refactor your code
•Small is beautiful … i.e. length of function
Very true to every single word.
But the problems is very few care.
Shhhh! A little secret. Even I ignore them sometimes.
Posted by: Mir Nazim | September 26, 2005 at 11:25 AM
I do believe that very few people care. And that is precisely my (and Rob's) point. I feel that more people should care.
When I started reading the code that Dave Cutler wrote for NT in mid 90s I felt as if I had chanced upon a piece of art. It was so beautifully written and documented that I did not feel like adding a single line of code to it till I had carefully imitated his style.
Posted by: Tarun Anand | September 26, 2005 at 06:29 PM
Such posts can be really useful… not only for working professionals… but for beginners like me…. It would be nice if you document more things about the art of coding, upcoming technologies etc… it would be a great learning experience… and yes I too agree with the statement that code should be well documented so that other programmers can find it easy to understand…. Looking forward to more posts from you sir……
Posted by: Sid... | September 26, 2005 at 10:39 PM