今日已更新 327 条资讯 | 累计 39856 条内容
关于我们

Learning Elixir: Private vs Public Functions

João Paulo Abreu 2026年09月05日 20:48 1 次阅读 来源:Dev.to

Clients of a house only see the facade: the door, the windows, the porch. The boiler closet, the fuse box, and the plumbing stay out of sight — and that is exactly what lets someone rearrange them without telling anyone. An Elixir module works the same way. The functions other modules call are the facade; helpers marked defp are the boiler closet. In the previous article about project structure we agreed that Todo is the front door of the todo feature and Parser is a back room. Nothing enforced that, though: every function we wrote with def was public, so any module could call Parser directly. defp turns the "back room" sign into an actual lock. In this article I'll explore the difference between def and defp , what privacy actually protects, and the patterns I use to keep our todo modules' interfaces small. Note : The examples in this article use Elixir 1.20.1. While most operations should work across different versions, some functionality might vary. We keep building on the same learning_elixir Mix project from the previous article ( Learning Elixir: Project Structure ). If you no longer have it, recreate it with mix new learning_elixir and add the Todo modules back — we'll show every file in full anyway. Two details that keep showing up: modules live under lib/ , and multi-step scripts like try_todo.exs live at the project root, next to mix.exs . Short checks run inline with mix run -e '...' , no file needed, and iex -S mix opens the same project in the shell for quick experiments. One more note on the outputs: mix prints a Compiling N files (.ex) banner before running, and the count depends on your build cache. I trimmed that line from most examples below. Table of Contents Introduction The Difference: def and defp What Privacy Actually Protects Refactoring the Todo Project Privacy Is Per Module, Not Per Namespace Multiple Clauses: One Name, One Visibility Docs, Specs, and Private Functions @doc false: Public but Hidden Reading a Module's Surface Import Only Bri

本文内容来源于互联网,版权归原作者所有
查看原文