← Back to lesson 21: Keep records behind a module boundary

Keep records behind a module boundary: full examples and further reading

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

Use a record internally and return a public map to callers.

Create an internal user record, then expose only a stable map shape.

Run this first

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

Original full example
%% Keep this record inside its owning module
-record(user, {name, age = 0}).

public(#user{name = Name, age = Age}) ->
  #{name => Name, age => Age}.

Calling public/1 inside the module returns a map such as #{name => <<"Maya">>,age => 12}.

Steps for the full example

  1. Read #user{}: Construct or match the private record.
  2. Read Record#user.name: Read one record field.
  3. Read #{key => value}: Return a public map.

Original lesson notes

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

A record gives compile-time names to tuple positions inside modules that share its definition.

A public boundary is the data shape other modules are allowed to depend on.

Symbols and terms
#user{}
Construct or match the private record.
Record#user.name
Read one record field.
#{key => value}
Return a public map.
record
A record gives compile-time names to tuple positions inside modules that share its definition.
public boundary
A public boundary is the data shape other modules are allowed to depend on.
conversion
Converting a private record to a map prevents callers from depending on tuple layout.

Original full exercise

Hide age and expose only the name.

Exercise starter
public(#user{name = Name}) -> #{____ => Name}.

Return a map with the name key.

Show hint

Use the atom name.

Show original answer
Reference answer
public(#user{name = Name}) -> #{name => Name}.
Why not return a record from a public API?

Records compile to tuples, so changing a field can silently change the tuple layout expected by callers.

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