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.

16.5. Debugging 157But if we have the insight to treat times as base 60 numbers and make the investment of writing theconversion functions (time_to_int and int_to_time), we get a program that is shorter, easier toread and debug, and morereliable.Itisalsoeasiertoaddfeatureslater. Forexample,imaginesubtractingtwoTimestofindthedurationbetween them. The naïve approach would be to implement subtraction with borrowing. Using theconversion functions would be easier and more likelytobecorrect.Ironically,sometimesmakingaproblemharder(ormoregeneral)makesiteasier(becausetherearefewer special cases and fewer opportunities for error).16.5 DebuggingATimeobjectiswell-formedifthevaluesofminutesandsecondsarebetween0and60(including0 but not 60) and if hours is positive. hours and minutes should be integral values, but we mightallowsecondstohave afraction part.Requirementslikethesearecalledinvariantsbecausetheyshouldalwaysbetrue. Toputitadifferentway, ifthey are not true, then something has gone wrong.Writingcodetocheckyourinvariantscanhelpyoudetecterrorsandfindtheircauses. Forexample,youmighthaveafunctionlikevalid_timethattakesaTimeobjectandreturnsFalseifitviolatesan invariant:def valid_time(time):if time.hours < 0 or time.minutes < 0 or time.seconds < 0:return Falseif time.minutes >= 60 or time.seconds >= 60:return Falsereturn TrueThen atthe beginning of each function you could check the arguments tomake surethey arevalid:def add_time(t1, t2):if not valid_time(t1) or not valid_time(t2):raise ValueError, 'invalid Time object in add_time'seconds = time_to_int(t1) + time_to_int(t2)return int_to_time(seconds)Or you could use an assert statement, which checks a given invariant and raises an exception if itfails:def add_time(t1, t2):assert valid_time(t1) and valid_time(t2)seconds = time_to_int(t1) + time_to_int(t2)return int_to_time(seconds)assert statements are useful because they distinguish code that deals with normal conditions fromcode that checks forerrors.

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

Saved successfully!

Ooh no, something went wrong!