Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

elixir

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?

like image 349
Andrew Hendrie Avatar asked Mar 01 '16 23:03

Andrew Hendrie


2 Answers

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.

like image 116
josemrb Avatar answered Nov 11 '22 17:11

josemrb


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.

like image 22
vikram7 Avatar answered Nov 11 '22 19:11

vikram7