Not a programmer, but I think one other reason for this is that at least in certain languages (I think interpreted languages, e.g. Python, is the relevant category here), you have to define a term before you can use it; the interpreter basically executes the code top-down instead of compiling it first, so it can’t just look later in the file to figure out what you mean. So
The goal of the file is to export a makeFreshPasta function. It’s ok that the makeFreshPasta function uses functions like makeDough that are defined below it because of how closures work. Basically, the function body of makeFreshPasta will always have access to anything that was in scope at the time makeFreshPasta was defined.
I’m not sure about other languages, but I’m sure there are other solutions available for writing code that follows the top-down style.
So that is my response to the practical question of how to write code that is top-down. But I am also making a point about how I think things should be. So even if it weren’t possible to write this sort of top-down code, my prescriptive point of “this is how it should be possible to write the code” still stands.
Not a programmer, but I think one other reason for this is that at least in certain languages (I think interpreted languages, e.g. Python, is the relevant category here), you have to define a term before you can use it; the interpreter basically executes the code top-down instead of compiling it first, so it can’t just look later in the file to figure out what you mean. So
wouldn’t work, because you’re calling putToothpasteOnToothbrush() before you’ve defined it.
Yeah sometimes that is a problem for sure. In various situations it’s not a problem though. There’s a thing called hoisting where if you have:
sayHi
will be moved to the top of the file abovesayHi("Adam")
when the code is executed, even though it is written below it.The other way I know of that this dilemma is solved is closures. Imagine that we had a
makeFreshPasta.js
file with this:The goal of the file is to export a
makeFreshPasta
function. It’s ok that themakeFreshPasta
function uses functions likemakeDough
that are defined below it because of how closures work. Basically, the function body ofmakeFreshPasta
will always have access to anything that was in scope at the timemakeFreshPasta
was defined.I’m not sure about other languages, but I’m sure there are other solutions available for writing code that follows the top-down style.
So that is my response to the practical question of how to write code that is top-down. But I am also making a point about how I think things should be. So even if it weren’t possible to write this sort of top-down code, my prescriptive point of “this is how it should be possible to write the code” still stands.
Cool, thanks!
Sure thing!