Last week I was updating a module and I was really having a rough time following the logic. I was troubled and stopped for a moment wondering why I'm having difficulty understanding code I myself had written just days before. Then I had an epiphany.
I loathed breaking down functions (or procedures if you will) in the past. I wanted everything to be in one place as much as possible, believing that avoiding those extra calls will make some huge difference in execution performance.
I, too, have tried many styles and methodologies over the years of programming and took some ideas that generally worked out for me. However, there are three particularly interesting ideas I've read before but never gave much thought:
- In Perl, you have lots of shortcuts that allows you to write programs that don't take up more than a screenful of lines
- If you're moving your eyes too much when reading a line of code, you would do well to break that and rewrite than line
- A person's eyes look up when that person is engaged logically, and you can also tell whether he/she is mental constructing or recalling depending on which side the eyes lean
So there I was moving my eyes all over the screen left and right, scrolling back and forward, looking up then back to the screen. Aside from the activity being stressful to the eye muscles, it was also stressing my thought processes. No wonder I was having difficulty 'visualizing the process', or going with the flow as one would say.
I then proceeded to re-factoring the module with the following thoughts:
- If a line is lengthy or nearing the edge of the screen, break it up
- If a function doesn't fit on your screen, break it up. You can tolerate up to three levels of nesting, more than that you usually need to rethink your approach
- When you already have a handful of functions (and class variables) for support purposes, like say for formatting or conversion that aren't needed much to understand what your class strives to do, move them to a base class
When I was done, I had a module that I can read like plain English. I no longer have to scroll back and forth to figure what's being done. Couple with string search, I can quickly locate where a particular problem is. Picking out a bug is easier than before because I don't have too much to look at a time.
Logically, I no longer have to look up a lot.