On ruby, what is the reason for include
is private, while Object#extend
is public?
In simple words, the difference between include and extend is that 'include' is for adding methods only to an instance of a class and 'extend' is for adding methods to the class but not to its instance.
What is a private method in Ruby? It's a type of method that you can ONLY call from inside the class where it's defined. This allows you to control access to your methods.
protected methods can be called by any instance of the defining class or its subclasses. private methods can be called only from within the calling object. You cannot access another instance's private methods directly.
The only way to have external access to a private method is to call it within a public method. Also, private methods can not be called with an explicit receiver, the receiver is always implicitly self. Think of private methods as internal helper methods.
Object#extend
has to be public, otherwise you wouldn't be able to use it. After all, its purpose is to mix in a module into an object, so you'd generally call it like obj.extend(Foo)
, which isn't possible with private methods.
Module#include
is usually only used inside a module body like so:
class Bar
include Foo
end
I.e. it is usually called without a receiver, so it doesn't have to be public. Of course, it doesn't have to be private either.
My guess is the reason why it is private is that it is more invasive, because it changes the behavior of every instance of Bar
, whereas Object#extend
only changes a single object. Therefore, Module#include
is in some sense "more dangerous" and thus is made private.
I don't know whether that is the actual reason, but it is consistent with other similar methods like Module#define_method
.
To be able to run Foo.include(Bar)
at any point would most likely be a source of very nasty bugs.
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