For me, the goal of writing code beyond getting it to work, is that another programmer can easily read and understand it. Quality code has the same characteristics as any good writing. It's concise, well structured, and clear. Often when writing code you have a lot of domain knowledge and context in your head and it can influence you to ambiguously name variables. It's amazing later to look at code you wrote and wonder what you were thinking. Some of the best programmers can keep more in their head and have less need to write self documenting code.
I often think it might make sense to call programmers writers or authors... It might remind them that what they write will be read, not just by the compiler, but by their future selves and others.
Here are some rules of thumb I use:
Variables:
Don't use a variable to mean more than one thing. Use separate variables.
Use constants, not "magic numbers."
Use companyTypeId == CompanyType.OEM instead of companyTypeId == 3.
Don't be afraid to use long variable names. Often my variable names are 2 or 3 words. This is especially true when you have autocomplete.
Use conventions to name variables. Use is or has at the beginning of boolean variables. Capitalize constant variable names.
Pick specific, unambiguous variable names. Leave out the computer science lingo, like master, detail, object, or entity.
Refactor variable names liberally.
Structure
Use functions for complex if statements.
Use
if(obj.isValid())
instead of
if(obj.x > 00 && obj.y > 0 && obj.z > 0...
Think of functions like a paragraph, best kept to less than one page, and it expresses one idea.
If I had more time, I would have written a shorter letter. - Mark Twain
There are only two hard things in computer science: cache invalidation and naming things - Alan Kay
No comments:
Post a Comment