What's the difference between `def` and `defp` in the Phoenix Framework?

Andrew Hendrie picture Andrew Hendrie · Mar 2, 2016 · Viewed 15.3k times · Source

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 inside a controller in the Phoenix Framework.

Answer

josemrb picture josemrb · Mar 2, 2016

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.

If you have more questions, feel free to read that documentation.