Recently I ran across these few lines of code that break many of the following tips I’m going to give you. I’ve seen some code that the Developer who wrote it clearly didn’t understand. It contained no error handling cases and only worked in the success case (1 out of 50 paths). In every other path it would fail!
For example, in one situation, 10 variables are created (none are initialized, another problem) with names of x,x1,x2,x3,x4,x5… and so on. The Developer then proceeded to use these 10 variables in the next 500 lines of code. When I asked the Developer what these variables actually were, he couldn’t even explain it to me!
With the above in mind, I thought of a few tips that would really help a few people write much better code. I realize that a good amount of the following tips are CS101 type comments, but without even following these, you have no hope of writing any sort of manageable code.
How to combat it:
It’s far better to ask someone for help if you don’t understand how something should be done than to write some spaghetti code that may solve the problem for the Success now, but may become a minefield for every other case later on.
Following some basic steps when writing code
- Null checks – Don’t create mind field code that crashes on specific cases that you haven’t checked for
- Don’t write 4 lines of code when 2 will do. If a block of code requires more lines of comments to explain what it does than the code itself, you need to rethink how it’s being done
- Comment frequently
- Having the problem of too many comments is always a better situation to be in than having no comments at all. I would rather see a story describing some method/function than no comments at all.
- Name variables that make sense
- Names like X and B are simply no help, and they show that you were simply too lazy to write a more descriptive name of the variable. This will quickly come back to haunt you when the code gets even slightly more complicated. Take the time to make informative variable names! You will thank yourself later.
- Avoid Copy/Paste of Code! If you need to use a block of code over, it’s time to refactor that code into a function/method
- Anytime you can simplify code that has been written, do so!
- Reuse any code that is written as much as possible
- Always try to improve the code you have written.
All right. I’ll get off my soap box now. I hope these tips help you become a better programmer. Feel free to let me know if you have some tips of your own.