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 necessary more convenient. For example:
public
def my_method
# do something
minion_method
end
private
def minion_method
# do something
end
public
def next_method
end
This way I find the code more readable instead of scrolling up and down continuously which is very irritating.
Is there something terribly wrong in this approach? Is having private methods at the bottom not just a best practice and something else?
One style is to group methods together so that you only use
private
andprotected
once per class at most. Another style is to specify visibility right after the method definition:As of Ruby 2.1.0
def
returns the method name as a symbol, so a more streamlined style is possible:(Note that we use
private_class_method
for class methods -- otherwise we'd getNameError: undefined method
sinceprivate
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:
It's a matter of taste I suppose, but I'd rather explicitly name each method private on the line after said method like so:
I don't like having to specify public or private for each method. Putting all private methods at the bottom lets me have a single instance of "private" per file. I guess it's a matter of taste.
The best practice in my point of view is to go sequentially and declare your methods without keeping private in point of view.
At the end, you can make make any method private by just adding:
private :xmethod
Example:
Does this justify your question?
There's also the option to prepend
private
to the method definition since Ruby 2.1.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.As others have already pointed out the convention is to put private methods at the bottom, under one private class. However, you should probably also know that many programers use a double indented (4 spaces instead of 2) method for this. The reason is that often times you won't see "private" in your text editor and assume they could be public. See below for an illustration:
This method should prevent you from having to scroll up and down and will make other programmers more comfortable in your code.