You are on page 1of 47

LEARNABLE

PROGRAMMING
Designingaprogrammingsystemforunderstandingprograms
BretVictor/September2012

Here'satrickquestion:Howdowegetpeopletounderstandprogramming?
KhanAcademyrecentlylaunchedanonlineenvironmentforlearningtoprogram.Itoffersa
setoftutorialsbasedontheJavaScriptandProcessinglanguages,andfeaturesa"livecoding"
environment,wheretheprogram'soutputupdatesastheprogrammertypes.
BecausemyworkwascitedasaninspirationfortheKhansystem,IfeltIshouldrespondwith
twothoughtsaboutlearning:
Programmingisawayofthinking,notaroteskill.Learningabout"for"loopsisnot
learningtoprogram,anymorethanlearningaboutpencilsislearningtodraw.
Peopleunderstandwhattheycansee.Ifaprogrammercannotseewhataprogramis
doing,shecan'tunderstandit.
Thus,thegoalsofaprogrammingsystemshouldbe:
tosupportandencouragepowerfulwaysofthinking
toenableprogrammerstoseeandunderstandtheexecutionoftheirprograms
AlivecodingProcessingenvironmentaddressesneitherofthesegoals.JavaScriptand
Processingarepoorlydesignedlanguagesthatsupportweakwaysofthinking,andignore
decadesoflearningaboutlearning.Andlivecoding,asastandalonefeature,isworthless.

AlanPerliswrote,"Tounderstandaprogram,youmustbecomeboththemachineandthe
program."Thisviewisamistake,anditisthiswidespreadandvirulentmistakethatkeeps
programmingadifficultandobscureart.Apersonisnotamachine,andshouldnotbeforced
tothinklikeone.
Howdowegetpeopletounderstandprogramming?
Wechangeprogramming.Weturnitintosomethingthat'sunderstandablebypeople.

Contents
Aprogrammingsystemhastwoparts.Theprogramming"environment"isthepartthat's

Theconceptofasystemsplitbetweenthe

installedonthecomputer.Theprogramming"language"isthepartthat'sinstalledinthe

computerandtheheadwasderivedfrom

programmer'shead.

WillWright'sthoughtsongames.

Thisessaypresentsasetofdesignprinciplesforanenvironmentandlanguagesuitablefor
learning.
Theenvironmentshouldallowthelearnerto:
readthevocabularywhatdothesewordsmean?
followtheflowwhathappenswhen?
seethestatewhatisthecomputerthinking?
createbyreactingstartsomewhere,thensculpt
createbyabstractingstartconcrete,thengeneralize
Thelanguageshouldprovide:
identityandmetaphorhowcanIrelatethecomputer'sworldtomyown?
decompositionhowdoIbreakdownmythoughtsintomindsizedpieces?
recompositionhowdoIgluepiecestogether?
readabilitywhatdothesewordsmean?

Thefeaturesarenotthepoint

Weoftenthinkofaprogrammingenvironmentorlanguageintermsofitsfeaturesthisone
"hascodefolding",thatone"hastypeinference".Thisislikethinkingaboutabookintermsof
itswordsthisbookhasa"fortuitous",thatonehasa"munificent".Whatmattersisnot
individualwords,buthowthewordstogetherconveyamessage.
Likewise,awelldesignedsystemisnotsimplyabagoffeatures.Agoodsystemisdesigned
toencourageparticularwaysofthinking,withallfeaturescarefullyandcohesivelydesigned
aroundthatpurpose.
Thisessaywillpresentmanyfeatures!Thetrickistoseethroughthemtoseethe
underlyingdesignprinciplesthattheyrepresent,andunderstandhowtheseprinciplesenable
theprogrammertothink.

READ THE
VOCABULARY
Hereisasimpletutorialprogramthatalearnermightface:
Forthesakeofcomparison,theexamples
herewillusethesamelanguagesasthe
KhanAcademysystem,JavaScriptand
Processing.

Beforeareadercanmakeanysenseofthiscode,beforeshecanevenbegintounderstand

howitworks,herearesomequestionsshewillhave:

KhanAcademy'stutorialsencouragethelearnertoaddressthesequestionsbyrandomly
adjustingnumbersandtryingtofigureoutwhattheydo.

Thoughtexperiment.Imagineifyouboughtanewmicrowave,tookitoutofthebox,and
foundapanelofunlabeledbuttons.

Imagineifthemicrowaveencouragedyoutorandomlyhitbuttonsuntilyoufiguredoutwhat
theydid.

Now,imagineifyourcookbookadvisedyouthatrandomlyhittingunlabeledbuttonswashow
youlearncooking.

Makemeaningtransparent
Learningcookingisnotaboutguessingthefunctionalityofyourkitchenappliances.It'sabout
understandinghowingredientscanbecombined.
Likewise,guessingthethirdargumentofthe"ellipse"functionisn't"learningprogramming".
It'ssimplyabarriertolearning.Inamodernenvironment,memorizingtheminutiaofanAPI
shouldbeasrelevantasmemorizingtimestables.
Theenvironmentisresponsibleformakingmeaningtransparent.Theenvironmentmust
enablethereadertoeffortlesslyreadtheprogram,todecodethecode,soshecan
concentrateongenuineprogrammingconceptshowthealgorithmic"ingredients"combine.
Hereisoneexampleofhowaprogrammingenvironmentcanmakemeaningtransparent,by
providinglabelsonmouseover:

Controlstructurescanbelabeledaswell.

It'stemptingtothinkofthisas"inlinehelp",butit'snothelpit'ssimplylabeling.The
problemwiththefollowingUIisn'tthatitlacksa"helpfeature".Theproblemisthatnothingis
labeled.

ThatUIisexactlyasinformativeasthislineofcode:

WhydoweconsiderthecodeacceptableandtheUInot?Whydoweexpectprogrammersto
"lookup"functionsin"documentation",whilemodernuserinterfacesaredesignedsothat
documentationistypicallyunnecessary?

Explainincontext
Aprogrammingenvironmentisauserinterfaceforunderstandingaprogram.Especiallyinan
environmentforlearning,theenvironmentmustbedesignedtoexplain.

Oneattributeofgreatexplanationsisthattheyareoftenembeddedinthecontextofwhat
theyareexplaining.Thatis,theyshowaswellastell.

Insteadofjustdescribingwhatvocabularymeans,wecanoftenshowitinthecontextofthe
data.Inthefollowingexample,thelabelsconnectthecodeanditsoutput:

Suchaconnectioncanbeespeciallypowerfulwhenalineofcodedoesmultiplethings:

SummaryReadthevocabulary
Theparticularsolutionsshownherearemerelyexamples.Whatmattersistheunderlying
purpose:enablingthelearnertoreadtheprogram.
Theenvironmentshouldmakemeaningtransparent,sothelearnercanconcentrateon
highlevelconcepts,notvocabulary.
Theenvironmentshouldexplainincontext.Showandtell.Annotatethedata,notjust
thecode.
Theexamplesabovearejustoneofmanywaysofachievingthesegoals.Allthatreally
mattersisthatsomehowthelearner'squestionsgetanswered:

Anenvironmentwhichallowslearnerstogethunguponthesequestionsisanenvironment
whichdiscourageslearnersfromevengettingstarted.

FOLLOW THE
FLOW

Atypicallivecodingenvironmentpresentsthelearnerwithcodeontheleft,andtheoutputof
thecodeontheright.Whenthecodeischanged,theoutputupdatesinstantaneously.

Anotherthoughtexperiment.Imagineacookingshow,ruthlesslyabbreviated.First,you're
shownacounterfullofingredients.Then,youseeadelicioussouffl.Then,theshow'sover.

Wouldyouunderstandhowthatsoufflwasmade?Wouldyoufeelpreparedtocreateone
yourself?
Ofcoursenot.Youneedtoseehowtheingredientsarecombined.Youneedtoseethesteps.
Theprogrammingenvironmentexhibitsthesameruthlessabbreviationasthishypothetical
cookingshow.Weseecodeontheleftandaresultontheright,butit'sthestepsinbetween
whichmattermost.Thecomputertracesapaththroughthecode,loopingaroundloopsand
callingintofunctions,updatingvariablesandincrementallybuildinguptheoutput.Wesee
noneofthis.
Peopleunderstandthingsthattheycanseeandtouch.Inorderforalearnertounderstand

whattheprogramisactuallydoing,theprogramflowmustbemadevisibleandtangible.

Makeflowtangible
Thatexampleprogramagain:

Thisisaparticularlydifficultexampleforabeginnertofollow.The"for"construct,withits
threestatementsonasingleline,makesthecontrolflowjumparoundbizarrely,andisan
unnecessarilysteepintroductiontotheconceptoflooping.

Tomaketheflowmoresaneforalearner,theloopcanberewrittenusing"while":

Now,thecontrolflowmustbemadetangible.Wemustputtheexecutionoftheprograminto
theprogrammer'shand,letherfeelthatitisarealthing,letherownit.

Inthefollowingexample,theprogrammerusesaslidertoscrubthroughtheexecution:

Thiscontrolallowstheprogrammertomovearoundtheloopatherownpace,andunderstand
whatishappeningateachstep.Shecangobackwardsandforwards,dwellindifficultareas,
andcomparewhatishappeningatdifferenttimes.Shecanstudyhowtheoutputisbuiltup
overtime,insteadofseeingitmagicallyappearallatonce.

Makeflowvisible
Theexampleaboveallowstheprogrammertofollowtheprogram'sexecutionovertime.But
she'speekingthroughapinhole,onlyseeingasinglepointintimeatanyinstant.Shehasno
visualcontext.
ToillustratewhatImean,herearetworepresentationsofatriparoundmyneighborhood,one
wheretheneighborhooditselfisn'tvisible,andonewhereitis.

This"overheadview"letsapersonunderstandthetripatahigherlevel.Shecanseethe
shapeofthetrip.Shecanseepatterns.
Inthefollowingexample,theprogramflowisplottedonatimeline.Eachlineofcodethatis
executedleavesadotbehind.Theprogrammercantakeintheentireflowataglance:

Thepatternsthatemergeareespeciallyhelpfulinthepresenceofconditionalsandother
formsofflowcontrol:

Thisvisualizationallowstheprogrammertoseethe"shape"ofanalgorithm,andunderstandit

It'spossiblethatsomenovicesmayinitially

atahigherlevel.Theprogramflowisnolonger"onelineafteranother",butapatternoflines

beconfusedbyatimeline,butI'dsaythat

overtime.

learningtoreadatimelineisafarmore
valuableandgeneralskillthanlearningthe
detailsofsomegraphicslibrary.

Maketimetangible
Linebylineexecutionisaveryfinegrainedviewoftime.Theprogrammeralsothinksabout

timeatothergranularities.
Forinstance,animationsandgamesrunataframerate,say,sixtyframespersecond.Every
1/60thofasecond,theprogrampreparesthenextframetodisplayonthescreen.Other
programsareeventdriventheyrespondtoanexternalevent,suchasabuttonclickor
networkrequest,byperformingsomecomputation,andthentheywaitforthenextevent.
Theseframesoreventresponsesformanaturalwayof"chunking"time.Iftheexecutionofa
lineofcodeislikeasentence,thenaframeislikeachapter.Thesechapterscanalsobe
madetangible,sotheprogrammercanunderstandtheexecutionatthisgranularityaswell.
Thefollowingexampleprovidesatimelineforexploringlinebylineexecution,andasliderfor
exploringframebyframe.

Thiscontrolenablestheprogrammertogobackwardsandforwardsthroughtime,study
interestingframes,andcomparetheexecutionacrossdifferentframes.

Maketimevisible
Intheaboveexample,weareonceagainpeekingthroughapinhole,seeingjustoneframeat
atime.Inthefollowingexample,allframesarelightlyoverlaid,inordertogivecontextto
theactiveframe.Theentirepathoftheballcanbeseenatonce.

*Oneofthedeepestandmostpowerful
ideasinmathematicsistherelationship
betweenadifferentialformulation(suchas

Theoutputoftheprogramisnolongeraseriesoffleetingmoments,butcanbeseenasa
single,solidthingthatextendsovertime.Thereisgreatpowerinthiswayofthinking.*

astepbystepprocess,likeour"draw"
function)anditsintegratedform(suchasa
functionoftime,orplotovertime).
"Flatteningtime"allowsthelearnertosee
theprocessanditstrajectoryastwo

SummaryFollowtheflow
Again,theparticularsolutionsshownherearemerelyexamples.Whatmattersisthe
underlyingpurpose:enablingthelearnertofollowtheprogramflow,bycontrollingtimeand
seeingpatternsacrosstime.Transformingflowfromaninvisible,ephemeralnotionintoa
solidthingthatcanbestudiedexplicitly.
Theenvironmentcanmakeflowtangible,byenablingtheprogrammertoexplore
forwardandbackwardatherownpace.
Theenvironmentcanmakeflowvisible,byvisualizingthepatternofexecution.
Theenvironmentcanrepresenttimeatmultiplegranularities,suchasframesorevent
responses,toenableexplorationacrossthesemeaningfulchunksofexecution.

representationsofthesamething,and
therebythinkoftheminterchangeably.

SEE THE
STATE
Asimpleprogram:

Thethirdlinedeclaresavariablenamed"scaleFactor",whichvarieswitheachiterationofthe
loop.

Takeamomenttolookatthatline,andthinkaboutthesequestions:
WhatvaluesdoesscaleFactortakeon?1?100?1?pi/2?
WhatisscaleFactoratthebeginningoftheloop?Attheend?
HowdoesscaleFactorchangeoverthecourseoftheloop?Linearlyup?Linearlydown?
Doesthechangegetfasterorslower?
Wait.Waitaminute.Wereyoutryingtoanswerthosequestionsbydoingarithmeticinyour
head?Thecomputersomehowdrewthatpicture,sothecomputermusthavecalculatedall
thosescaleFactorsitself.Areyouseriouslyrecalculatingtheminyourhead?
NowimagineifscaleFactoralsodependedonsomeothervariables,orsomeotherfunctions,

*Otherthansettinga"breakpoint",which

orexternalinput.Therewouldbenowaytoeasilyanswerthosequestions.*

islikemonitoringtrafficonthefreewayby
settingupabarricade.Orwritingtoa

Thinkaboutthis.Weexpectprogrammerstowritecodethatmanipulatesvariables,without

"console",whichislikefiguringoutwhere

everseeingthevaluesofthosevariables.Weexpectreaderstounderstandcodethat

yourdoggoesduringthedaybyfollowing

manipulatesvariables,withouteverseeingthevaluesofthevariables.Theentirepurposeof

thetrailofdroppings.

codeistomanipulatedata,andweneverseethedata.Wewritewithblindfolds,andwe
readbyplayingpretendwithdataphantomsinourimaginations.
InformationdesignpioneerEdwardTuftehasoneprimaryrule,andthisruleshouldbethe

Oneofthealltimemostpopular

principleunderlyinganyenvironmentforcreatingorunderstanding.

programmingmodelsisthespreadsheet.A
spreadsheetisthedualofaconventional

Showthedata.
Ifyouareseriousaboutcreatingaprogrammingenvironmentforlearning,thenumberone

programminglanguagealanguage
showsallthecode,buthidesthedata.A
spreadsheetshowsallthedata,buthides

thingyoucandomoreimportantthanlivecodingoradjustableconstants,moreimportant

thecode.Somepeoplebelievethat

thannarratedlessonsordiscussionforums,moreimportantthanbadgesorpointsorultra

spreadsheetsarepopularbecauseoftheir

pointsoranythingelseistoshowthedata.

twodimensionalgrid,butthat'saminor
factor.Spreadsheetsrulebecausethey
showthedata.

Showthedata
Becausethevalueofavariablevariesovertime,showingthedataisintimatelyconnected
withshowingtime.
Theprevioussectionpresentedatimelinerepresentationthatshowedthedataateachstep.In
thefollowingexample,theprogrammermousesoveraparticularrowofthetimelineto
concentrateonasingleline.

Inthisexample,itiseasytoanswerthefirsttwoquestions.Byskimmingovertheexecution
ofthatlineofcode,wecanseeallofthevaluesthatscaleFactortakeson,andwhen.
However,itisstilldifficulttoanswerthethirdquestion:howdoesthevariablevary?Whatis
theshapeofitschange?Thequestionisdifficultbecauseweare,onceagain,peekingthrough
apinhole,onlyseeingasinglepointatatime.
EdwardTuftehasasecondrule.Itisnotenoughtojustshowthedata.Wemustshow
comparisons.

Showcomparisons
Dataneedscontext.Itisrarelyenoughtoseeasingledatapointinisolation.Weunderstand
databycomparingittootherdata.
Thetimelineexamplessofarhaveuseddotstorepresentexecutedlines.Butinsteadofdots,
wecanshowdata.ThefollowingtimelineshowseachofthescaleFactors:

Almosteverylineofcodeherecalculatessomething.Theenvironmentshouldprovidethebest
visualizationofwhateverthatsomethingis.Forexample,the"rotate"linecanshowthe
rotations.

The"fill"linesetsafillcolor.Thatcolorcanbeshown.

The"triangle"linedrawsatriangletothecanvas,rotatedandcolored.Thetimelinecanshow
athumbnailofeachtriangleproduced.

Takentogether,wehaveatimelinethatdepictsnotjusttheflow,butallofthedatacalculated
inthatflow.Theexecutionoftheprogramislaidbareforthereader.Ataglance,shecansee
whichlineswereexecuted,whentheywereexecuted,andwhattheyproduced.Theflowand
thedataarebothshownincontext.

Theexampleaboveonlyloopstwentytimes.Isitpossibletounderstandaloopwith,say,
thousandsofiterations,withoutdrowninginthousandsofnumbers?
Yesthereisanentirefieldofstudydevotedtodepictinglargeamountsofnumbers.To
visualizethisdata,wecanuseallofthestandardtechniquesofdatavisualization.
Inthefollowingexample,astheprogrammerzoomsthetimelineout,thevisualization
automaticallyswitchesfromatabletoaplot.

Eliminatehiddenstate
Inordertounderstandwhatalineofcodedoes,thelearnermustseeitseffect.Forexample,

astheprogrammermovesoveriterationsofthe"triangle"line,sheseeseachtriangleappear
onthecanvas:

The"fill"line,ontheotherhand,setsthefillcolorforsubsequentdrawingoperations.When
theprogrammermovesoverthisline,whateffectdoesshesee?Sheseesnothinghappen,
becausethe"fill"functionmodifieshiddenstate.
TheProcessinggraphicslibraryreliesheavilyonimplicitstate,intheformofthe"current"fill
color,strokecolor,transformmatrix,andsoon.Codethatmodifiesthisstateproducesno
visibleeffectonthecanvas.Inaninteractiveenvironment,thisisunacceptable.
Therearetwodesignoptionshere.Onealternativeistoeliminatethestate.Forexample,
colorcouldbepassedasaparametertothe"triangle"function.

Theotheralternativeistoshowthestate.Inthefollowingexample,thecurrentfilland
strokecolorsareshownabovethecanvas.Now,whenalineofcodechangesthefillcolor,the
programmeractuallyseessomethingchange.Makingsomethingvisiblemakesitreal.

Allstatemustbeeliminatedorshown.Eithercanbeareasonabledesigndecision.An
environmentthatdoesneitherforcinglearnerstoimaginethestateandmakesenseof
functionsthatproducenovisibleeffectisirresponsibledesign,anddisrespectfultothe
learner.
Thecurrenttransformmatrixisaparticularlycriticalandconfusingmemberofthestate.

Justtheconceptofa"transformmatrix"is

DrawinganythinginterestingwiththeProcessinggraphicslibraryrequiresmatrixtransforms,

undoubtablybafflingformanylearners,but

butthecurrenttransformisinvisible.Functionssuchas"scale"and"rotate"havenovisible

withabettermetaphor,itneedn'tbeso.

effect,andcompoundtransformations(suchastranslationfollowedbyscale,orshoulditbe
theotherwayaround?)ofteninvolvegropingblindlythroughtrialanderror.
Inthefollowingexample,thetransformisvisualized,andtheeffectofeveryfunctioncanbe
seendirectly.

Logo,forinstance,usesaturtletoreify
translationandrotation,andchildren
understanditreadily.Moreonthislater.

SummarySeethestate
Codemanipulatesdata.Tounderstandcode,alearnermustseethedata,andseetheeffectof
codeonthedata.
Theenvironmentmustshowthedata.Ifalineofcodecomputesathing,thatthing
shouldbeimmediatelyvisible.
Theenvironmentmustshowcomparisons.Ifaprogramcomputesmanythings,allof
thosethingsshouldbeshownincontext.Thisisnothingmorethandatavisualization.
Thesystemmusthavenohiddenstate.Stateshouldeitherbeeliminated,or
representedasexplicitobjectsonthescreen.Everyactionmusthaveavisibleeffect.

CREATE BY
REACTING
Iwasrecentlywatchinganartistfriendbeginapainting,andIaskedhimwhataparticular
shapeonthecanvaswasgoingtobe.Hesaidthathewasn'tsureyethewasjust"pushing
paintaroundonthecanvas",reactingtoandgettinginspiredbytheformsthatemerged.
Likewise,mostmusiciansdon'tcomposeentiremelodiesintheirheadandthenwritethem
downinstead,theynoodlearoundonainstrumentforawhile,playingwithpatternsand
reactingtowhattheyhear,adjustingandsculpting.
Anessentialaspectofapainter'scanvasandamusicalinstrumentistheimmediacywith
whichtheartistgetssomethingtheretoreactto.Acanvasorsketchbookservesasan
"externalimagination",whereanartistcangrowanideafrombirthtomaturityby

continuouslyreactingtowhat'sinfrontofhim.
Programmers,bycontrast,havetraditionallyworkedintheirheads,firstimaginingthedetails
ofaprogram,thenlaboriouslycodingthem.
Workingintheheaddoesn'tscale.Theheadisahardwareplatformthathasn'tbeenupdated
inmillionsofyears.Toenabletheprogrammertoachieveincreasinglycomplexfeatsof
creativity,theenvironmentmustgettheprogrammeroutofherhead,byprovidingan
externalimaginationwheretheprogrammercanalwaysbereactingtoaworkinprogress.
Someprogrammingsystemsattempttoaddressthiswithasocalled"livecoding"

*Recently,somepeoplehavemistakenly

environment,wheretheoutputupdatesimmediatelyasthecodechanges.Anexampleoflive

attributedthe"livecoding"concepttome,

coding:*

butit'snotanewidea,it'scertainlynot
"myidea",andit'snotaparticularly
interestingideainitself.Immediateupdate
ismerelyaprerequisitefordoinganything
interestingitenablesotherfeatures
whichrequireatightfeedbackloop.An
actiongamewithalowframerateisabad
game,butsimplyuppingtheframerate
doesn'tmagicallymakeagamegood.

Asyoucansee,livecoding,onitsown,isalmostworthless.Theprogrammerstillmusttype
atleastafulllineofcodebeforeseeinganyeffect.Thismeansthatshemustalready
understandwhatlineofcodesheneedstowrite.Theprogrammerisstilldoingthecreative
workentirelyinherheadimaginingthenextadditiontotheprogramandthentranslatingit
intocode.

Getsomethingonthescreenassoonaspossible
Livecodingdoes,however,provideafoundationforotherfeatureswhichcanjumpstartthe
createbyreactingprocess.Inthefollowingexample,theenvironmentoffersautocomplete
withdefaultarguments.Aftertypingjustacoupleofcharacters,theprogrammerimmediately
seessomethingonthescreen,andcanproceedtoadjustit.

Autocompleteisacommonfeatureofmostprogrammingenvironments,buttherearetwo
criticalsubtletieshere.First,thefunctionsallhavedefaultarguments(position,width,height,
andsoonarealreadyfilledin),soeachcompletionisacompletestatementthatproducesa
visibleeffect.Second,adefaultcompletionisselectedimmediately.Here'swhatthismeans
fortheprogrammer'sthoughtprocess:
Intheexampleabove,theprogrammerwantstodrawaroofonthehouse.Shedoesn'tneed
tomentallyplanouthowtodrawtheroofbeforehandshedoesn'tneedtoimaginewhich
functionswouldbeappropriate.Shejustneedsthevaguenotion:"Iwanttodrawsomething."
Shestartstyping"draw",andimmediatelyseesashapeonthescreen.
Atthispoint,shecanstopimaginingandstartreacting:
"Thisisthewrongshape.Whichshapewillworkbetter?"Shegoesdownthelistandturns
theshapeintoatriangle.
"Thisisarighttriangle.Iwantadifferenttriangle."Sheadjuststhetriangle'spointsintoa
morerooflikeshape.
"Theroofisn'tlyingonthehouse."Sheadjuststhetriangletoloweritontothehouse.
Thisexampleassumedahypotheticalgraphicslibrarywhichwasdesignedforautocomplete
allofthedrawingfunctionsbeginwith"draw",sothecompletionlistwouldappearasthe
designerintended.*
Adifferentwaytostructurethelibrarywouldbetoprovideasingle"shape"function,which
takesthetypeofshape(triangle,ellipse,etc.)asanargument.Forexample:

*Strangely,Idon'tactuallyknowofany
APIsthatareintentionallydesignedwith
autocompleteinmind.Idoknowmany
APIs,suchasProcessing,thataredesigned
forbrevity,whichisirrelevantinan
environmentwithgoodautocomplete.

Thiscouldhelptofurtherencouragethecreatebyreactingwayofthinking.Because
"drawTriangle"and"drawRect"aren'tinthevocabulary,theprogrammerwouldneverfind
herselfthinkingaboutspecificshapefunctionsbeforesomethingisonthescreen.Herstarting
pointisalwaysjust"shape".
Theenvironmentistheuserinterfaceforworkingwithaprogram.Considerthesecondmenu
thatappearedabove,with"line","triangle",etc.Ifanargumentcantakeoneoffivevalues,
theenvironmentshouldprovidethebestinterfaceforselectingamongthosevalues.Thatis,in
thissituation,theprogrammerisauserwhohastoselectoneoffivechoices.Howwoulda
goodUIdesignerrepresentthosefivechoices?Perhapsmorelikethis:

Whyshouldweexpectanythinglessfromaprogrammingenvironment?

Dumpthepartsbucketontothefloor

Asachild,youprobablyhadtheexperienceofplayingwithaconstructionkitofsomekind
Legos,orErectorSets,orevenjustblocks.Asafirstactbeforestartingtobuild,achildwill
oftenspreadoutallofthepartsonthefloor.

Thisprovidesmorethansimplyquickaccess.Itallowsthechildtoscantheavailableparts
andgetnewideas.AchildbuildingaLegocarmightspotawideflatpiece,anddecidetogive
thecarwings.
Thisisasecondformofcreatebyreacting.Inadditiontoreactingtotheobjectunder
construction,thechildisalsoreactingtothepartsshehasavailable.
Inthefollowingexample,theavailablefunctionsarelocatedadjacenttothecodingarea,and
theprogrammercanskimoverthese"parts"andgetideas.

Theaboveexampleencouragestheprogrammertoexploretheavailablefunctions.Alearner
whowouldneverthinktotrytypingthe"bezier"function,withitsunfamiliarnameandeight
arguments,cannoweasilystumbleuponitanddiscoverwhatit'sabout.
Theexampleaboveisonewayofrepresentingthe"partsbucket"forprogrammaticdrawing.
Butwouldauserinterfacedesignerconsiderthattobethebestinterfacefordrawingapicture
onacomputerscreen?Whataboutthefollowing?

play
again

Anobjectionmightariseatthispoint.Withthisinterface,isthiseven"programming"?
No,notreally.Butnoneoftheexamplesinthissectionare"programming".Typinginthecode
todrawastaticshape

isnotprogramming!It'smerelyaverycumbersomeformofillustration.Itbecomes
genuineprogrammingwhenthecodeisabstractedwhenargumentsarevariable,whena

blockofcodecandodifferentthingsatdifferenttimes.Thenextsectionwilldiscusshow
createbyreactingleadsintocreatebyabstracting.

SummaryCreatebyreacting
Thecreatebyreactingwayofthinkingcouldbestatedas:startwithsomething,thenadjust

*Thus,weneedapowerfulwayofgetting

untilit'sright.*

somethingonscreen,andpowerfulwaysof
adjustingit.Adjustablevalues(suchas

Theprogrammermustbeabletodoherthinkingoutintheenvironment,nottrappedinher

draggablenumbersorcolorpalettes)area

head.Theenvironmentmustserveasanexternalimagination,wheretheprogrammercanbe

valuablecomponentforthelatterpurpose,

continuouslyreactingtoaworkinprogress.

andIamalongtimeproponentof

Tobeclear,thisdoesnotrelievetheprogrammerfromthinking!Itsimplymakesthose

Calculator,ExplorableExplanations,Ten

thoughtsimmediatelyvisible.Iamhappytobecomposingthisessayinatexteditor,where

BrighterIdeas).However,Ihavealways

mywordsbecomevisibleandeditableassoonasIthinkofthem,asopposedtoworking
entirelyinternallyliketheoratorsandplaywrightsofthedistantpast.
Theenvironmentmustbedesignedtogetsomethingonthescreenassoonas
possible,sotheprogrammercanstartreacting.Thisrequiresmodelingthe
programmer'sthoughtprocess,anddesigningasystemthatcanpickupontheearliest
possibleseedofthought.
Theenvironmentmustdumpthepartsbucketontothefloor,allowingtheprogrammer
tocontinuouslyreacttoherrawmaterialandsparknewideas.

adjustablevalues(e.g.,Scrubbing

proposedadjustablenumbersinacontext
wheretheadjusteralreadyunderstandsthe
meaningofthenumber.Asmentioned
earlier,Iamveryuncomfortablewiththe
KhanAcademyapproachofencouraging
learnerstoadjustunlabelednumbersand
figureoutwhatthey'refor,andIfeelthat
thisisacaseofatoolbeingadopted
withoutanunderstandingofwhatpurpose
thetoolserves.

CREATE BY
ABSTRACTING

Learningprogrammingislearningabstraction.
Acomputerprogramthatisjustalistoffixedinstructionsdrawarectanglehere,thena
trianglethereiseasyenoughtowrite.Easytofollow,easytounderstand.

Italsomakesnosenseatall.Itwouldbemucheasiertosimplydrawthathousebyhand.
Whatisthepointoflearningto"code",ifit'sjustawayofgettingthecomputertodothings
thatareeasiertododirectly?
Becausecodecanbegeneralizedbeyondthatspecificcase.Wecanchangetheprogramsoit
drawsthehouseanywhereweask.Wecanchangetheprogramtodrawmanyhouses,and
changeitagainsothathousescanhavedifferentheights.Critically,wecandrawallthese
differenthousesfromasingledescription.

Thedescriptionstillsays"drawarectanglehere,thenatrianglethere",butthehereandthere
havebeenabstracted.Differentparametersgiveusdifferentheresanddifferenttheres.

Howdoesaprogrammerlearntowritethisabstractcode?Howdoesshelearntowritea
singledescriptionthatisgeneralizedformanycases?
Shedoesn't.Thelearnershouldstartbywritingconcretecode,andthengraduallychangeitto
introduceabstraction.Andtheenvironmentmustprovidethetoolstoperformthisprocess,in
suchawaythatthelearnercanunderstandtheprogramateachstage.

Startconstant,thenvary
Inthecreatebyabstractingwayofthinking,theprogrammerstartsbycreatingaspecific
case,typicallyinvolvingconstants.Shethenmovestothegeneralcasebyturningthose
constantsintovariables.Here'sanexampleofhowtheenvironmentcanencouragethiswayof
thinking,startingwiththehousefromearlier.

Theprogrammerwantstomovethehousetoadifferentlocation.Shecan'tmoveitby
adjustingasinglenumberinthecode,becausetherearefourdifferentpointswhichallneed
tochangeatthesametimetherectangle'sorigin,andthetriangle'sthreepoints.
Here,theprogrammerselectsoneofthenumbers,andconvertsitintoavariable.

Shethenconnectsthevariabletoanothernumber,bydraggingfromonetotheother.

Therearetwoadditionalargumentsto"triangle"whichneedtovaryaswell.Whenshe
connectsthevariable,whosevalueis80,totheconstant100,theenvironmentoffersachoice
offourpossiblerelationshipsbetweenthenumbers.

Thefourexpressionsinvolveaddition,subtraction,multiplication,anddivisionrespectively.
Oneofthemwilltypicallybeeitherthecorrectrelationshiporagoodstartingpoint.

Hereistheentireprocessofintroducingthevariable.

play
again

Startwithone,thenmakemany
Intheexampleabove,thehouseisnowabstractedthecodedoesn'tjustdrawonefixed
house,butcandrawahouseanywhere.Thisabstractedcodecannowbeusedtodrawmany
differenthouses.
Inthefollowingexample,theprogrammerwantstodrawarowofhouses.Sheselectsthe
abstractedcode,andconvertsitintoaloop.

play
again

Thevariableinthefirstlineoftheselectionbecomesaninductionvariable,andthe
programmercanthenadjustitsbounds.
Thisisaprocessofstartingwithaspecificcase,andprogressivelygeneralizing:
First,theprogrammercreatesahouseatafixedlocation.Here,shehasinteractive
controlovereachindividualshape.

Sheturnsthehouse'slocationintoavariable.Now,shehasinteractivecontroloverthe
variable,whichaffectsmanyshapes.
Sheintroducesalooptovarythatvariable.Now,shehasinteractivecontroloverthe
boundsoftheloop,whichaffectsmanyhouses,whichaffectmanyshapes.
Ateachstage,theprogrammerhasinteractivecontrolovertherelevantparameters,butthe
parametersareatsuccessivelyhigherlevelsofabstraction.Thatis,theprogrammercanstill
createbyreacting,butshe'screatingandreactingathigherlevels.

Insteadofdrawinganevenlyspacedrowofhouses,theprogrammernowwantsindividual
controlovereachofthehouses.Startingfromthevariableabstraction,sheselectsthecode
andconvertsitintoafunction.

play
again

0:14

Byduplicatingthefunctioncall,sheobtainsseveralhouseswhichcanbecontrolled
individually.
Now,insteadofidenticalhouses,shewantstovarytheheightsofthehouses.Sheintroduces
anothervariable,andthenconvertsitintoanadditionalargumenttothefunction.

play
again

Theprocess,again,consistsofstartingconcrete,andprogressivelyintroducingabstraction:*
Theprogrammercreatesadrawingofahouse.
Sheturnsxintoavariable,soshecancontrolthehouse'sposition.
Sheturnsxintoafunctionargument,sodifferenthousescanhavedifferentpositions.

*InLadderofAbstractionterminology,the
programmerclimbedtwolevelsonthe
ladderofabstractionshecontrolledx,
thenabstractedoverx,thencontrolledy,
thenabstractedovery.

Sheturnsyintoavariable,soshecancontrolthehouse'sheight.
Sheturnsyintoafunctionargument,sodifferenthousescanhavedifferentheights.

SummaryCreatebyabstracting
Startconcrete,startgrounded.Startwithonespecificcase,entirelyunderstood.Then
graduallygeneralize,levelbylevel,insuchawaythattheprogrammerstillfullyunderstands
theprogramateachlevelofabstraction.
Fullyconcretecodecanbemicromanagedtheprogrammerhasexplicitcontroloverevery
stepoftheexecution.Abstractionmeansgivingupsomeofthiscontrol,andthiscanbescary
foralearner.
Butthelearnercanworkuptoitintroduceavariable,interactivelycontrolit,connectthe
variabletoanothervalue,interactivelycontrolit,turnthevariableintoafunctionargument,
interactivelycontrolit.Thelearneralwaysgetstheexperienceofinteractivelycontrolling
thelowerleveldetails,understandingthem,developingtrustinthem,beforehanding
offthatcontroltoanabstractionandmovingtoahigherlevelofcontrol.
Theenvironmentmustsupportthisprocess.Atypicaltexteditoronlyprovidesdirectsupport

*Thecodetransformationsshowninthe

forgrowing"outward"addingnewlinesofcode.Theenvironmentmustalsosupport

aboveexampleshaveasuperficial
resemblanceto"refactoring",whichis

growing"upward"abstractingoverexistingcode.*

supportedbysomeenvironments.
However,thefeatureshavedifferent

Theenvironmentshouldencouragethelearnertostartconstant,thenvary,byproviding

intents.Refactoringisaboutwriting

meaningfulwaysofgraduallyandseamlesslytransitioningconstantexpressionsinto

workingbutpoorlyorganizedcode,then

variableexpressions.

cleaningitup.Createbyabstractingis

Theenvironmentshouldencouragethelearnertostartwithone,thenmakemany,by

generalizingit.

providingwaysofusingthosevariableexpressionsatahigherlevel,suchasfunction
applicationorlooping.

LANGUAGE
Aprogrammingsystemhastwoparts.Theenvironmentisinstalledonthecomputer,andthe
languageisinstalledintheprogrammer'shead.
Thedesignofthelanguageisjustascriticaltotheprogrammer'swayofthinkingasthedesign
oftheenvironment.Inthebestcases,theyarecodesignedandinseparable.Manyrecent
learningenvironmentsuseJavaScriptorProcessing,andforthesakeofcomparison,the
examplesinthisessayusedthemaswell.Butneitherisawelldesignedlanguageforlearning.
Fortunately,therearegiantshoulderstostandonhereprogrammingsystemsthatwere
carefullyandbeautifullydesignedaroundthewaypeoplethinkandlearn.Thissectionwillbriefly
offersomedesignprinciplesthathavebeendistilledfromthesegreatsystemsofthepast.

Greatworks

aboutwritingcodeforaspecificcase,then

Thecanonicalworkondesigningprogrammingsystemsforlearning,andperhapsthegreatest
bookeverwrittenonlearningingeneral,isSeymourPapert's"Mindstorms".
MindstormsonAmazon
MindstormsonGoogleBooks
MindstormsatPowell's

Designingalearningsystemwithoutasolidunderstandingoftheprinciplesinthisbookislike
designingamechanicalsystemwithoutunderstanding"thelever".Or"gravity".Ifyouare
readingthisessay(andI'mprettysureyouare!)thenyouneedtoread"Mindstorms".
Seriously.Imeanit.Ifyouaregoingtodesignanythingwhatsoeverrelatedtolearning,then
youliterallyneedtoread"Mindstorms".
Forfuck'ssake,read"Mindstorms".

Thissectionwillmakereferencetofourseminalprogrammingsystemsthatweredesignedfor
learning,andIstronglyrecommendstudyingeachofthem.

Studyinghistoricalsoftwarecanbe

challenging.Itcanbedifficulttopointtoan
accessiblereferencewhichexplainsa
system's"heart".Herearethebest
referencesIcanoffer:
Logo:weareveryfortunatetohave
SeymourPapert'sMindstormsandThe
Children'sMachine.
Smalltalk:IrecommendAlanKay'sEarly
HistoryofSmalltalkandperhapsDan
Ingalls'sDesignPrinciplesBehind
Smalltalk.
HyperCard:seethispresentationbyBill
Atkinson.
Rocky'sBootscanbeplayedonline,or
seethisbriefexplanation,butneitherisas
enlighteningasagoodanalysiswouldbe.

Tobeclear,I'mnotadvocatingusinganyofthesesystems,ineithertheirhistoricalormodern
incarnations.I'madvocatingunderstandingthem,andbuildingontheirinsights.

Identityandmetaphor
InLogo,theprogrammerdrawspicturesbydirectingthe"turtle",anonscreencharacter
whichleavesatrailasitmoves:

Watchjusttwominutesofthisvideothechildren,andthebeardyguytalking:

That'sSeymourPapertexplainingtheLogoturtle.Theturtleservesanumberofbrilliant
functions,butthemostimportantisthattheprogrammercanidentifywithit.Tofigureout
howtomaketheturtleperformanaction,theprogrammercanaskhowshewouldperform
thatactionherself,ifsheweretheturtle.
Forexample,tofigureouthowtodrawacircle,alearnerwillwalkaroundincirclesforabit,
andquicklyderivea"circleprocedure"oftakingastepforward,turningabit,takingastep
forward,turningabit.Afterteachingittoherself,thelearnercanthenteachittothe
computer.*Theturtleistheincomputerembodimentoftheprogrammerherself,a"self",like

*Here,thelearnerhasderivedand

theplayercharacterinavideogame,andtherebyallowsthelearnertotransferher

implementedthedifferentialequationfora

knowledgeofherownbodyintoknowledgeofprogramming.

circle,withoutknowingwhatadifferential

Everyprogramminglanguageismadeofmetaphors,butsomefitthemindbetterthanothers.

programisan"intuitiveanalogofthe

Standardimperativeprogrammingusesthemetaphorof"assigningtovariables",shufflingbits

differentialequation".

equationis.ToquotePapert,aLogo

betweenlittleboxes.UnliketheLogoturtle,thismetaphorwasnotdesignedtoresonatewith
howpeoplelearnandunderstanditsimplyevolvedasathinlayeroverthemetaphorsused
intheunderlyingmachinearchitecture,suchas"storingtomemory".*
Smalltalk,likeLogo,alsohasastrongresonantmetaphor,whichisthemessage.All

*AlanKayinTheEarlyHistoryof
Smalltalk:"Assignmentstatementseven
abstractonesexpressverylowlevel

computationinSmalltalkisrepresentedbyobjectssendingandrespondingtomessagesfrom

goals...Humanprogrammersaren'tTuring

otherobjects.Inordertoprogramthebehaviorofanobject,theprogrammercastsherself

machinesandthelesstheir

intotheroleofthatobject(totheextentofreferringtotheobjectas"self"!)andthinksof

programmingsystemsrequireTuring

herselfascarryingonaconversationwithotherobjects.Thisisapowerfulmetaphor,because
roleplayingandconversingarepowerfulinnatehumanfacilities.AswithLogo,tremendous
timeandthoughtwentintothecraftingandhoningofSmalltalk'smetaphors.
InHyperCard,theprogramisrepresentedasastackofcards,withtheprogrammerdrawing
objectsontoeachcard.Unlikeatypicalprogramminglanguage,wherean"object"isan
abstractetherealentityfloatinginsidethecomputer,everyobjectinHyperCardhasa
"physicalpresence"ithasalocationonaparticularcard,itcanbeseen,itcanbe
interactedwith.EveryobjectinHyperCardisa"realthing",andthisisapowerfulmetaphor
whichallowsprogrammerstoapplytheirintuitionandunderstandingofthephysicalworld.
Rocky'sBootsisstructuredasavideogame,withaplayercharacterthatcanbemoved
arounddirectly.Theplayernotonlycanpickupandmoveobjects,butalsoactsasapower
sourcealiterallypowerfulmetaphor.Everythingisvisibleandtangibleelectricityisnot
someabstractvoltagereading,butcanbeseendirectlyasorangefire,flowingthroughwires.
Thisbeautifulmetaphormakesittrivialtofollowtheflowandseethestate.
InProcessing,bycontrast,theprogrammerhasnoidentitywithinthesystem.Thereareno
strongmetaphorsthatallowtheprogrammertotranslateherexperiencesasapersoninto
programmingknowledge.Theprogrammercannotsolveaprogrammingproblemby
performingitintherealworld.
Processing'scoremetaphoristhe"painter'salgorithm"thecomputerplacesaseriesof
shapesonthescreen,likedrawingonpaper.Becausethismetaphorcarriesnocomputational
power(youcannotcomputebyfillinginpixels),allcomputationoccursoutsidetheboundsof
themetaphor.Inthisexampleofabouncingballanimation

machinetechniques,thebetter."

thesimulatedpropertiesoftheball(position,velocity)arenotassociatedwiththepicture
oftheballonscreen.Theyarecomputedandstoredabstractlyas"numbers"in"variables",
andtheballismerelyashadowthatiscastoffbythisetherealinternalrepresentation.The
ballcannotbepickedupandmoveditcannotbetoldhowtointeractwithotherobjects.Itis
nota"livingthing",andthesimulationcannotbeunderstoodorthoughtaboutinanyway
otherthan"numbersinvariables".Thisisaveryweakwayofthinking.*

Decomposition
Modularityisthehumanmind'sleveragainstcomplexity.Breakingdownacomplexthinginto
understandablechunksisessentialforunderstanding,perhapstheessenceofunderstanding.
Aprogramminglanguagemustencouragetheprogrammertodecomposetoapproacha
complexproblembybreakingitintosimplerproblems.Papertreferstothisasbreakingdown
aprograminto"mindsizebites".
Logousesthemetaphorof"teachingtheturtleanewword".Todrawafaceconsistingoffour
circles,wecanteachtheturtleasubprocedurefordrawingacircle,andthenapplythat
subprocedurefourtimes.Longandcarefulthoughtwasgiventotheprocessbywhicha
learnerdiscoverstheneedforsubprocedures,andthenfactorsalargeprocedureinto
subprocedures.
Smalltalkis,inessence,aphilosophyofdecompositionintheformofaprogramming

*Forexamplesofsystemswhereevery
onscreenobjectisalivingtangiblething,
seeEtoysorMorphic.

language.ThisisAlanKayinventingobjects:
BobBarton[said]"Thebasicprincipleofrecursivedesignistomakethepartshavethe
samepowerasthewhole."ForthefirsttimeIthoughtofthewholeastheentire
computer,andwonderedwhyanyonewouldwanttodivideitupintoweakerthings
calleddatastructuresandprocedures.Whynotdivideitupintolittlecomputers...Why
notthousandsofthem,eachsimulatingausefulstructure?
Smalltalk'skeyinsightwasthatacomplexcomputerprogramcouldbedecomposedinto
smallercomputers,called"objects".ProgramminginSmalltalkisalmostentirelyanexercise
indecompositionbreakingdownthoughtsintoclassesandmessages.
Almosteverycomputerlanguageprovidessomefacilityfordecomposition,butsomeare

Forthisanotherlanguagewhose

betterthanothers.InhiswonderfulessayWhyFunctionalProgrammingMatters,JohnHughes

extraordinarydecomposabilityisvaluable

arguesthatdecompositionliesattheheartofthepoweroflanguageslikeHaskell:

tostudyandunderstand.

Whenwritingamodularprogramtosolveaproblem,onefirstdividestheprobleminto
subproblems,thensolvesthesubproblems,andfinallycombinesthesolutions.Theways
inwhichonecandivideuptheoriginalproblemdependdirectlyonthewaysinwhich
onecangluesolutionstogether.Therefore,toincreaseone'sabilitytomodularizea
problemconceptually,onemustprovidenewkindsofglueintheprogramming
language.
Functionallanguagesprovidetwonew,veryimportantkindsofglue...Thisisthekeyto
functionalprogrammingspoweritallowsimprovedmodularization.
ProcessingallowsforLogostyledecompositionintosubprocedures,intheformoffunction

KhanAcademy'stutorialsdonotmention

definitions.ThemorepowerfulSmalltalkstyledecomposition,wheresubmodulescanbe

decompositionorfunctionsatall,andmany

thoughtaboutindependently,isnotsupported.InProcessing,drawingandinputeventsare

exampleprogramsarewrittenasonelong

tiedtosingleentrypointstoplevelfunctionssuchas"draw"and"mouseDown".The
behaviorofsubmodulesmustbetangledacrosstheseglobalfunctions.Cleandecompositionis
notpossible.
Consideraprogrammerwhohasmadeabouncingballanimation.Howdoesshegofromone
balltotwo,toahundred?Howdoesshemaketheballsbounceoffoneanother?Howdoesshe
makeballsdraggablewiththemouse?InagenuinelearningenvironmentsuchasEtoys,this
progressionisnaturalandencouraged.InProcessing,eachofthesestepsisanightmareof
needlesscomplexity.

listofinstructions.

Alanguagethatdiscouragesdecompositionisalanguagethatcripplesaprogrammer'smost
valuablewayofthinking.

Recomposition
Creatingisremixing.Toalargeextent,newideasareoldideasinnewcombinations.
Aprogramminglanguagemustencouragerecompositiongrabbingpartsofotherprograms,
assemblingthemtogether,modifyingthem,buildingontopofthem.Thisgivescreatorsthe
initialmaterialtheyneedtocreatebyreacting,insteadoffacingeverynewideawithablank
page.Italsoallowscreatorstolearnfromeachother,insteadofderivingtechniquesandstyle
inavacuum.
HyperCardwasdesignedforrecomposition,andisperhapsstillunsurpassedinthatrespect.
BillAtkinsonfullyintendedforcreatorstoassembleaprogrambycopyingandpastingobjects
fromotherprograms,andthengraduallytweakingandcustomizingthem.Everyprogramthus
servesasapartskitforcreatingnewprograms.Becauseallsourcecode,ifany,isembedded
inindividualobjectsintheformofscripts,andbecausescriptsuseloose,relativereferences
tootherobjects,groupsofrelatedobjectscanbetransplantedmuchmoreeasilyand
successfullythaninothersystems.*
ManypeoplerevereHyperCardforinitiatingthemintoprogramming.Anyusercanremixtheir

*HyperCardisseenbysomeas"whatthe
webshouldhavebeen".It'slamentable
thatacreatorcannot,andprobablycan

softwarewithcopyandpaste,therebysubtlytransitioningfromusertocreator,andoften

never,createawebsitebycopyingand

eventuallyfromcreatortoprogrammer.

pastinggraphicalobjectsfromother
websites.Thisisnotdueto"technological

Processing'slackofmodularityisamajorbarriertorecomposition.Theprogrammercannot

limitations"it'saconsequenceof

simplygrabafriend'sbouncingballandplaceitalongsideherownbouncingballvariables

thoughtlesssystemdesign.

mustberenamedormanuallyencapsulatedthe"draw"andmousefunctionsmustbewoven
together,andsoon.OnecaneasilystartfromanexistingProcessingprogramandmodifyit,
butthelanguagedoesnotencouragecombiningtwoprograms.
Worse,Processing'sdependenceonglobalstatehinderseventhesimplestformsof
recomposition.Asananalogy,imagineyou'rewritinganemail.Youcopysomeredtextfroma
website,pasteitintoyouremail,andeverythingelseinyouremailturnsred:

ThisisexactlywhatcanhappenwhencopyingandpastinglinesofProcessingcode,because
Processing'swayofhandlingcolorisinherentlyleaky:

Experiencedprogrammersmightlookatthisexampleandconsiderthisaprogrammer'serror,
becausethisis"justhowcodeworks."Butthiserrorisnotintrinsictoprogrammingit'sa

consequenceofspecificdesigndecisionsmutablestate,globalvariables,noencapsulation.
Worseyet,Processinghasglobalmodeswhichalterthemeaningoffunctionarguments.The
followinglineofcodesetsafillcolor.Doyouknowwhatcoloritis?

Trickquestionit'simpossibletoknowwhatcoloritis,becausethemeaningof"255"
dependsontheglobal"colormode".Itcouldbeanyofthesecolors:

IftwoProcessingprogramsspecifytheircolorsindifferentcolormodes,thencombiningthe
twoprogramsisalmosthopeless.
Designingasystemthatsupportsrecompositiondemandslongandcarefulthought,anddesign
decisionsthatmakeprogrammingmoreconvenientforindividualsmaybedetrimentalto
socialcreation.

Readability
Alearnermustbeabletolookatalineofcodeandknowwhatitmeans.
Syntaxmatters.HerearetwostatementsinHyperCard'sscriptinglanguage,andtheir
equivalentsinamoreconventionalsyntax:
HyperTalk: Write "hello" to file "greetings".
Clikesyntax: writeFile("hello", "greetings");

Drag from "0,0" to "100,100" with optionKey.


dragMouse(0, 0, 100, 100, OPTION_KEY);

HyperTalkhappenstouseanEnglishlikesyntax,butthat'snotthepointhere.Whatmattersis

SeealsoInform7.Englishlikelanguages

thateveryargumentcanbeunderstoodincontext.It'sclearthat"hello"isastringand

likethesearesometimesaccusedofbeing

"greetings"isafilename,andthat"0,0"and"100,100"arestartandendpoints.Inthe

difficulttowrite(sincethesyntaxismore

conventionalsyntax,bothareambiguous.

restrictivethanactualEnglish),butthat'sa
faultoftheenvironment.Programmers

Asanotherexample,here'showaprogrammermightdrawanellipseinthreelanguages:

shouldn'tbetypingthisstuff.

Smalltalk: canvas drawEllipseCenteredAtX:50 y:50 width:100 height:100.


Processing: ellipse(50,50,100,100);
x86assembly: push 100; push 100; push 50; push 50; call _ellipse
InSmalltalk,argumentshavecontext.Processing's"ellipse"isexactlyascrypticasassembly
language.Thereadermustlookupormemorizeeveryargument,asignificantbarrierto
reading.
Namesmatter.BelowarefourarraymethodsfromApple'sCocoaframework,andthe
equivalentJavaScriptmethods:
Cocoa: addObject addObjectsFromArray
JavaScript: push

splice

arrayByAddingObject

arrayByAddingObjectsFromArray

concat

concat

Cocoafollowsstronggrammaticalconventionswhichimmediatelyconveythemeaningsof

Toseetheamountofthoughtthatisput

methods.Verbphrases("addObject")performanactionandreturnnothing.Nounphrases

intoCocoanaming,Ihighlyrecommend

("arrayByAddingObject")returnthenounsonamed,andgenerallydonothavestatefuleffects

theCocoacodingguidelines.

unlessthenamesuggestsso.Expectedargumentsareclearlyindicatedbythename,in
Smalltalkstyle.("addObject"takesanobject"addObjectsFromArray"takesanarray.)Most
Cocoacodecanthusbereadandatleastvaguelyunderstoodwithoutdocumentation.
Bycontrast,manyofProcessing'sfunctionnamesaregrammaticallyambiguousormisleading.

*Processing's"fill"and"stroke"readas

Manynouns,suchas"ellipse"and"triangle",performactions.Manyverbs,suchas"fill"and

verbs,althoughit'spossibletheywere

"stroke",donot.*Theprogrammerconstructsacolorusinganoun("color"),andconstructs

intendedasshorthandstonouns("fillcolor"

animageusingaverb("createImage").Thissortoflinguisticsloppinessisinappropriate,
especiallyinasystemforlearning.Alanguagemustbeparsedbypeople,notjustcompilers.

and"strokecolor").Inmostotherlibraries
(HTMLcanvas,Quartz,cairo),"fill"and
"stroke"areunambiguouslyverbs,andact
accordingly.

OKAY THEN!
Thedesignprinciplespresentedinthisessaycanbeusedasachecklisttoevaluatea
programmingsystemforlearning.
Doestheenvironmentallowthelearnerto...
readthevocabulary?Ismeaningtransparent?Ismeaningexplainedincontext,byshowingandtelling?
followtheflow?Istimevisibleandtangible?Atallmeaningfulgranularities?
seethestate?Doestheenvironmentshowthedata?Showcomparisons?Ishiddenstateeliminated?
createbyreacting?Issomethingonscreenassoonaspossible?Isthepartsbucketonthefloor?
createbyabstracting?Cantheprogrammerstartconcrete,thengeneralize?
Doesthelanguageprovide...
identityandmetaphor?Isthecomputer'sworldconnectedtotheprogrammer'sworld?
decomposition?Cantheprogrammerbreakdownherthoughtsintomindsizedpieces?
recomposition?Cantheprogrammerputdiversepiecestogether?
readability?Ismeaningtransparent?
Thisessaysuggestedsomefeaturesandreferencesthataddressthesequestions,butthe
questionsmattermorethanmyanswers.
Ifyouaredesigningasystemandyoucan'tanswerthesequestions,it'stimetoreopenyour

Somepeoplewilldefendpoorlydesigned

sketchbook,becauseyourdesign'snotdoneyet.

systemsbypointingoutallthecreativity
thattheyhaveenabled.Forexample,if
novicesarecreatinglotsofprogramsinthe

Thesearenottrainingwheels

KhanAcademyandProcessingsystems,
doesn'tthatmeanthesystemsare
worthwhileandvaluable?

Thesedesignprincipleswerepresentedinthecontextofsystemsforlearning,buttheyapply

Notnecessarily.Peopleareinherently

universally.Anexperiencedprogrammermaynotneedtoknowwhatan"if"statementmeans,

creative,andsomewillmanagetocreate

butshedoesneedtounderstandtheruntimebehaviorofherprogram,andsheneedsto

ineventhemosthostileofenvironments.

understanditwhileshe'sprogramming.

Thatdoesn'tjustifybaddesign.IanBogost

Afrequentquestionaboutthesortoftechniquespresentedhereis,"Howdoesthisscaleto

thatlineofthinking.

hasaparticularlymemorableresponseto

realworldprogramming?"Thisisareasonablequestion,butit'ssomewhatlikeaskinghow
theinternalcombustionenginewillbenefithorses.Thequestionassumesthewrongkindof
change.
Hereisamoreusefulattitude:Programminghastoworklikethis.Programmersmustbe
abletoreadthevocabulary,followtheflow,andseethestate.Programmershavetocreate
byreactingandcreatebyabstracting.Assumethatthesearerequirements.Giventhese
requirements,howdoweredesignprogramming?
Here'sanexample.Inmanystylesofprogrammingtoday,whenanapplicationlaunches,it
createsalargesetofinterconnectedstatefulobjects.Toseetheeffectofacodechange,the
applicationmustbe"relaunched"thatis,itsentireworldisdestroyed,andrebuiltagain
fromscratch.Howcanwe"createbyreacting",continuouslychangingthecodeandseeing
continuouseffectsintheflowanddata,whenthereisnocontinuitybetweentheapplication's
statebeforeandafterthechange?
Wecan't.That'sthewrongquestion.Abetterquestionis:Howdowedesignanew

*IntheSmalltalkmodel,forinstance,

programmingmodelthatdoesallowforcontinuouschange?Wealreadyhaveclearhints.*

stateispersistentandcodechangesdon't
affectdata.IntheClojuremodel,codeis

Anotherexample.Mostprogramstodaymanipulateabstractdatastructuresandopaque

"mostlyfunctional",withasmallamountof

objects,notpictures.Howcanwevisualizethestateoftheseprograms?

carefullymanagedstate.Eithermodel
couldbeastartingpointforasystem

Again,wrongquestion.Abetterattitudeistoassertthatwehavetobeabletounderstandthe

wherecontinuouscodechangescanbe

stateofourprograms.Wecanthenask:Howdowedesigndatastructuresthatcanbe

seenascontinuouseffects.Butthereisno

visualized?Canweinventdatastructuresthatareintendedtobevisualized?Howdowemove

futureindestroytheworldprogramming.

towardsaculturewhereonlyvisuallyunderstandabledataisconsideredsound?Whereopaque
dataisregardedinthesamewaythat"goto"istoday?*
InhisinfluentalessayNoSilverBullet,FredBrooksmakesthecasethatsoftwareisinherently

*Forwardreference:SomeworkthatI've
doneinautomaticvisualizationofadhoc
datastructureswillbepublishedlaterthis

"invisibleandunvisualizable",andpointsouttheuniversalfailureofsocalled"visual

year,incollaborationwithViewpoints

programming"environments.Idon'tfaultFredBrooksforhismistakethevisual

Research.

programmingthathe'sthinkingofindeedhaslittletooffer.Butthat'sbecauseitvisualizesthe
wrongthing.
Traditionalvisualenvironmentsvisualizethecode.Theyvisualizestaticstructure.Butthat's

notwhatweneedtounderstand.Weneedtounderstandwhatthecodeisdoing.
Visualizedata,notcode.Dynamicbehavior,notstaticstructure.
Maybewedon'tneedasilverbullet.Wejustneedtotakeoffourblindfoldstoseewherewe'refiring.

MuchthankstoStarSimpson,DanAmelang,DaveCerf,PatrickCollison,
ChristinaCacioppo,andOliverSteelefortheirfeedbackonthisessay.
Thisessaywasanimmuneresponse,triggeredbyhearingtoomanytimesthat
InventingonPrinciplewas"aboutlivecoding",andseeingtoomanyattemptsto
"teachprogramming"byadorningaJavaScripteditorwithbadgesandmascots.
PleasereadMindstorms.Okay?

You might also like