Sunday, June 27, 2010

Paragraphs and Functions

The list of software instructions you already know, it is breaking them up into manageable pieces that is the problem. What is the best way to accomplish this?

Chopping up code into bite-sized, tasty morsels remains one of the most difficult tasks in programming. Too small, and the intent is dispersed to widely, hidden in the nooks and crannies of the system. Too large, and the bulk is intimidating, difficult to understand or verify.

A useful trick is to see the base unit of code -- a function, procedure or method -- as being equivalent to the usage of paragraphs in writing.

Writing is broken up into paragraphs to make it easier to read. Each paragraph contains the sentences that relate together. Sentences that share some common idea. Short paragraphs are OK, but too many are distracting. Long paragraphs are less desirable, the reader loses focus. A good writer balances their ideas, using the paragraphs as transitioning points to move from one idea to the next. To keep the work flowing.

In that regard, writing does share some commoniality with the programmer's desire to produce 'readable' work. That is, the point of breaking things up into smaller functions is nearly identical to the point of using paragraphs. They both clump together the related ideas.

One notable difference is that writing remains linear, while functions are also hierarchical. That's actually a good thing because it gives the programmer more flexibility when grouping their code. Some sets of instructions are obvious subsets of a larger overall plan. A hierarchy can maintain that relationship.

Getting the pieces right makes the code more readable. It makes it easy for other programmers to follow along and enhance the code later. Getting it right also makes it easier to reuse the code in many other places. Leveraging existing work is the most effective way to avoid a time-crunch.

A readable program is a platform for further work, while a non-readable one is generally tossed and re-written from scratch. Getting the code to work is nice, but having it last as the working solution is far superior. Why build things over and over again? If you do it right the first time, it can be built upon. It can provide a solid base for future effort.