12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

4.8. A development plan 354.8 AdevelopmentplanA development plan is a process for writing programs. The process we used in this case study is“encapsulation and generalization.” The steps of thisprocess are:1. Start by writingasmallprogram withno function definitions.2. Once you get the program working, encapsulate it inafunction and give itaname.3. Generalize the function by adding appropriate parameters.4. Repeat steps 1–3 until you have a set of working functions. Copy and paste working code toavoid retyping (and re-debugging).5. Look for opportunities to improve the program by refactoring. For example, if you havesimilarcode inseveral places, consider factoring itintoan appropriately general function.This process has some drawbacks—we will see alternatives later—but it can be useful if you don’tknowaheadoftimehowtodividetheprogramintofunctions. Thisapproachletsyoudesignasyougo along.4.9 docstringA docstring is a string at the beginning of a function that explains the interface (“doc” is short for“documentation”). Here isanexample:def polyline(t, n, length, angle):"""Draw n line segments with the given length andangle (in degrees) between them. t is a turtle."""for i in range(n):fd(t, length)lt(t, angle)This docstring is a triple-quoted string, also known as a multiline string because the triple quotesallow thestringtospan more than one line.It is terse, but it contains the essential information someone would need to use this function. Itexplains concisely what the function does (without getting into the details of how it does it). Itexplainswhateffecteachparameterhasonthebehaviorofthefunctionandwhattypeeachparametershould be (ifit isnot obvious).Writing this kind of documentation is an important part of interface design. A well-designed interfaceshouldbesimpletoexplain;ifyouarehavingahardtimeexplainingoneofyourfunctions,thatmight be asignthat the interface could be improved.4.10 DebuggingAn interface is like a contract between a function and a caller. The caller agrees to provide certainparameters and the function agrees todocertain work.

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!