Skip to content

Instantly share code, notes, and snippets.

@sbaldwin24
Last active August 29, 2015 14:06
Show Gist options
  • Save sbaldwin24/1233bf3d917cf6d770a2 to your computer and use it in GitHub Desktop.
Save sbaldwin24/1233bf3d917cf6d770a2 to your computer and use it in GitHub Desktop.
Imperative programming
Imperative programming
An imperative programming style is categorized by its exquisite (and often infuriating)
attention to the details of algorithm implementation. Further, imperative programs are
often built around the direct manipulation and inspection of program state. For exam‐
ple, imagine that you’d like to write a program to build a lyric sheet for the song “99
Bottles of Beer.” The most direct way to describe the requirements of this program are
as such:
• Start at 99
• Sing the following for each number down to 1:
— X bottles of beer on the wall
— X bottles of beer
— Take one down, pass it around
— X-1 bottles of beer on the wall
• Subtract one from the last number and start over with the new value
• When you finally get to the number 1, sing the following last line instead:
— No more bottles of beer on the wall
As it turns out, this specification has a fairly straightforward imperative implementation
in JavaScript, as shown here:
var lyrics = [];
for (var bottles = 99; bottles > 0; bottles--) {
lyrics.push(bottles + " bottles of beer on the wall");
lyrics.push(bottles + " bottles of beer");
lyrics.push("Take one down, pass it around");
if (bottles > 1) {
lyrics.push((bottles - 1) + " bottles of beer on the wall.");
}
else {
lyrics.push("No more bottles of beer on the wall!");
}
}
This imperative version, while somewhat contrived, is emblematic of an imperative
programming style. That is, the implementation describes a “99 Bottles of Beer” pro‐
gram and exactly a “99 Bottles of Beer” program. Because imperative code operates at
such a precise level of detail, they are often one-shot implementations or at best, difficult
to reuse. Further, imperative languages are often restricted to a level of detail that is good
for their compilers rather than for their programmers (Sokolowski 1991).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment