‘ def’和‘ defp’有什么区别

我正在阅读《编程凤凰》这本书,我想知道 defdefp之间的区别是什么。

我的控制器中有几个函数——大多数都是这样的操作:

def new (conn, _params) do
...
end

这本书让我在这个控制器中创建另一个函数,这个函数不是典型的控制器操作:

defp user_videos(user) do
...
end

所以我的问题是,在长生不老药中定义一个功能时,我如何知道何时使用 defp,何时使用 def

22742 次浏览

From Elixir’s documentation on functions within modules:

Inside a module, we can define functions with def/2 and private functions with defp/2. A function defined with def/2 can be invoked from other modules while a private function can only be invoked locally.

So defp defines a private function.

So my question is how do I know when to use defp and when to use def when defining a function inside a controller in the Phoenix Framework.

def functions of a module can be called from other modules, whereas defp functions are private, or not callable from other modules. How do you know when to use def and when to use defp? It depends on what other modules may or may not need to know about. A common design pattern is for a module to provide a parent def function that wraps all the behavior of its defpfunctions:

defmodule MyModule do


def function do
# call all the defp functions below to do something
end


defp function2 do
# do something that no other module cares about or needs to know about
end


defp function3 do
# do something that no other module cares about or needs to know about
end


defp function4 do
# do something that no other module cares about or needs to know about
end
end

Here is an example of this with a parser for SEC filings: SEC Company Filings Parser. The main def method wraps all the private functions which no other module really needs to know about.