Document First

This is some strongly suggested advice from a professional.

When writing a new function, particularly within a class, do two things. First, make your function name as long as needed to express what it does. Don’t go crazy on this, but particularly within a class, be as particular and descriptive as you can with function names. It makes things far easier to debug in the future. Abbreviate as you like and don’t be completely unreasonable about function name length. Strike a reasonable balance.

Second, and most important, particularly if you are writing more than one function at a time (as I often do), declare the function and document it before anything else. Just write the function as empty at first. Make your documentation according to whatever standards you use. Declare the function name, parameters and return value(s), along with their types, as a first action.

For example, if you have four class functions you’re going to need from your controller, go into your class and declare the function headers. Above that, describe in detail what the function will do. And document your parameters and return values and types as completely as feasible. Do this for all the functions you know you’re going to need. You can come back later (much later if necessary) and write the function bodies, knowing from the documentation what the function is supposed to do and how.

I know programmers normally want to get to the “good stuff” of writing the function internals. But preliminary documentation isn’t that hard to write, and it forces some discipline. I’ve written lots of functions with only some vague idea in mind of what they should do, only to have to come back later and rewrite them. Start out with documentation, and it clears your mind and forces you to concentrate on your exact requirements. It also aids you later immensely when you come back and have to figure out what’s going on, as when you’re debugging something.

Also, don’t forget, someone else may have to review or debug your code later. I hate having to do that kind of work and maybe you do too. Having someone who generously documented their work makes your life a whole lot easier when that time comes. And if you’re Open Sourcing your code, this is the barest courtesy to those who will download and fiddle with it later (possibly improving it).

Just from friendly advice from someone who’s made all the mistakes already.