AlgoViz

Tell, don't ask

medium 40 min

Do not read an object's state, decide for it and write the result back.

Watch lesson4:30

Where it shows up

The same pattern appears across everyday software.

  • Redis: INCR

    Reading a number, adding 1 and writing it back from a client loses updates. `INCR` tells the server to do it as one atomic step and answers with the new value.

  • Java: ConcurrentHashMap.putIfAbsent

    The documentation shows the ask version, `containsKey` and then `put`, and adds that the method does the same atomically.

  • Java: Collection.removeIf

    You tell the collection which elements to drop. It chooses how to walk and to close the gaps. Callers no longer write an iterator loop.

  • Python: EAFP

    The glossary describes the style easier to ask forgiveness than permission, and warns that looking first can race in programs with several threads: the key may be gone before the lookup.

  • Akka: fire and forget

    The interaction patterns of Akka begin with telling an actor a message. Asking for a reply is a separate pattern with a timeout.

  • Kubernetes: controllers

    Users state the desired state. Controllers compare it with the current state and act, as a thermostat does. Users do not inspect nodes and place Pods by hand.

  • PostgreSQL: UPDATE ... WHERE

    The condition travels with the change, `RETURNING` gives the new values back, and the count of rows says whether it happened.

  • HTTP: If-Match

    A client says: change this only if it is still the version I saw. The server checks and answers 412 if it is not.

  • React: setState with a function

    `setAge(a => a + 1)` tells React how to compute the next state from the latest one, instead of using a value read earlier.