[Tutor] Tutor Digest, Vol 115, Issue 28

Steven D'Aprano steve at pearwood.info
Wed Jan 15 12:06:32 CET 2014


On Sun, Jan 12, 2014 at 12:37:12AM +0000, Alan Gauld wrote:

> As to your question. The best advice is to read what you type
> carefully.
> And know what you are trying to do before you type it.
> In other words, think about the design of your code don't
> just type randomly. That way you are less likely to
> get random errors.

This is excellent advise for all but the smallest, simplest, and most 
obvious programs. You should *design* the program before you *write* the 
program.

You might even discover that you can avoid writing the program in the 
first place!

Design doesn't need to be complicated. For example, if I'm designing a 
function, sometimes all I need do is think about what I want it to do, 
then write the documentation first. So I write:

def download_from_internet(url):
    """Download text or data from a URL.

    >>> text = download_from_internet("http://example.com")
    >>> print(text)
    "Hello"

    """
    pass


These few lines are a perfectly good design, at least for a first draft. 
By writing it down, I get to see how I expect to use this function, and 
the expected results, which helps me decide:

- Is this a good name for the function?

  Answer: no, because it's not just from the Internet that it can 
  download, it can download from local web servers, or even local
  files on my hard drive using the "file://" protocol.

- Is the function well thought-out? What job does it do?

  Answer: partly. It is useful for downloading data into a variable, but 
  what if I just want to download a file and save to disk? Perhaps that
  should be a separate function?

- Is the function's job well defined?

  Answer: not really. I talk about downloading "text or data", but that 
  requires slightly different handling. With text, for example, I need 
  to consider what encoding the text is (e.g. is it ASCII, or Unicode, 
  or Latin-1?), but with binary data, I mustn't convert anything.


So this helps me design a better function, before I have written a 
single line of code except for the function definition header line.



-- 
Steven


More information about the Tutor mailing list