Programming Search⌘K

Conceptcore

Procedural programming

Also called procedural style, procedures, subroutines, top-down design, stepwise refinement, functional decomposition.

Procedural programming organizes an imperative program as named procedures that take parameters and return results, and divides a task into steps until each step is simple.

Applies to
core-languages

Idea

Procedural programming organizes an imperative program as a set of procedures. A procedure is a named block of statements that takes parameters, may return a result, and can be called from other code. The programmer divides a large task into steps, writes each step as a procedure, and divides the steps again until each one is simple. The main program then reads as a short list of calls:

def read_scores(lines):
    return [int(x) for x in lines if x.strip()]


def mean(xs):
    return sum(xs) / len(xs)


def grade(score):
    if score >= 90:
        return "A"
    if score >= 75:
        return "B"
    return "C"


def print_report(scores):
    print(f"mean {mean(scores):.1f}")
    for s in scores:
        print(s, grade(s))


print_report(read_scores(["91", "78", "", "64"]))
Output
mean 77.7
91 A
78 B
64 C

Each procedure has one task and a name that says what the task is. print_report does not know how a grade is computed, and grade does not know where the scores came from. A change to the grading rule touches one procedure.

How it works

Procedures as abstraction. A call to a procedure hides its statements behind a name and a list of parameters. The caller depends only on what the procedure does, not on how. cppreference describes a C function as a construct "that associates a compound statement (the function body) with an identifier (the function name)".1 The same procedure can be called from many places, so a fix in one place fixes all the callers.

The call stack. Each call gets a new frame on the stack, with its parameters, its local variables and the address to return to. The frame disappears when the procedure returns. This is what lets a procedure call itself, and what keeps the local variables of one call apart from those of another. See the stack and the heap and recursion.

Local and global state. Variables declared inside a procedure are local to one call. Variables declared outside are global and shared by all procedures. Global state is easy to use and hard to reason about, because any procedure can change it. Languages make writes to it visible. The Python tutorial explains that a function cannot assign to a global variable unless the variable is "named in a global statement".2 The good procedural style passes data through parameters and return values and keeps global state small.

Top-down decomposition. The usual method of design is stepwise refinement: write the top-level procedure in terms of steps that do not exist yet, then write each step in the same way. Niklaus Wirth described the method in 1971, and it became the standard way to teach programming in Pascal. The result is a tree of procedures in which each level is a more detailed version of the level above.

Short procedures. Procedural style guides limit the size of a procedure. The Linux kernel coding style says that "Functions should be short and sweet, and do just one thing."3 It also limits local variables: "They shouldn't exceed 5-10, or you're doing something wrong. Re-think the function, and split it into smaller pieces."3

Modules. As programs grow, procedures are grouped into modules, such as C source files with a header, Pascal units or Go packages. A module exports some procedures and keeps others private. David Parnas showed in 1972 that the choice of what goes into a module matters. A decomposition that makes "each major step in the processing a module" follows the flowchart,4 and a change to a data format then touches many modules. A decomposition in which each module hides "a design decision" from the others keeps such changes local.4

In languages

LanguageVerdictNote
PythonNative
C++Native
JavaIdiom
CNative
C#Idiom
JavaScriptNative
TypeScriptNativeAs JavaScript, with typed function signatures and modules.
GoNative
RustNative
KotlinNativeTop-level functions in files and packages need no class; no example file because kotlinc is not installed on the machine that recorded the examples.
SQLIdiomStored procedures in procedural extensions such as PL/pgSQL and T-SQL group statements under a name; standard queries have no procedures.
BashNative
PowerShellNativeFunctions with param blocks, script files and modules; no example file because pwsh is not installed on the machine that recorded the examples.
HTMLDoes not applyHTML has no procedures.
CSSDoes not applyCSS has no procedures.
Regular expressionsDoes not applyA regular expression has no procedures.
Language Verdict Mechanism
Python native def at module level, modules as files, global for writes to shared state
JavaScript native function declarations, ES modules
TypeScript native as JavaScript, with typed signatures
Java idiom static methods in a class; no free functions
Kotlin native top-level functions in packages
C# idiom static methods and classes, local functions in top-level code
Go native package-level functions, export by capital letter
Rust native free functions in modules, pub
C native functions, headers, static for file scope
C++ native free functions, namespaces, overloading
Bash native shell functions, local
PowerShell native functions with param blocks, modules
SQL idiom stored procedures in procedural extensions
Regex, HTML, CSS n/a no procedures

C, Go, Rust, Python and C++ let a program consist of free functions with no classes. In C, the procedure is the main unit of design. A source file is a module, static makes a function private to its file, and a header declares the functions that other files may call. Go follows the same plan with packages, and a name that starts with a capital letter is exported. Rust uses modules and pub.

Java and C# require every method to be in a class. A procedural design there uses classes that have only static methods, such as java.lang.Math, and C# adds static classes and local functions. The procedural style is still common inside methods, which are often written as a sequence of steps.

Bash and PowerShell functions are procedures too, but their parameters and results are different. A Bash function takes its arguments as strings in $1, $2 and so on, writes its result to standard output, and returns a status code.

PythonGitHub
def split_words(text):
    return text.lower().split()


def count_words(words):
    counts = {}
    for w in words:
        counts[w] = counts.get(w, 0) + 1
    return counts


def top(counts, n):
    return sorted(counts.items(), key=lambda kv: (-kv[1], kv[0]))[:n]


def report(text, n):
    for word, c in top(count_words(split_words(text)), n):
        print(f"{word:5} {c}")


report("The cat and the hat and the bat", 2)
Output
the   3
and   2

This code runs but gives a wrong answer on purpose.

total = 0


def add_all(xs):
    global total
    for x in xs:
        total += x
    return total


print(add_all([1, 2, 3]))
print(add_all([1, 2, 3]))
Output
6
12
  • Verdict: native. def defines a function, and a module groups functions in a file. A function can be called before it is defined in the text, as long as the definition has run before the call.
  • The tutorial explains that a function cannot assign to a global variable unless the variable is "named in a global statement". The rule makes writes to shared state visible in the code.
  • In the wrong block, add_all keeps its sum in a global variable, so two calls with the same argument return different results. Use a local variable and return it.
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <map>
#include <sstream>
#include <string>
#include <utility>
#include <vector>

namespace words {

std::vector<std::string> split(const std::string& text) {
    std::istringstream in(text);
    std::vector<std::string> out;
    for (std::string w; in >> w;) {
        std::transform(w.begin(), w.end(), w.begin(), [](unsigned char c) { return std::tolower(c); });
        out.push_back(w);
    }
    return out;
}

std::map<std::string, int> count(const std::vector<std::string>& ws) {
    std::map<std::string, int> counts;
    for (const auto& w : ws) ++counts[w];
    return counts;
}

std::vector<std::pair<std::string, int>> top(const std::map<std::string, int>& counts, std::size_t n) {
    std::vector<std::pair<std::string, int>> all(counts.begin(), counts.end());
    std::stable_sort(all.begin(), all.end(), [](const auto& a, const auto& b) { return a.second > b.second; });
    all.resize(std::min(n, all.size()));
    return all;
}

}  // namespace words

int main() {
    for (const auto& [w, c] : words::top(words::count(words::split("The cat and the hat and the bat")), 2)) {
        std::cout << std::left << std::setw(5) << w << " " << c << "\n";
    }
}
Output
the   3
and   2
  • Verdict: native. C++ keeps the free functions of C and adds namespaces, overloading and references, so a procedural design can be written with no classes.
JavaGitHub
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    static String[] splitWords(String text) {
        return text.toLowerCase().split("\\s+");
    }

    static Map<String, Integer> countWords(String[] words) {
        Map<String, Integer> counts = new TreeMap<>();
        for (String w : words) {
            counts.merge(w, 1, Integer::sum);
        }
        return counts;
    }

    static List<Map.Entry<String, Integer>> top(Map<String, Integer> counts, int n) {
        List<Map.Entry<String, Integer>> entries = new ArrayList<>(counts.entrySet());
        entries.sort((a, b) -> b.getValue() - a.getValue());
        return entries.subList(0, n);
    }

    static void report(String text, int n) {
        for (var e : top(countWords(splitWords(text)), n)) {
            System.out.println(String.format("%-5s %d", e.getKey(), e.getValue()));
        }
    }

    public static void main(String[] args) {
        report("The cat and the hat and the bat", 2);
    }
}
Output
the   3
and   2
  • Verdict: idiom. Java has no free functions. A class with only static methods acts as a module of procedures, as java.lang.Math does.
#include <ctype.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

struct count {
    char word[16];
    int n;
};

static int split_words(char *text, char *words[], int max)
{
    int n = 0;
    for (char *p = text; *p; p++)
        *p = (char)tolower((unsigned char)*p);
    for (char *w = strtok(text, " "); w && n < max; w = strtok(NULL, " "))
        words[n++] = w;
    return n;
}

static int count_words(char *words[], int nwords, struct count out[])
{
    int n = 0;
    for (int i = 0; i < nwords; i++) {
        int j = 0;
        while (j < n && strcmp(out[j].word, words[i]) != 0)
            j++;
        if (j == n) {
            snprintf(out[n].word, sizeof out[n].word, "%s", words[i]);
            out[n++].n = 0;
        }
        out[j].n++;
    }
    return n;
}

static int by_count(const void *a, const void *b)
{
    const struct count *x = a, *y = b;
    if (x->n != y->n)
        return y->n - x->n;
    return strcmp(x->word, y->word);
}

static void report(const char *text, int top)
{
    char buf[256];
    char *words[64];
    struct count counts[64];

    snprintf(buf, sizeof buf, "%s", text);
    int nwords = split_words(buf, words, 64);
    int n = count_words(words, nwords, counts);
    qsort(counts, (size_t)n, sizeof counts[0], by_count);
    for (int i = 0; i < top && i < n; i++)
        printf("%-5s %d\n", counts[i].word, counts[i].n);
}

int main(void)
{
    report("The cat and the hat and the bat", 2);
    return 0;
}
Output
the   3
and   2
  • Verdict: native. C is the standard procedural language. A program is a set of functions, and cppreference describes a function as a construct "that associates a compound statement (the function body) with an identifier (the function name)".
  • static at file level makes a function private to its source file. A header file declares the functions that other files may call.
Report("The cat and the hat and the bat", 2);

static string[] SplitWords(string text) =>
    text.ToLowerInvariant().Split(' ', StringSplitOptions.RemoveEmptyEntries);

static Dictionary<string, int> CountWords(string[] words)
{
    var counts = new Dictionary<string, int>();
    foreach (var w in words)
    {
        counts[w] = counts.GetValueOrDefault(w) + 1;
    }
    return counts;
}

static IEnumerable<KeyValuePair<string, int>> Top(Dictionary<string, int> counts, int n) =>
    counts.OrderByDescending(kv => kv.Value).ThenBy(kv => kv.Key).Take(n);

static void Report(string text, int n)
{
    foreach (var (word, c) in Top(CountWords(SplitWords(text)), n))
    {
        Console.WriteLine($"{word,-5} {c}");
    }
}
Output
the   3
and   2
  • Verdict: idiom. Methods belong to classes, but a file with top-level statements can declare local functions, as here, and a static class holds procedures that do not need an object.
JavaScriptGitHub
function splitWords(text) {
  return text.toLowerCase().split(/\s+/);
}

function countWords(words) {
  const counts = new Map();
  for (const w of words) counts.set(w, (counts.get(w) ?? 0) + 1);
  return counts;
}

function top(counts, n) {
  return [...counts].sort((a, b) => b[1] - a[1] || a[0].localeCompare(b[0])).slice(0, n);
}

function report(text, n) {
  for (const [word, c] of top(countWords(splitWords(text)), n)) {
    console.log(`${word.padEnd(5)} ${c}`);
  }
}

report("The cat and the hat and the bat", 2);
Output
the   3
and   2
  • Verdict: native. A function declaration is hoisted, so it can be called from code above it in the same scope. Modules with import and export group functions in files.
package main

import (
	"fmt"
	"sort"
	"strings"
)

type wordCount struct {
	word string
	n    int
}

func splitWords(text string) []string {
	return strings.Fields(strings.ToLower(text))
}

func countWords(words []string) map[string]int {
	counts := map[string]int{}
	for _, w := range words {
		counts[w]++
	}
	return counts
}

func top(counts map[string]int, n int) []wordCount {
	var all []wordCount
	for w, c := range counts {
		all = append(all, wordCount{w, c})
	}
	sort.Slice(all, func(i, j int) bool {
		if all[i].n != all[j].n {
			return all[i].n > all[j].n
		}
		return all[i].word < all[j].word
	})
	return all[:n]
}

func report(text string, n int) {
	for _, wc := range top(countWords(splitWords(text)), n) {
		fmt.Printf("%-5s %d\n", wc.word, wc.n)
	}
}

func main() {
	report("The cat and the hat and the bat", 2)
}
Output
the   3
and   2
  • Verdict: native. Go programs are mostly package-level functions and types. A name that starts with a capital letter is exported from its package, and other names are private to it.
RustGitHub
use std::collections::HashMap;

fn split_words(text: &str) -> Vec<String> {
    text.split_whitespace().map(|w| w.to_lowercase()).collect()
}

fn count_words(words: &[String]) -> HashMap<&str, usize> {
    let mut counts = HashMap::new();
    for w in words {
        *counts.entry(w.as_str()).or_insert(0) += 1;
    }
    counts
}

fn top<'a>(counts: &HashMap<&'a str, usize>, n: usize) -> Vec<(&'a str, usize)> {
    let mut all: Vec<_> = counts.iter().map(|(w, c)| (*w, *c)).collect();
    all.sort_by(|a, b| b.1.cmp(&a.1).then(a.0.cmp(b.0)));
    all.truncate(n);
    all
}

fn report(text: &str, n: usize) {
    let words = split_words(text);
    for (word, c) in top(&count_words(&words), n) {
        println!("{word:<5} {c}");
    }
}

fn main() {
    report("The cat and the hat and the bat", 2);
}
Output
the   3
and   2
  • Verdict: native. Free functions in modules are the base of a Rust program, and pub marks the ones that other modules can call. The signatures show which arguments a function borrows and which it may change.
BashGitHub
split_words() {
    tr 'A-Z' 'a-z' <<< "$1" | tr ' ' '\n'
}

count_words() {
    sort | uniq -c | sort -k1,1nr -k2,2
}

report() {
    local text=$1 n=$2
    split_words "$text" | count_words | head -n "$n" |
        while read -r c w; do printf '%-5s %d\n' "$w" "$c"; done
}

report "The cat and the hat and the bat" 2
Output
the   3
and   2
  • Verdict: native. Shell functions take arguments as $1, $2 and so on, and return text on standard output and a status code. Variables are global unless the function declares them local.
  • Functions and procedures. Some languages separate procedures, which act, from functions, which return a value. Pascal and Ada have both, and in C a procedure is a function that returns void.
  • Structured programming. Procedures are one of the structured forms, with one entry and one exit. See structured programming.
  • Modular programming. Procedures grouped behind an interface, with private data. Modula-2 and Ada made modules part of the language.
  • Object-oriented programming. Procedures move into the data types that they work on and become methods. See object-oriented programming.
  • Functional programming. Functions with no side effects, so that the order of calls does not matter. See functional programming.
  • Coroutines. Procedures that can suspend and resume, rather than run to the end on each call.

Pitfalls

  • Global state. Procedures that read and write global variables depend on the order in which they are called, and cannot be tested alone. Pass the state as parameters.
  • Long procedures. A procedure of hundreds of lines does many things, has many local variables, and is hard to test. Split it into named steps.
  • Long parameter lists. A procedure with many parameters is easy to call with the arguments in the wrong order. Group related parameters into a structure.
  • Output parameters. Procedures that return results through pointer or reference parameters hide which arguments change. Prefer return values, and return a structure or a tuple when there is more than one result.
  • Decomposition by steps only. Dividing a program by the steps of the flowchart spreads knowledge of each data format across many procedures. Group the procedures that know a format into one module.
  • Data and code apart. When many procedures work on the same structure, each one must keep its invariants. A procedure that forgets breaks the others.

Cost

A procedure call costs a few instructions: the arguments go into registers or onto the stack, the processor saves the return address and jumps, and the procedure may save registers and set up a frame. Compilers inline small procedures, so a short procedure usually costs nothing when the compiler can see its body. Calls across module or library boundaries are harder to inline, and link-time optimization recovers some of them. Deep chains of calls use stack space, and each thread has a fixed amount.

History

Subroutines are older than high-level languages. The programmers of EDSAC in Cambridge used a library of subroutines in 1949, and David Wheeler devised the method of jumping to a subroutine and back that is now called the Wheeler jump. Fortran II added SUBROUTINE and FUNCTION in 1958. ALGOL 60 added procedures with local variables, recursion and parameters by name, and Pascal and C made the procedure the main unit of design in the 1970s. Wirth's stepwise refinement in 1971 and Parnas's criteria for modules in 1972 set the methods of procedural design,4 and the Linux kernel, written in C, remains one of the largest procedural programs in use.3

References

  1. Functions, C reference, cppreference.com, introduction
  2. The Python Tutorial, 4. More Control Flow Tools, Python 3.14 documentation, 4.8 Defining Functions
  3. Linux kernel coding style, 6) Functions
  4. On the Criteria To Be Used in Decomposing Systems into Modules, D. L. Parnas, Communications of the ACM 15(12), 1972, The Criteria

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW4 complete
  • a review of the text: no review record reviews/7D9E78/text.yaml