Most of the blogs or tutorials or books have private methods at the bottom of any class/module. Is this the best practice?
I find having private methods as and when nece
There's also the option to prepend private
to the method definition since Ruby 2.1.
class Example
def xmethod
end
private def ymethod
end
private def zmethod
end
end
Looking at the definition, you instantly know if a method is private, no matter where in the file it's defined. It's a bit more typing (if you don't autocomplete) and not all your def
s will be nicely aligned.
You don't need to put public
or private
above each method. I usually put all of my private methods at the bottom of my class. Also, don't have to explicitly say public
as methods are public by default. For example:
class FooBar
def some_public_method
end
def another_public_method
end
private
def some_private_method
end
def another_private method
end
end
One style is to group methods together so that you only use private
and protected
once per class at most. Another style is to specify visibility right after the method definition:
class Example
def my_private_method
end
private :my_private_method
def my_public_method
end
end
As of Ruby 2.1.0 def
returns the method name as a symbol, so a more streamlined style is possible:
class Example
private def my_private_method
end
def my_public_method
end
protected def my_protected_method
end
private_class_method def self.my_private_class_method
end
end
(Note that we use private_class_method
for class methods -- otherwise we'd get NameError: undefined method
since private
expects an instance method. Even when using it as a macro like in the original example it only affects the visibility of instance methods.)
I like this inline visibility style best, as it allows you to organize methods as you wish. It decreases the risk of adding a new method in the wrong place and inadvertently making it private.
As for the class method syntax, you can handle it this way instead:
class Example
private def my_private_method
end
class << self
private def my_private_class_method
end
end
end
I think that public methods is a some kind of interface of the object, and it's logical to place them on the most prominent place i.e. in the top of file.