Skip to the workspace
Pebellslearn by building
Object-Oriented Programming  ›  Lesson

Abstraction

Abstraction 13 minAbstraction gives callers a simple view of what something does while hiding how it does it.

software design architecture / Abstraction

Explore each scene at your own pace.

01 · The rule

The rule

Abstraction

To charge a card, Shelfwise has to build an HTTP request, sign it with a secret key, send it, wait, retry if the network hiccups, and translate the provider's error codes. The checkout code should not know any of that. It wants to say one thing: "charge this card this amount". Abstraction lets it say exactly that.

The rule

Show what it does; hide how it does it.

An abstraction is a simplified view of something: the few operations a caller needs, with every detail of how they work kept out of sight.

from abc import ABC, abstractmethod

class PaymentGateway(ABC):
    @abstractmethod
    def charge(self, card, amount):
        """Charge the card; raise PaymentFailed if it is declined."""

class CardProviderGateway(PaymentGateway):
    def charge(self, card, amount):
        ...  # HTTP, signing, retries, error translation

Checkout depends only on PaymentGateway.charge(card, amount). The abstract class declares what every gateway can do; the concrete class fills in how. Python's abc module stops anyone creating a PaymentGateway directly, since it has no real charge of its own.

Abstraction vs encapsulation. They work together but answer different questions:

  • Encapsulation protects an object's state: nobody outside can break its rules.
  • Abstraction simplifies an object's interface: callers see only what they need.

You meet abstraction everywhere. open("orders.csv") hides disk sectors and file systems. A car's steering wheel hides the steering rack. A good abstraction is one you can use correctly without ever looking inside. Its docstring states the promise, such as "raises PaymentFailed if declined", and that promise is all a caller needs.

Two things follow from depending on the simple view. You can swap the implementation (a different payment provider) without touching callers. And you can fake it in tests with a tiny FakeGateway that records charges instead of sending them.

Scene 1 of 5
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.