Python Programming: An Introduction to Computer Science

(Nora) #1
10.3. DEFININGNEWCLASSES 159

10.2.3 ModularizingtheProgram


Youmayhave noticedduringthedesigndiscussionthatI employedstepwiserefinement(top-downdesign)
todeveloptheprogram,butI didnotdividetheprogramintoseparatefunctions.We aregoingtomodularize
theprogramintwo differentways.First,we’ll usefunctions(ala top-downdesign).
Whilethefinalprogramis nottoolong,it is fairlycomplex foritslength.Onecauseofthecomplexityis
thatit usestenvariables,andthatis a lotforthereadertokeeptrackof.Let’s trydividingtheprograminto
functionalpiecestoseeif thathelps.Here’s a versionofthemainalgorithmusinghelperfunctions:


def main():
angle, vel, h0, time= getInputs()
xpos, ypos = 0, h0
xvel, yvel = getXYComponents(velocity, angle)
while ypos >= 0:
xpos, ypos,yvel = updateCannonBall(time, xpos, ypos,xvel, yvel)
print "\nDistancetraveled: %0.1f meters." % (xpos)


It shouldbeobviouswhateachofthesefunctionsdoesbasedontheirnamesandtheoriginalprogramcode.
Youmighttake a coupleofminutestocodeupthethreehelperfunctions.
Thissecondversionofthemainalgorithmis certainlymoreconcise.Thenumberofvariableshasbeen
reducedto eight,sincethetaandyvel1have beeneliminatedfromthemainalgorithm.Doyouseewhere
they went?Thevalueofthetais onlyneededlocallyinsideofgetXYComponents. Similarly,yvel1is
now localtoupdateCannonBall. Beingableto hidesomeoftheintermediatevariablesis a majorbenefit
oftheseparationofconcernsprovidedbytop-downdesign.
Eventhisversionseemsoverlycomplicated.Lookespeciallyattheloop.Keepingtrackofthestateof
thecannonballrequiresfourpiecesofinformation,threeofwhichmustchangefrommomenttomoment.
Allfourvariablesalongwiththevalueoftimeareneededtocomputethenewvaluesofthethreethat
change.Thatresultsinanuglyfunctioncallhavingfive parametersandthreereturnvalues.Anexplosionof
parametersis oftenanindicationthattheremightbea betterwaytoorganizea program.Let’s tryanother
approach.
Theoriginalproblemspecificationitselfsuggestsa betterwaytolookatthevariablesinourprogram.
Thereis a singlereal-worldcannonballobject,butdescribingit inthecurrentprogramrequiresfourpieces
ofinformation:xpos,ypos,xvelandyvel. SupposewehadaProjectileclassthat“understood”
thephysicsofobjectslike cannonballs.Usingsucha class,wecouldexpressthemainalgorithminterms
ofcreatingandupdatinga suitableobjectstoredina singlevariable.Usingthisobject-basedapproach,we
mightwritemainlike this.


def main():
angle, vel, h0, time= getInputs()
cball = Projectile(angle,vel, h0)
while cball.getY()>= 0:
cball.update(time)
print "\nDistancetraveled: %0.1f meters." % (cball.getX())


Obviously, thisisa muchsimplerandmoredirectexpressionofthealgorithm. Theinitialvaluesof
angle,velandh0areusedasparameterstocreateaProjectilecalledcball. Eachtimethrough
theloop,cballisaskedtoupdateitsstatetoaccountfortime. We cangetthepositionofcballat
any momentbyusingitsgetXandgetYmethods. To make thiswork,wejustneedtodefinea suitable
Projectileclassthatimplementsthemethodsupdate,getX, andgetY.


10.3 DefiningNew Classes.


Beforedesigninga Projectileclass,let’s take anevensimplerexampletoexaminethebasicideas.

Free download pdf