I'm going through the Programming Phoenix book and I am wondering what the difference between def
and defp
is.
There are several functions in my controller - most of them are actions like this:
def new (conn, _params) do
...
end
The book had me create another function in this controller that is not a typical controller action like this:
defp user_videos(user) do
...
end
So my question is how do I know when to use defp
and when to use def
when defining a function in Elixir?
From Elixir’s documentation on functions within modules:
Inside a module, we can define functions with
def/2
and private functions withdefp/2
. A function defined withdef/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 defp
functions:
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With