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 function while helpers stay private.
Run this first
Run it once, change one input, and compare the new result.
%% Export a small parser and one summary call
-module(cleaner).
-export([run/1, parse_line/1]).
run(Records) -> {ok, count(Records)}.
parse_line(Line) ->
case binary:split(string:trim(Line), <<" ">>, [trim]) of
[] -> skip;
[<<"INFO">>, Message] -> {ok, {info, Message}};
[<<"WARN">>, Message] -> {ok, {warn, Message}};
[<<"ERROR">>, Message] -> {ok, {error, Message}};
_ -> {error, invalid_line}
end.
count(Records) ->
lists:foldl(fun({Level, _}, Acc) ->
maps:update_with(Level, fun(N) -> N + 1 end, 1, Acc)
end, #{}, Records).cleaner:run([{info,<<"ready">>},{info,<<"done">>}]) returns {ok,#{info => 2}}.
Steps for the full example
- Read
-export([run/1]).: Expose one project entry point. - Read
count/1: Keep an unexported helper private. - Read
maps:update_with/4: Update one count in a map.
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 and protects internal changes.
Pure functions transform supplied data without opening files or changing outside state.
Symbols and terms
-export([run/1]).- Expose one project entry point.
count/1- Keep an unexported helper private.
maps:update_with/4- Update one count in a map.
- public API
- A small public API gives callers fewer contracts and protects internal changes.
- pure core
- Pure functions transform supplied data without opening files or changing outside state.
- boundary module
- A boundary performs IO and turns its failures into project results.
Original full exercise
Add a public total/1 function.
total(Records) -> ____.Return the list length.
Show hint
Use length/1 and remember to export the function.
Show original answer
total(Records) -> length(Records).Can callers invoke count/1?
No. It is not exported, so the module can change that helper without changing its public API.
Original lesson takeaways
- Export a narrow API.
- Keep transformations pure.
- Put IO and error conversion at boundaries.