← Back to lesson 29: Keep the public API small

Keep the public API small: full examples and further reading

The original lesson material is preserved here for reference. The main notebook focuses on this lesson's core question.

The original English project below is a log cleaner. The current notebooks use the same file-statistics project as the Chinese route. These preserved examples show another application of the concepts; their inputs and expected outputs belong to the log cleaner.

Separate file access, parsing, and pure summary logic.

Call one public Cleaner.run/1 API while keeping helper steps private.

Run this first

Run it once, change one input, and compare the new result.

Original full example
# Expose a small parser and one summary call
defmodule Cleaner do
  @levels %{"INFO" => :info, "WARN" => :warn, "ERROR" => :error}

  def parse_line(line) do
    case String.split(String.trim(line), ~r/\s+/, parts: 2) do
      [""] -> :skip
      [level, message] ->
        case Map.fetch(@levels, level) do
          {:ok, tag} -> {:ok, {tag, message}}
          :error -> {:error, :invalid_line}
        end
      _ -> {:error, :invalid_line}
    end
  end

  def run(records), do: {:ok, count(records)}
  defp count(records), do: Enum.frequencies_by(records, fn {level, _message} -> level end)
end

Cleaner.run([{:info, "ready"}, {:warn, "hot"}, {:info, "done"}])

The API returns {:ok, %{info: 2, warn: 1}}.

Steps for the full example

  1. Read def run/1: Expose one project entry point.
  2. Read defp: Keep an implementation helper private.
  3. Read Enum.reduce/3: Build the summary in a pure fold.

Original lesson notes

Run the example first. Predict one result, then change one input and run it again.

A small public API gives callers fewer contracts to learn and protects internal changes.

Pure functions transform supplied data without opening files or changing outside state.

Symbols and terms
def run/1
Expose one project entry point.
defp
Keep an implementation helper private.
Enum.reduce/3
Build the summary in a pure fold.
public API
A small public API gives callers fewer contracts to learn and protects internal changes.
pure core
Pure functions transform supplied data without opening files or changing outside state.
boundary module
A boundary module performs IO and converts its errors into project results.

Original full exercise

Add a public total/1 that returns the number of records.

Exercise starter
def total(records), do: ____

Return the list length.

Show hint

Use length/1.

Show original answer
Reference answer
def total(records), do: length(records)
Should callers invoke count/1?

No. defp keeps it private so the module can change its implementation.

Original lesson takeaways
Design trade-offs and language comparisons
Original course references