Archive - Originally posted on "The Horse's Mouth" - 2009-06-11 18:22:18 - Graham Ellis
Q: Where do I start when writing a program?
A: Start off by thinking about what you want to achieve, and what inputs you have available to you. In other words, look at what the customer provided and what the customer wants to get (yes, you may be your own customer!). If it's too much to think through in one step, split it into a series of stories, and write each stage in turn, frequently refactoring as you go.
As well as the inputs and outputs, think about the major structures you'll use internally within your program - your collection variables (arrays, lists, hashes, dictionaries, tuples ... whatever is available in the language of your choice), and think what is likely to be common code which will allow you to (re)use you own code later, or to call in someone else's stuff from day 1.
When you've given this some thought and you're moving to a coding stage, write your comments first - they will in essence form a textual flowchart, help you identify pitfalls early, and avoid you coding up too many blind alleys.
On today's Perl Course, I went through these principles, in order to start answering the question "what operating system(s) do people who use my website run?" .... you can see my initial (all comments!) design here. I then went on to add some code - a first test or - 'spike' solution - see here. The results of running that program on a recent log file from our own site:
Dorothy-2:perl grahamellis$ perl whatos
There are 80520 good records and 34 mucked up ones
unknown ... 49716
Googlebot ... 9574
Windows NT 5\.1 ... 21230
Dorothy-2:perl grahamellis$
which is very short .. but an excellent demonstration of principle.
Although I am talking about Perl in this note, you'll find that what I've suggested is equally suitable for use in Python, PHP, Ruby, Lua ... indeed, in all the other languages we teach. If what I've written is of interest to you, have a look at our "learning to program in ...." courses, where an extra day on the front of the main course helps newcomers to programming. But if it's stuff you're happy with, start on our ".... programming" courses which assume prior knowledge of things like this