Tutorial on Good Lisp Programming Style
Total Page:16
File Type:pdf, Size:1020Kb
Lisp Users and Vendors Conference August Tutorial on Go o d Lisp Programming Style Peter Norvig Sun Microsystems Labs Inc Kent Pitman Harlequin Inc c Portions copyright Peter Norvig c Portions copyright Kent M Pitman All Rights Reserved Outline What is Go o d Style Tips on BuiltIn Functionality Tips on NearStandard Tools Kinds of Abstraction Programming in the Large Miscellaneous What is Go o d Style Good Lisp Programming Style Elegance is not optional Richard A OKeefe Good style in any language leads to programs that are Understandable Reusable Extensible Ecient Easy to developdebug It also helps correctness robustness compatibility Our maxims of go o d style are Be explicit Be sp ecic Be concise Be consistent Be helpful anticipate the readers needs Be conventional dont b e obscure Build abstractions at a usable level Allow to ols to interact referential transparency Good style is the underware that supp ortsaprogram Where do es go o d style come from What To Believe Dont b elieve everything we tell you Just most Worry less ab out what to b elieve and more ab out why Know where your Style Rules come from Religion Go o d vs Evil This way is b etter Philosophy This is consistent with other things Robustness Liability Safety Ethics Ill put in redundant checks to avoid something horrible Legality Our lawyers say do it this way Personality Opinion I like it this way Compatibility Another to ol exp ects this way Portability Other compilers prefer this way Co op eration Convention It has to be done some uniform waysowe agreed on this one Habit Tradition Weve always done it this way Ability My programmers arent sophisticated enough Memory Knowing how I would do it means I dont have to rememb er howIdid do it Sup erstition Im scared to do it dierently Practicality This makes other things easier Where do es go o d style come from Its All Ab out Communication Expression Understanding Communication Programs communicate with Human readers Compilers Text editors arglist do c string indent To ols trace step aprop os xref manual Users of the program indirect communication Where do es go o d style come from Know the Context When reading co de Know who wrote it and when When writing co de Annotate it with comments Sign and date your comments Should b e an editor command to do this Some things to notice Peoples style changes over time The same p erson at dierent times can seem like a dierent p erson Sometimes that p erson is you How do I knowifitsgood Value Systems Are Not Absolute Style rules cannot b e viewed in isolation They often overlap in conicting ways The fact that style rules conict with one another re ects the natural fact that realworld goals conict A good programmer makes tradeos in programming style that reect underlying priority choices among var ious major goals Understandable Reusable Extensible Ecient co ding space sp eed Easy to developdebug How do I knowifitsgood Why Go o d Style is Go o d Good style helps build the current program and the next one Organizes a program relieving human memory needs Encourages mo dular reusable parts Style is not just added at the end It plays a part in Organization of the program into les Toplevel design structure and layout of each le Decomp osition into mo dules and comp onents Datastructure choice Individual function designimplementation Naming formatting and do cumenting standards How do I knowifitsgood Why Style is Practical Memory When I was young I could imagine a castle with twenty ro oms with each ro om having ten dierent ob jects in it I would have no problem I cant do that anymore Now I think more in terms of earlier exp eri ences I see a network of inchoate clouds instead of the picturep ostcard clearness But I do write b etter programs Charles Simonyi Some p eople are go o d programmers b ecause they can handle many more details than most p eople But there are a lot of disadvantages in selecting programmers for that reasonit can result in programs no on else can maintain Butler Lampson Pick out any three lines in my program and I can tell you where theyre from and what they do David McDonald Good style replaces the need for great memory Make sure any lines are selfexplanatory Also called referential transparency Package complexity into objects and abstractions not global variablesdep endencies Make it fractally selforganizing all the way updown Saywhatyou mean Mean what you say How do I knowifitsgood Why Style is Practical Reuse Structured Programming encourages mo dules that meet sp ecications and can b e reused within the b ounds of that sp ecication Stratied Design encourages mo dules with commonly needed functionality which can be reused even when the sp ecication changes or in another program ObjectOriented Design is stratied design that con centrates on classes of objects and on information hid ing You should aim to reuse Data typ es classes Functions metho ds Control abstractions Interface abstractions packages mo dules Syntactic abstractions macros and whole languages How do I knowifitsgood Say What You Mean Saywhatyou mean simply and directly Kernighan Plauger Say what you mean in data b e sp ecic concise Use data abstractions Dene languages for data if needed Cho ose names wisely Say what you mean in co de b e concise conventional Dene interfaces clearly Use Macros and languages appropriately Use builtin functions Create your own abstractions Dont do it twice if you can do it once In annotations b e explicit helpful Use appropriate detail for comments Do cumentation strings are b etter than comments Saywhatitisfor not just what it do es Declarations and assertions Systems and test les etc How do I knowifitsgood Be Explicit Optional and Keyword arguments If you have to lo ok up the default value you need to supply it You should only take the default if you truly b elieve you dont care or if youre sure the default is wellundersto o d and wellaccepted byall For example when op ening a le you should almost never consider omitting the direction keyword argu ment even though you know it will default to input Declarations If you knowtyp e information declare it Dont do what some p eople do and only declare things you know the compiler will use Compilers change and you want your program to naturally take advantage of those changes without the need for ongoing intervention Also declarations are for communication with human readers to onot just compilers Comments If youre thinking of something useful that others might want to know when they read your co de and that might not b e instantly apparent to them make it a comment How do I knowifitsgood Be Sp ecic Be as sp ecic as your data abstractions warrant but no more Cho ose more specific more abstract mapc processword map nil processword first sentences elt sentences Most sp ecic conditional if fortwobranch expression when unless foronebranch statement and or for b o olean value only cond for multibranch statement or expression Violates Expectation Follows Expectation and numberp x cos x and numberp x x if numberp x cos x if numberp x cos x nil if numberp x print x when numberp x print x How do I knowifitsgood Be Concise Test for the simplest case If you make the same test or return the same result in two places there must b e an easier way Bad verb ose convoluted defun countallnumbers alist cond null alist t if listp first alist countallnumbers first alist if numberp first alist countallnumbers rest alist Returns twice Nonstandard indentation alist suggests asso ciation list Good defun countallnumbers exp typecase exp cons countallnumbers first exp countallnumbers rest exp number t cond instead of typecase is equally go o d less sp ecic more conventional consistent How do I knowifitsgood Be Concise Maximize LOCNW lines of co de not written Shorter is b etter and shortest is b est Jim Meehan Bad to o verb ose inecient defun vectoradd x y let z nil n setq n min listlength x listlength y dotimes j n reverse z setq z cons nth j x nth j y z defun matrixadd A B let C nil m setq m min listlength A listlength B dotimes i m reverse C setq C cons vectoradd nth i A nth i B C Use of nth makes this O n Why listlength Why not length or mapcar Why not nreverse Why not use arrays to implement arrays The return value is hidden How do I knowifitsgood Be Concise Better more concise defun vectoradd x y Elementwise add of two vectors mapcar x y defun matrixadd A B Elementwise add of two matrices lists of lists mapcar vectoradd A B Or use generic functions defun add rest args Generic addition if null args reduce binaryadd args defmethod binaryadd x number y number x y defmethod binaryadd x sequence y sequence map typeof x binaryadd x y How do I knowifitsgood Be Helpful Do cumentation should b e organized around tasks the user needs to do not around what your program hap p ens to provide Adding do cumentation strings to each function usually do esnt tell the reader how to use your program but hints in the right place can be very ef fective Good from Gnu Emacs online help nextline Move cursor vertically down ARG lines If you are thinking of usingthisinaLispprogram consider using forwardline instead It is usually eas ier to use and more reliable no dep endence on goal column etc defun denes NAME as a function The denition is lambda ARGLIST DOCSTRING BODY See also the function interactive These anticipate users use and problems How do I knowifitsgood Be Conventional Build your own