Thursday, July 2, 2009

Tips for Making Code Last

This was asked in StackOverflow:

http://stackoverflow.com/questions/1073473/tips-for-making-code-last/1074596#1074596

I have found the following tips useful:

1.Use meaningful variable/member/class/function names, even if your fingers hurt from the typing.

2.Comment each class and function, procedure (unless it is boilerplate e.g. set/get methods) accurately, concisely. If this is not possible or easy then probably your function/sub is too complex.

3.Keep functions/procedures small - 5-10 lines. This helps keep them easy to validate, test, debug, document, and use.

4.When you review your code (usually during the course of bug fixes or further development) and something strikes you as off, document the issue or fix it. Often later you will find a bug and it will be related, or you will use the code in a way that violates some of these assumptions made and the documentation will help you.

5.Keep a working log of the changes you are making throughout the day. When you save to the repository, you can cut and paste the part of the log from the last save to the current place, so your code repository changes are well-documented. Save the logs separately (repository, email, blog).

6.Factor your code into independent, reusable components. There is a fine line here between over-engineering, KISS, and generalization, so you have to weigh the pro's and con's. The advantage of making reusable components is that you tend to design the component better to make few assumptions, to have clean interfaces, to have few dependencies -- all of which makes for better code. Also, the reusable components get used in more places, so the code tends to be better tested.

7.Throw exceptions or use assertions wherever your code might fail depending on how it is called, i.e. parameters passed or dependency on any external factors to the function/procedure. "Never happens" only exists in theory -- the exceptions make narrowing down bugs much easier.

8.Keep a running todo list/bug list for things that need to be done or enhancements as part of your log. Chances are this list will never be completed, because as fast as you can complete items on the list new ones will be added. At some point, the list will consist of low-priority, or deferrable items, and you move to production or to a new release. How many years has MS word been worked on and is it complete now?

No comments:

Post a Comment