Lecture Eight (Notes) - Documentation
Lecture Eight (Notes) - Documentation
Lecture Eight (Notes) - Documentation
What these lecture notes co er! How to write good comments How to document code (a suggestion)
Lecture Eight (Notes) Documentation ...................................................................................................1 What these lecture notes cover:.............................................................................................................1 Documenting code.................................................................................................................................1 Commenting code well..........................................................................................................................1 !adl" commented #iece o$ code.........................................................................................................1 well commented #iece o$ code...........................................................................................................% E&ternal Documentation........................................................................................................................' (ser Documentation..............................................................................................................................) Docu"ent#n$ co%e n im#ortant #art o$ "our #ro*ect write u# will !e the #rogram documentation. +here are three se#arate #arts to code documentation: 1) +he comments "ou #ut in "our code. (internal documentation) ,) What "ou write a!out "our code to e&#lain how it wor-s to a #rogrammer who will !e wor-ing on e&#anding "our code. (e&ternal documentation) .) What "ou write a!out "our code to e&#lain how it wor-s to a user who will !e using "our #rogram (user documentation) Each o$ these three t"#es o$ documentation re/uires its own a##roach. Co""ent#n$ co%e &ell Comments are eas" to #ut in code and almost ever" #rogrammer realises that the" should #ut comments in code !ut almost no #rogrammers do it well. 0ou should consider the $ollowing with each comment: a) Will it hel# the reader understand the code or !) m 1 *ust adding a comment here !ecause 1 thin- 1 should add a comment as- "oursel$ 21s this something that the reader could have triviall" wor-ed out $or themselves2 Comments are good !ut sometimes less is more. Consider: i= i+1; /* Adds one to i */ 1$ something is #articularl" tric-" then re$er to a re$erence rather than e&#lain it in comment: void very_complicated_sort (int array[]) /* Sorts the array into increasing n meric order ! see "n th #$ery complicated programming% p1&'(1&& )or details */ +he ne&t #age shows a !ad set o$ comments the code #rints #art o$ the 3eigen!aum diagram $rom coursewor-. A 'a%l( co""ente% )#ece o* co%e *incl de +stdio,h-
*incl de +stdli.,h*incl de +math,h/* /ichard0s chaos program */ /* 1rototypes */ void 2rite_3d_array (char []4 int4 )loat []4 )loat []); /* 5n ms and *de)ines */ en m 6 We could tell 7A819:;<S= &''''4 this an"wa" /5S9=><:9;= 1''' without the ?; comment *de)ine 9><@:=5 Achaos3,o tA int main() /* main ro tine */ 6 /* Be)ine some varia.les */ )loat Cpts[7A819:;<S]4 ypts[7A819:;<S]; +his seems int tot_points; sill" !ut 14ve )loat C4lam.da; seen this )loat D[/5S9=><:9;]; comment so int Dval; man" times int i4E; tot_points= '; )or (i= '; i + /5S9=><:9;; i++) 6 /* <ricFy .it */ lam.da= ',G&+ (',3&*()loat)i / (/5S9=><:9;(1)); )or (E= '; E + /5S9=><:9;; E++) 6 D[E]= '; ? C= ',HI&J; )or (E= '; E + &'; E++) 6 /* Bo this )or every E*/ ? )or (E= &'; E + 1&'; E++) 6 /* =ong ram.ling comment 2hich doesn0t )inish C= I*lam.da*C*(1,' ( C); Dval= (int) (C* (/5S9=><:9;(1)); i) (Dval -= /5S9=><:9;) Dval= /5S9=><:9;(1; Comments "ou i) (D[Dval] == ') 6 must scroll to read D[Dval]= 1; Cpts[tot_points]= lam.da; are ver" ver" ypts[tot_points]= C; anno"ing tot_points++; i) (tot_points == 7A819:;<S) 6 print) (A<oo many points to plotKnA); ret rn (1; ? ? ? ? 2rite_3d_array (9><@:=54 tot_points4 Cpts4 ypts); ret rn '; /* 5nd o) main */
void 2rite_3d_array (char )ilename []4 int no_points4 )loat CaCis[]4 )loat yaCis[]) /* Lrite a 3 dimensional array */ 6 @:=5 *)ptr; /*@ile pointer */ int i; /* >sed in )or loop */ )ptr= )open ()ilename4 A2A); /* 9pen the )ile */ i) ()ptr == ;>==) 6
)or (i= '; i + no_points; i++) 6 /* =oop over i */ )print) ()ptr4 AM) M)KnA4 CaCis[i]4 yaCis[i]); ? )close()ptr); /* Nlose it */ C= I*lam.da*C*(1,' ( C);
+he author o$ this #rogram has managed to #ut in a lot o$ comments without actuall" an" o$ them !eing hel#$ul (e&ce#t5 #erha#s5 to a non C #rogrammer and a non6#rogrammer isn4t going to !e $i&ing "our code 1 would ho#e). What should we comment7 s 1 guideline5 1 would alwa"s comment:
a) 8aria!les unless the" are o!vious $or e&am#le no need to sa" that i5* or - are varia!les used in loo#s the" almost alwa"s are. No need to comment that @:=5 *)ptr is a $ile #ointer. 9n the other hand int total might total u# an"thing and could #erha#s use some clari$"ing. !) 1 would alwa"s tr" to #ut in a comment at the !eginning o$ a $unction to sa" what that $unction does5 what it returns and when it !rea-s. int )actorial (int n) /* /et rn the )actorial o) n, n m.er */ 6 , , , ? <his 2ill .reaF i) passed a negative
int 2rite_3d_array (char )ilename[]4 int no_points4 )loat CaCis[]4 )loat yaCis[]) /* Lrites a 3d array to the )ile speci)ied .y )ilename in a )ormat s ita.le )or 7aple plotting, CaCis and yaCis are the t2o dimensions to .e plotted 2ith no_points in each, <he ) nction ret rns ' i) it is s ccess) l or !1 i) there is a pro.lem 2riting to the )ile */ 0our comment need not !e /uite so ver!ose as this !ut should give an idea what each $unction does5 what arguments it ta-es and what it returns. c) 1 alwa"s tr" to #ut a smaller comment !" the #rotot"#e o$ each $unction which gives some descri#tion. +he reason is that when "ou write a large #rogram5 the #rotot"#es are all grou#ed together in a header $ile and it is easier to gain an understanding o$ the #rogram !" loo-ing at them. d) 1n multi#le $ile #rogramming 1 would #ut a comment in each $ile to sa" what #ur#ose it serves in the #rogram: )ileio,cO /* <his contains .asic )ile inp t/o tp t ) nctions )or reading and 2riting records in the payroll program */ e) :tructures are almost alwa"s worth a comment since these are li-el" to !e ver" im#ortant in "our #rogram. 9ther than these situations5 "ou must !e guided !" common sense. ;utting in too man" comments ma-es "our #rogram unreada!le and mess". ;utting in too $ew will leave it cr"#tic. good guide is to #ut a comment on an"thing which "ou would $ind con$using even i$ given a minute or two to loo- at it. 1$ what "ou are doing is unusual then it is as well to comment it as such. 3or e&am#le5 it is eas" to
!e con$used !" code that has a 1/(r*r*r) i$ the code is su##osed to deal with gravitation (normall" a 1<r,) so it is as well to comment that something unusual is going on. Even i$ "ou -now the code is correct5 a later user might !e con$used !" it (or even worse =correct> it to 1<r,). $inal rule is that i$ something is e&tremel" di$$icult to comment and "ou $ind "oursel$ s#ending $our or $ive lines going on a!out it then it4s almost certainl" worth #utting a re$erence to e&ternal documentation instead. 0ou should note that in the ?odel answers to coursewor- 1 have tried to comment a##ro#riatel" !ut erred on the side o$ ma-ing too man" comments !ecause the coursewor- model answers were written to !e understood !" learning #rogrammers. @enerall" "ou should write comments with the assum#tion that the readers will !e e&#erienced #rogrammers. Here is how "ou should comment the code $rom the a!ove e&am#le (the code !elow is5 i$ an"thing5 over commented $or most #rogrammersA tastes):
A &ell co""ente% )#ece o* co%e *incl de +stdio,h*incl de +stdli.,h*incl de +math,h/* @eigen.a m,c <his program plots a @eigen.a m diagram )rom the =ogistic map ! see4 )or eCampleO 1eitgen4 P rgens and Sa peO Nhaos and @ractals <he plotting is simpli)ied .y splitting the y(aCis into A.insA and recording 2hether or not a point )alls into each o) these A.insA and then plotting a point accordingly*/ void 2rite_3d_array (char []4 int4 )loat []4 )loat []); /* Lrite the contents o) t2o arrays to a )ile in a )ormat 2hich can .e plotted .y maple */ en m 6 7A819:;<S= &''''4 /5S9=><:9;= 1''' ?; /* 7aC, n m.er o) pts to .e plotted*/ /* ; m.er o) A.insA to split ['41] into */
*de)ine 9><@:=5 Achaos3,o tA int main() 6 /* Nalc late the )eigen.a m diagram .y looping aro nd each val e o) lam.da and calc late 2hich o) the A.insA contain points to plot */ )loat Cpts[7A819:;<S]4 ypts[7A819:;<S]; int tot_points; /* <he n m.er o) points act ally plotted*/ )loat C4lam.da; /* varia.les in the logistic eQ ation */ )loat D[/5S9=><:9;]; /* Rolds a temporary AsliceA o) the diagram )or a val e o) lam.da */ int Dval; /* Rolds the A.inA 2e are plotting in */ int i4E; tot_points= '; )or (i= '; i + /5S9=><:9;; i++) 6 /* lam.da is in the range [',G141,'] */ lam.da= ',G&+ (',3&*()loat)i / (/5S9=><:9;(1)); /* Nlear o t the D array ! in e))ect maFe s re all the A.insA .egin empty */ )or (E= '; E + /5S9=><:9;; E++) 6 D[E]= '; ? C= ',HI&J; /* C_' ! a randomly chosen start point */ /* SFip over the initial &' points .y iterating the map &' times */ )or (E= '; E + &'; E++) 6 C= I*lam.da*C*(1,' ( C); ? /* <he neCt 1'' points may .e plotted so iterate the map a ) rther 1'' times*/ )or (E= &'; E + 1&'; E++) 6 C= I*lam.da*C*(1,' ( C); /* Nalc late 2hich A.inA 2e are in */ Dval= (int) (C* (/5S9=><:9;(1)); i) (Dval -= /5S9=><:9;) /* NhecF it is in range */ Dval= /5S9=><:9;(1; /* i) this A.inA has not .een visited .e)ore then
set it as visited and plot a point */ i) (D[Dval] == ') 6 D[Dval]= 1; Cpts[tot_points]= lam.da; ypts[tot_points]= C; tot_points++; i) (tot_points == 7A819:;<S) 6 print) (A<oo many points to plotKnA); ret rn (1; ? ?
void 2rite_3d_array (char )ilename []4 int no_points4 )loat CaCis[]4 )loat yaCis[]) /* Lrite the C and y points o) the graph to a )ile4 named in the string )ilename4 in a )ormat )or maple plotting C aCis and yaCis sho ld contain at least no_points pieces o) data, */ 6 @:=5 *)ptr; int i; )ptr= )open ()ilename4 A2A); i) ()ptr == ;>==) 6 )print) (stderr4 A>na.le to open KAMsKA to 2riteKnA4 )ilename); eCit ((1); ? /* Lrite all the points to the )ile*/ )or (i= '; i + no_points; i++) 6 )print) ()ptr4 AM) M)KnA4 CaCis[i]4 yaCis[i]); ? )close()ptr); ? E+ternal Docu"entat#on +he role o$ e&ternal documentation is to let another #rogrammer who will !e wor-ing on "our code understand what is going on and how he or she might modi$" "our code. 1t4s hard to give a general descri#tion o$ how to document code since ever" com#an" has its own standards $or this. 1n addition man" automatic documentation tools e&ist $or this #ur#ose. +his descri#tion is intended as a reasona!le wa" o$ documenting at the level re/uired $or "our #ro*ects rather than as a descri#tion o$ =!est #ractice> in the real world. Documentation must !e done at several levels: 1) Descri!e the !road #ur#ose o$ "our code what it is su##osed to achieve and how. Descri!e what $iles the #rogram needs to run and how it wor-s (in !rie$). +his section can !e /uite long in a com#le& #rogram. E&am#le:
'
+his tra$$ic simulation #rogram ta-es in#ut in the $orm o$ a =road networ-> (s#eci$"ing the la"out o$ a town4s road s"stem) and a =demand matri&> (s#eci$"ing the drivers who wish to use the networ-). +he networ- and the demand are s#eci$ied in in#ut $iles to the #rogram. +he structure o$ the in#ut and out#ut $iles is descri!ed in the user documentation. +he #rogram then simulates a da"4s travel on the road networ-s and #roduces out#ut into a results $ile. +he travel is simulated using an iterative #rocedure which.... (etc etc) ,) Descri!e the general =$low> o$ "our #rogram. +hat is5 how it wor-s as an algorithm i$ "ou4ve used #articular sorting routines $or e&am#le then descri!e which one. 9$ten this is clearer in a diagram $orm. E&am#le: +he main routine #er$orms the $ollowing tas-s: i) Cead in networ- $ile and demand $ile (e&it on errors). ii) ssign vehicles to the networ- $or a $irst iteration o$ the simulation. iii) ;ic- shortest routes $or the vehicles (uses Di*-stra4s algorithm see later descri#tion) assuming there will !e no congestion on the networiv) :imulate one da" o$ travel on the networ- (see section on =simulation methods>). v) (se the simulated congestion and travel times to #ic- new shortest #aths $or vehicles. vi) 1$ the vehicle routes have not =converged> (see section on =routing convergence>) then go to iv) vii) 9ut#ut results o$ the simulation (see section on =out#ut $ormats>) DNote that this is an e&am#le onl" and "ou need not use this $ormat5 sometimes something more li-e a traditional =$low chart> can !e ver" e$$ective.E .) Descri!e what =source modules> "our #rogram has i$ "ou have used multi#le $ile #rogramming. +hat is5 what .c## and .h $iles "ou have used and what the" each contain (a !rie$ list o$ the most im#ortant things in each $ile). E&am#le: netstr ct,h: +his header $ile contains t"#ede$4s relating to the structure o$ the road networ-. 1t de$ines the t"#es NE+W9CF and DE? ND which are structures re#resenting the to#olog" o$ the road structure and the demand which is a##lied to the networ-. roadsim,cpp: +his contains the main() $unction and the general control o$ the #rogram. sim late,cpp: +his contains the main simulation engine. +he most im#ortant $unctions are: calc_delay() which calculates the dela" e&#erienced at a #articular *unction t"#e. neCt_linF() which $inds the ne&t lin- $or a vehicle. ro te,cpp: +his contains route $inding algorithms: )ind_shortest(): calculates the shortest #ath through a networ-. . . . B) lmost an" struct<t"#ede$ used in "our code should !e descri!ed in the documentation unless it is #articularl" trivial. E&am#le: +he NE+W9CF structure descri!es the to#olog" o$ the networ- which the simulation is #er$ormed on. ?em!ers o$ the structure re#resent the *unctions and roads in the networ-. +he structure is de$ined in the $ile netstr ct,h
%) 3or each ma*or $unction descri!e what that $unction does5 what varia!les it ta-es and what it returns. +his is ver" similar to the comments made on ever" $unction on the internal documentation. Note that 1 have !een vague a!out what constitutes a =ma*or> $unction. 0our code $or this #ro*ect is li-el" to !e short enough that e&#laining ever" $unction won4t ta-e too long. ;a" #articular attention to descri!ing $unctions which are doing the =real wor-> these are not necessaril" the most com#licated ones to write it can !e ver" com#licated to write a $ile in#ut $unction to read individual words !ut it would not !e use$ul (or #articularl" interesting) to s#end a great deal o$ time descri!ing this. E&am#le: roadsim,cppO )loat calc_delay(int linF_no4 int vehicle_no) +his $unction ta-es as its in#ut the num!er o$ a lin- (road) in the simulation and the num!er o$ a vehicle which is a!out to e&it that lin-. +he routine calculates the dela" using We!sterAs $ormula (see earlier documentation) and returns it as a $loat. +his routine will crash with an error i$ the vehicleHno s#eci$ied is out o$ range. int neCt_linF(int vehicle_no) +his $unction considers vehicle num!er 2vehicleHno2 which is a!out to e&it a *unction at the end o$ a lin-. +he routine returns the num!er o$ the ne&t lin- which the vehicle will move into. +his routine will return A<_B5S<:;A<:9; (de$ined to !e 1 in netstr ct,h) i$ the vehicle has arrived at its home. )loat calc_travel_speed(int linF_no4 int vehicle_no) ... etc etc etc 0ou should also comment on an" e/uations "ou use within the code unless their #ur#ose is #articularl" o!vious. 1$ there is an"thing unusual a!out how the #rogram wor-s or an" /uir-s then these should !e mentioned. E&am#le: +he #rogram can crash i$ the networ- in#ut $ile is !adl" $ormatted. 1t is ho#ed to $i& this in a $uture release. +his is a #ro!lem with the read_net2orF() routine User Docu"entat#on (ser documentation is written to descri!e to the end6user how to run "our #rogram. Writing user documentation is an art6$orm in itsel$ and entire !oo-s have !een written on how to do it. 1n general "our #rograms will not !e com#le& enough to re/uire e&tensive user documentation so 1 don4t intend to teach "ou an"thing a!out how to write this. 3eel $ree to include limited user documentation in "our write u# i$ "ou want (!ut don4t s#end too long on it5 it is not reall" ver" im#ortant to "our mar-).