Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails: what are the main reasons for making methods private?

If the end_user cannot access the source code of the app, why we still need to make some methods private?

I'm reading the Pragmatic Agile Web Development with Rails and I couldn't understand why we need to make the following method private (even after reading the explanation):

private
  def current_cart Cart.find(session[:cart_id])
   rescue ActiveRecord::RecordNotFound 
   cart = Cart.create 
   session[:cart_id] = cart.id
   cart
   end 
end

It says that it will never allow Rails to make it available as an action, but as a coder, why would I ever do that myself?

like image 865
Chim Kan Avatar asked Oct 27 '25 09:10

Chim Kan


2 Answers

As you say there may be no external reason to make it private. However, it also prevents you — or somebody else using your code — from accidentally making use of the method where you're not supposed to.

See it as a sanity check on your own future behaviour if you will.

like image 104
Janne Avatar answered Oct 28 '25 23:10

Janne


It aims to encourage good practices and good code.

The idea is that you have two separate parts to your code:

"Above the line" (Public). This is the interface to the rest of the world. This is the API, where calls are made when using instances of the object. Once created, you know that THIS is the area where changes can affect current usages of the code.

"Below the line (Private). This is where detailed logic resides. This code can be changed and refactored freely without any affect to the public interface.

It may help guide your test writing

  • Private methods may or may not be (unit) tested.
  • Public methods are more encouraging of both unit and integrated tests as the fact that is is public means that it is serving as the public face for that code and as it is public it might be called from any other point in the future, so having good tests to make sure it continues to work as advertised is essential.

It may help with security as you have greater control who calls private methods (i.e. only public methods in the same class calling them).

It may help reduce name collisions as you have less names in the public space.

like image 28
Michael Durrant Avatar answered Oct 28 '25 23:10

Michael Durrant