Saturday, December 3, 2016

Rule of Thumb for Coding: Embrace Your Fallibility!

My esteemed colleague, Jorge Aguero, just showed me this fabulous article, written by a political scientist, providing hints on how not to make mistakes when coding.

The grand insight: The answer is not "just be more careful." The answer is to program in such a way that you find mistakes very quickly.

I urge you to read the entire article at least once every six months, but I'll summarize my favorite pieces of advice here. Again, the most important thing to keep in mind: "humans are effectively incapable of writign error-free code, and that if we wish to improve the quality of the code we write, we must start learning and teaching coding skills that maximize the probability our mistakes will be found and corrected."

How? 
1. Add tests to your code. Run the tests every time you run the code. Examples: If you have state-level data, then you know you can only have 50 observations. If your variable is a percentage, then you know you can never have values above 100 or below 0. Use the assert command in Stata to make sure these things are true. Yeah, this is definitely my favorite tip of the article. Better researchers are probably really good at coming up with these types of tests and use them often. 
2. Copy-paste is the enemy. Never ever copy-paste. Use outreg2 to get tables into excel. Use local (or global?) macros if you are going to do the same thing to several variables. 
3. Comment! Comment! Comment! Things that are obvious when you write the code will not at all be obvious when you get back to revisions six months (or six years) later. 
4. Use informative variable names. You'll get better at this with practice. 

My own addition (sort of): 
6. Copy-edit your code. Make it look nice. Add spacing and use indents. Delete unnecessary code. This will make it easier to read through often. The more you look at it, the more your coauthors look at it, the more likely that you will find mistakes that were not caught by your tests. 

Any other tips? Comment below. 




No comments:

Post a Comment