I come from more of a C# background yet am learning Ruby in my spare time.
Given classes, it is possible to make their methods private
, public
(default) or protected
. While I understand their usage, is it typical for Ruby code to make use of such modifiers, despite being a dynamic language, in which the user can easily override access?
While using something like Send
allows the user access to private methods regardless, I was just wondering what the best practice is regarding Ruby and access modifiers? In other words, should I be making use of them in my classes?
Given classes, it is possible to make their methods private, public (default) or protected. While I understand their usage, is it typical for Ruby code to make use of such modifiers, despite being a dynamic language, in which the user can easily override access?
It's still relatively common, because it conveys intent and minimizes the interface you're exposing. Some conventions to observe:
Simply omit the public
, since all methods are public unless you say otherwise, and methods are typically grouped by access modification.
Even though a user can override access, that doesn't mean they should (in much the same way, you don't see C# developers doing crazy things like injecting IL stubs into classes so that they can access private methods). So it's still useful to have the distinction.
Protected methods are somewhat rarer than they would be in C#, because Ruby doesn't really encourage inheritance as a means of passing on behavior. Common behavior can often be refactored into Module
s and then include/extend
-ed as necessary.
Private methods are about as common as in C#; Ruby often favors lots of tiny methods that do very specific things, which you then compose together to get something useful. But you don't expose these methods, because they're not part of your public interface and you want to keep that clutter-free.
Because private methods aren't considered part of the interface, you should be free to change them with impunity. By making them private, you've put others on notice that these methods and their implementation or definitions could change at any time.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With