Feature #6539
closedpublic and private for core methods
Description
I feel there are inconsistencies in which methods are public and which are private.
For example:
obj = []
prev = obj.instance_variable_get(:@foo) # allowed
obj.instance_variable_set(:@foo, nil) # allowed
# But these are almost equivalent to:
prev = obj.remove_instance_variable(:@foo)
# => NoMethodError: private method `remove_instance_variable' called for []:Array
Another example:
module M
def foo
42
end
end
M.module_function :foo # private method `module_function' called for M:Module
M.extend M # allowed
M.foo # => 42
Reverse example:
{}.method_missing :foo # => private method `method_missing' called
{}.respond_to_missing? :foo, false # => allowed, why?
Which methods should be private is a different question for Ruby than for apps and libraries; the "real" private methods of Ruby are in C!
For Ruby, I feel that a method should be private if it is not meant to be called except by Ruby itself (callbacks, etc...), or if it's a "global" methods of Kernel that is meant to be called directly (i.e. puts
instead of 42.puts
)
Otherwise, it should be public. This includes methods like Module#include
.
I don't know what the rationale was to make include
and the like private.
I feel it is now quite common to use metaprogramming, e.g. to include
modules from outside a class. It's part of a Class' API that it can be extended and modified, so these methods should be public.
Concrete proposal:
Should be made private:
Object and descendants
#initialize_clone
#initialize_dup
#respond_to_missing?
Rational & Complex
#marshal_dump
#marshal_load
Time
#_dump
._load
Note that Delegate#initialize_{clone|dup} are already private
Should be made public:
Object
#remove_instance_variable
Module
#attr
#attr_reader
#attr_writer
#attr_accessor
#remove_const
#include
#remove_method
#undef_method
#alias_method
#public
#protected
#private
#module_function
#define_method