Developing good coding habits
Engineering and IT Insight: Good coding habits reduce errors, save time, and can help you become a better control system programmer. These simple habits may seem to add extra work, but they actually reduce the overall time to code and debug control programs.
Last month's column focused on the habit of tracking your errors to improve your personal programming productivity. Tracking errors, both large and small, allows you to focus on habits and patterns to reduce or eliminate whole classes of errors. An error that is avoided can be a tenth of the cost and time of an error discovered during testing. Reducing errors is an important step in becoming a better control programmer. There are also good coding habits that should be followed to reduce errors and become a better control system programmer. While these are simple habits and may seem to be adding extra work to an already complex task, they actually reduce the overall time to code and debug control programs.
5 simple programming habits
The five simple programming habits are:
- Write your logic in comments first
- Comment the reasons for code changes
- Use an easy-to-read style
- Trust no code
- Read your own code
Importance of comments
A good habit to have is to write your logic in comments inside each class, module, and function before you start coding. Assuming you have a good design and a well laid out architecture, the initial step is to start defining the header sections, interface definitions, and empty body sections. Write the logic, in comments, inside the empty body sections. These become the comments in the code. Many new programmers don't understand the importance of commenting code, claiming that the code should be self-documenting and obvious to the reader.
Experienced programmers know that comments are there to describe what the code is intended to do and not meant to contain the details of how something is being done, such as stepping through all elements of an array. Comments are provided so that the reader does not have to guess what is happening. Uncommented code is one of the worst bad habits a programmer can have, and starting with the comments is one of the best habits.
Comments for reference
When changing a module, include the change and the reason for the change, not just which element was changed. The best comments contain references to associated error reports or change requests. Commenting why the change was made is critical because a statistically significant number of errors are introduced when code is changed. Usually this happens because of unknown or unsuspected side effects of the code change. When someone has to go back and fix the fix, it is important for them to know enough to not undo the original fix.
Style in programming counts, so use "reader-friendly coding styles." It is important to remember the reader when writing code because code will be read many more times than it is written. During reviews, testing, and debugging it is common for the same code sections to be read five or more times. Indentation and line breaks should be consistent and allow the reader to quickly understand the program flow and decision points. Use indentation to illustrate the decision points, if-then-else, case statements, and loops.
Variable names, function names, class names, and object instance names should be obvious and related to their use. Use easy-to-understand names like interfaceCodeForErrors, instead of hard-to-understand names or abbreviations, such as ICFE. Follow a consistent style for naming variables, methods, and classes. A common style is to use "Camel Case," where methods and classes start with capital letters, variables start with lowercase letters, identifiers are made up of multiple words, and each intermediate word starts with an uppercase letter. For example, interfaceCodeForErrors for a variable, GenerateInterfaceCode for a method, and ErrorCode for a class. Another common style is to include the type of the variable or return type of a method in the name, such as interfaceCodeForErrorString or strInterfaceCodeForError.
Trust no code, even yours
One very helpful habit is to be a bit paranoid when programming, and assume that every method or function that is used can contain a bug or return an error. The simple method is to trust no code, including your own. If possible, check for error returns and check that the expected result is "reasonable." This may be no more complicated than checking that a string length is greater than zero, or that a count of elements is less than the maximum expected size. If you do detect an error, attempt to fail gracefully and log debug information so you can track down the error. Failing gracefully means that you present error messages, if possible, and operate in a degraded mode with some features disabled.
One of the hardest errors to debug happens when a function returns an error, but the result of the error does not show up until much later in processing. People often spend days trying to debug these problems because they are hard to reproduce and the symptoms are not related to the cause.
Write, switch, proof
Read your own code. After writing and compiling a section of code, put it aside, work on something else, and then come back and read it, from top to bottom. If you can't read it and understand it, then no one else will. In addition, by putting mental distance between writing code and reading the same code, you are less likely to fall into the trap of "seeing what you expect to see." Reading and reviewing is hard work, which is why authors have editors, and it is too easy to miss small mistakes because you know what the code is supposed to do.
Reading your own code before checking it in is probably the most important final step in programming. You can check that the code is readable, that the comments actually reflect what is being done, that the code follows a good consistent style, that variables and methods have easy-to-read names, and that you are not skipping error checking on method calls.
These good coding habits will help you become a better programmer by preventing errors, reducing the time to debug and maintain your code, and improving the readability and understandability of your code. You will be happier with the results, and your fellow team members will be happy when they have to review and change your code.
- Dennis Brandl is president of BR&L Consulting in Cary, N.C., www.brlconsulting.com. His firm focuses on manufacturing IT. Edited by Mark T. Hoske, content manager, Control Engineering, firstname.lastname@example.org.
This posted version contains more information than the print / digital edition issue of Control Engineering.
At www.controleng.com, search Brandl for more on related topics.
See other articles for 2014 at www.controleng.com/archives.
See other Manufacturing IT articles.
- See related article below on how to improve your control programming.
- Events & Awards
- Magazine Archives
- Digital Reports
- Global SI Database
- Oil & Gas Engineering
- Survey Prize Winners