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
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:
class Example
def xmethod
end
def ymethod
end
def zmethod
end
private :xmethod, :zmethod
end
Does this justify your question?
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.
Dennis had the perfect answer, that is, when using ruby >=2.1, just prefix the def with private (or protected,public)
But I believe that it's now also possible to use private as a block as in:
private begin
def foo
end
def bar
end
end
def zip
end
I'm coming from java background and I hate to have to scroll to see method type. I think it's insane that one cannot specify method visibility per method without ugliness. So I ended up putting a comment #private
before each suck method and then declaring private :...
.
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:
class FooBar
def some_public_method
end
def another_public_method
end
private
def some_private_method
end
def another_private method
end
end
This method should prevent you from having to scroll up and down and will make other programmers more comfortable in your code.
I generally order my methods as follows:
private
, written only onceI use “go to definition” features in my editor so that this doesn’t involve much scrolling, and in any case, if the class is big enough that scrolling becomes problematic, it probably should be broken up into several classes.