Notes Tutorials

Abstraction and naming

Abstraction hides details so you can think about one thing at a time; names are how you point at what's hidden. What a good abstraction looks like, how names carry meaning, the conventions in Python, JavaScript, Go and PHP, and what happens when an abstraction leaks.

8 min readAlso available in Bahasa Indonesia →

In part 0 abstraction was the third move of programming: giving a piece of work a name and using it as a unit. Since then we’ve used it constantly. Functions in part 7, the helpers in part 9, even sort() in part 10. This part looks at abstraction directly, and at its everyday partner: naming. One hides the details; the other is how you point at what’s hidden.

What abstraction is

Wikipedia puts it in one line: “In software, an abstraction provides access while hiding details that otherwise might make access more challenging. It focuses attention on details of greater importance.” Joel Spolsky describes it as “a simplification of something much more complicated that is going on under the covers.”

You use abstractions all day without thinking about them. print("hi") hides the operating system, the terminal, and the character encoding from part 2. A file name hides which blocks on the disk hold the data. A database query hides how the rows are found. Each one lets you think about what you want instead of how it happens.

The black box

Structure and Interpretation of Computer Programs explains this with a tiny function, square. Once it exists, you can treat square as a black box, which the book calls a procedural abstraction. The key sentence: “A user should not need to know how the procedure is implemented in order to use it.”

That’s the deal a good abstraction makes. On the outside: a name, the inputs, the output, and a promise about what it does. On the inside: anything, as long as the promise holds. The inside can be rewritten, made faster, or fixed, and nobody using it needs to change.

That’s also why the name carries so much weight. When the inside is hidden, the name, the parameters, and maybe a one-line docstring are all the reader gets.

Same logic, two versions

Here’s a function that works, and is correct:

def calc(d, t):
    r = []
    for x in d:
        if x[3] == 1 and t - x[2] > 2592000:
            r.append(x[0])
    return r

What does it do? You can work it out, but only by reading every line and guessing what x[3], 1, and 2592000 mean. Here is the same logic with names doing the work:

SECONDS_PER_DAY = 86_400
OVERDUE_AFTER_DAYS = 30
UNPAID = 1

def overdue_invoice_ids(invoices, now):
    """IDs of unpaid invoices issued more than 30 days before `now` (Unix seconds)."""
    limit = OVERDUE_AFTER_DAYS * SECONDS_PER_DAY
    return [
        inv_id
        for inv_id, customer, issued_at, status in invoices
        if status == UNPAID and now - issued_at > limit
    ]

Run both on the same three invoices (40 days old and unpaid, 10 days old and unpaid, 45 days old but paid):

['INV-1']
['INV-1']

Same result. The computer doesn’t care about names. People do. The second version tells you what it’s for before you read the body, and the call site reads like a sentence: overdue_invoice_ids(invoices, now).

2592000 in the first version is what’s called a magic number: “a numeric literal in source code whose meaning is unclear to the reader.” Giving it a name (OVERDUE_AFTER_DAYS * SECONDS_PER_DAY) also gives you one place to change it when the business decides that 45 days is the new limit.

The same function in PHP:

const SECONDS_PER_DAY = 86_400;
const OVERDUE_AFTER_DAYS = 30;
const UNPAID = 1;

function overdueInvoiceIds(array $invoices, int $now): array {
    $limit = OVERDUE_AFTER_DAYS * SECONDS_PER_DAY;
    $ids = [];
    foreach ($invoices as [$id, $customer, $issuedAt, $status]) {
        if ($status === UNPAID && $now - $issuedAt > $limit) {
            $ids[] = $id;
        }
    }
    return $ids;
}
// → ["INV-1"]

Why naming is hard

There’s an old line, usually credited to Phil Karlton: “There are only two hard things in Computer Science: cache invalidation and naming things.” It’s a joke, but the naming half is real. A good name requires you to know exactly what the thing is. When you can’t name a function, it’s often a sign that it does two things, or that you don’t yet understand what it’s for. That’s the same test as the “one sentence, no and” rule from part 9.

It matters because, as PEP 8 puts it, “code is read much more often than it is written.”

Habits that make names work

  • Say what it is, not how it’s stored. customers, not list1 or arr. price_by_product, not dict2.
  • Put the unit in the name when there is one. timeout_seconds, weight_kg, amount_rupiah. Many expensive bugs come from mixing milliseconds and seconds.
  • Booleans read as yes/no questions. is_paid, has_stock, can_edit. Then if is_paid: reads naturally.
  • Functions are actions or questions. send_invoice(), parse_order(), is_overdue(). A function named data() or process() tells you nothing.
  • Length should match scope. i is fine for a three-line loop. A value used across a whole file deserves a full name.
  • One word per idea. If it’s customer in one place, don’t call it client in the next and user in the third, unless they really are different things.
  • Avoid names that look alike. PEP 8 says: “Never use the characters ‘l’ (lowercase letter el), ‘O’ (uppercase letter oh), or ‘I’ (uppercase letter eye) as single character variable names.”
  • Rename when the meaning changes. A variable called total that now holds the total minus discounts is a trap for the next reader. Editors can rename safely; use that.

Each language has its own conventions

The habits above apply everywhere. The spelling of names depends on the language, and following the local convention is part of writing readable code:

Variables & functions Types / classes Constants
Python (PEP 8) snake_case CapWords UPPER_CASE
JavaScript (common practice) camelCase PascalCase UPPER_CASE or camelCase
Go (Effective Go) mixedCaps MixedCaps MixedCaps / mixedCaps
PHP (PSR-1) methods camelCase StudlyCaps class constants UPPER_CASE

The sources say it directly. PEP 8: “Function names should be lowercase, with words separated by underscores as necessary to improve readability.” Effective Go: “the convention in Go is to use MixedCaps or mixedCaps rather than underscores to write multiword names.” PSR-1: “Class names MUST be declared in StudlyCaps” and “Method names MUST be declared in camelCase.”

Go goes one step further: the name is the access control. In Go, “the visibility of a name outside a package is determined by whether its first character is upper case.” So a lowercase field is hidden behind the package’s abstraction:

package billing

type Invoice struct {
	ID     string // visible outside the package
	status int    // hidden
}

func (i Invoice) Status() int { return i.status }

Trying to read inv.status from another package doesn’t compile:

./main.go:11:18: inv.status undefined (type billing.Invoice has no field or method status, but does have method Status)

Note the method is Status(), not GetStatus(): Effective Go says “it’s neither idiomatic nor necessary to put Get into the getter’s name.” Small details like that are how code starts to look like it belongs in its language.

When abstractions leak

Spolsky named the catch: “All non-trivial abstractions, to some degree, are leaky.” The hidden details sometimes break through, and then you need to know what’s underneath.

We’ve already met a few leaks in this series:

  • Numbers. A decimal number in code looks exact, but 0.1 + 0.2 prints 0.30000000000000004, because of the binary representation from part 2.
  • Dictionaries. The O(1) lookup from part 10 is an average that assumes few hash collisions.
  • Databases. A helper like customer_name(customer_id) hides a query. It looks harmless, until you call it in a loop:
names = [customer_name(cid) for cid in order_customer_ids]   # 500 orders
one call per order: 500 queries
one query for all: 1 query

Counting the queries with SQLite’s trace callback makes the leak visible: the clean-looking line ran 500 queries, where one WHERE id IN (...) query did the same job. This is the “query inside a loop” shape from part 10, hidden behind a nice name.

Leaks don’t mean abstractions are bad. They mean the fundamentals still matter: you can use an abstraction without knowing its insides, but when it misbehaves, the insides are where the answer is.

Too much abstraction

The opposite mistake is also common: hiding things that didn’t need hiding.

  • A wrapper that only renames. def get_user(id): return fetch_user(id) adds a layer and a name to learn, and hides nothing.
  • Abstracting from one example. A “generic report engine” built for one report usually fits the second report badly. Wait until you’ve seen the pattern two or three times.
  • Too many layers. If finding where something actually happens takes six jumps through files, each layer should be pulling its weight.

A useful check: does this abstraction let the reader stop thinking about something? If they still have to open it to understand the caller, it isn’t helping much yet.

Why this matters day to day

  • Code review. Most review comments that aren’t about bugs are about names. Good names make reviews faster.
  • Debugging. A misleading name sends you to the wrong place. total that isn’t really the total costs hours.
  • Changing requirements. A named constant or a well-bounded function means one change instead of twenty.
  • Working with AI tools. Clear names are context. A function called overdue_invoice_ids gets better suggestions than calc, and generated code with vague names is a signal to slow down and read it carefully.

Try it yourself

  1. Find a function in your own code whose name you’d have to explain. Rename it so you wouldn’t.
  2. Search a project for magic numbers (86400, 3600, 1000, status codes like 1 and 2). Give two of them names.
  3. Write the same small function in Python and in PHP or Go, following each language’s naming convention.
  4. Pick one abstraction you use every day (an ORM, a fetch() helper, a framework’s save()). Write down one situation where you’d need to know what it does underneath.

Summary

  • Abstraction hides details so you can think about what, not how. A good one is a black box: name, inputs, output, and a promise.
  • Names are the interface to everything hidden; the computer ignores them, people depend on them.
  • Name things by meaning, include units, make booleans questions, and match length to scope.
  • Follow the language’s conventions: PEP 8, Effective Go, PSR-1, and common JavaScript practice.
  • Abstractions leak (floats, hash tables, queries in a loop); when they do, the fundamentals underneath explain why.
  • Don’t abstract too early; an abstraction should let the reader stop thinking about something.

References