What's the difference between `def` and `defp`

Elixir

Elixir Problem Overview


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?

Elixir Solutions


Solution 1 - Elixir

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.

Solution 2 - Elixir

> 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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionAndrew HendrieView Question on Stackoverflow
Solution 1 - ElixirjosemrbView Answer on Stackoverflow
Solution 2 - Elixirvikram7View Answer on Stackoverflow