12.07.2015 Views

Think Python - Denison University

Think Python - Denison University

Think Python - Denison University

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

34 Chapter 4. Case study: interface design4.7 RefactoringWhen I wrote circle, I was able to re-use polygon because a many-sided polygon is a good approximationof a circle. But arc is not as cooperative; we can’t use polygon or circle to draw anarc.One alternative is to start with a copy of polygon and transform it into arc. The result might looklikethis:def arc(t, r, angle):arc_length = 2 * math.pi * r * angle / 360n = int(arc_length / 3) + 1step_length = arc_length / nstep_angle = float(angle) / nfor i in range(n):fd(t, step_length)lt(t, step_angle)Thesecondhalfofthisfunctionlookslikepolygon,butwecan’tre-usepolygonwithoutchangingthe interface. We could generalize polygon to take an angle as a third argument, but then polygonwould no longer bean appropriate name! Instead, let’scall themore general functionpolyline:def polyline(t, n, length, angle):for i in range(n):fd(t, length)lt(t, angle)Now wecan rewritepolygonandarctousepolyline:def polygon(t, n, length):angle = 360.0 / npolyline(t, n, length, angle)def arc(t, r, angle):arc_length = 2 * math.pi * r * angle / 360n = int(arc_length / 3) + 1step_length = arc_length / nstep_angle = float(angle) / npolyline(t, n, step_length, step_angle)Finally, wecan rewritecircletousearc:def circle(t, r):arc(t, r, 360)This process—rearranging a program to improve function interfaces and facilitate code re-use—iscalled refactoring. In this case, we noticed that there was similar code in arc and polygon, so we“factored itout” intopolyline.If we had planned ahead, we might have written polyline first and avoided refactoring, but oftenyou don’t know enough at the beginning of a project to design all the interfaces. Once you startcoding, you understand the problem better. Sometimes refactoring is a sign that you have learnedsomething.

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

Saved successfully!

Ooh no, something went wrong!