3

Edit: This question has been marked as a duplicate of a more generic OO question about the purpose of private methods. This question is specifically geared towards controllers; I'm wondering if there are reasons besides the classic OO "don't make any methods public that don't need to be" sentiment.


There are a number of resources warning that non-action controller methods should be kept private to avoid the possibility of those methods being routed to. My question is about the reasoning behind that warning.

My understanding is that the routes.rb file is a whitelist of possible routes, so why does it matter if a controller has public methods (as long as they're not in the routes.rb file)? Is the idea that making the methods private is just an extra layer of protection against future me/developers mistakenly adding routes that include the methods? Is there some other sneaky way a public controller method could get into a route?

This book section warns that a controller's public methods can, by default, be accessed by some URL. Is that correct?

This answer explains that keeping controller methods private prevents any requests from being routed to it, but isn't that already handled by the routes?

The Rails Guide mentions that it's best practice to lower visibility of controller methods that shouldn't be actions.

The Thoughtbot Rails style guide doesn't even entertain the notion of public controller methods and says to use private over protected.

There's clearly community consensus here. What's the reasoning underlying these suggestions?

Parker
  • 113
  • 1
  • 7

1 Answers1

0

All these rules make sense. The idea to keep public interfaces (a set of public methods) for classes (including Rails controllers) as tiny as possible comes from the OOP paradigm along with the SOLID rules. And the motivation is that it allows keeping your system more robust and flexible for growing and refactoring (less public methods you have - less their calls you have in your code - easy refactoring).

In short, if you don't need a method to be visible "outside", hide it as default. I mean, when you write a new class start with one public method, that's really needed to have callable outside, and keep others private, until you really need them outside.

The explanation, that you need them keep private due to being accessible outside is partially correct. In fact, a public or private method can't be accessed by URL if no URL pointed to that method. In other words: no defined route for this method - no its call.

ka8725
  • 2,788
  • 1
  • 24
  • 39