What is the ruby conventions to name private method?

P

pierr

Hi,

What would you name the private method _insert in below situation?

Class Binary_search_tree

def insert node
_insert @root, node
end

private
def _insert tree, node
#....
end


end
 
R

Ryan Davis

What would you name the private method _insert in below situation?

Class Binary_search_tree

def insert node
_insert @root, node
end

private
def _insert tree, node
#....
end


end

My conventions applied to your code:
class BinarySearchTree
def insert node
# ...
end
end

1) Don't use underscores in class names.
2) Don't have extra empty lines for no reason.
3) Use 2 spaces per indent.
4) Don't have private methods if you don't need them.
5) You don't need them. No, really.
 
F

Fabian Streitel

[Note: parts of this message were removed to make it a legal post.]

I name them like any other method. If you look at the Standard
Library classes, they do so too. Like Object, for example:

002:0> Object.new.private_methods
=> ["exit!", "chomp!", "initialize", "irb_eval", "fail", "print",
"binding", "irb_binding", "split", "Array", "gem", "format", "chop",
"iterator?", "catch", "readlines", "trap", "remove_instance_variable",
"gem_original_require", "getc", "returning", "singleton_method_added",
"caller", "putc", "autoload?", "proc", "pp", "chomp", "block_given?",
"throw", "p", "sub!", "loop", "syscall", "trace_var", "exec", "Integer",
"callcc", "puts", "initialize_copy", "load", "x",
"singleton_method_removed", "exit", "srand", "lambda", "y", "DelegateClass",
"get_line", "global_variables", "gsub!", "untrace_var", "print_line",
"open", "`", "method_missing", "system", "Float", "require", "gets",
"abort", "sub", "singleton_method_undefined", "get_lines", "test", "rand",
"eval", "warn", "local_variables", "chop!", "fork", "set_trace_func",
"printf", "raise", "scan", "Rational", "String", "sleep", "select", "gsub",
"sprintf", "autoload", "readline", "at_exit", "__method__"]

Except for some rare cases where __something__ is used, but those are ruby
core methods and
you shouldn't use that pattern.


1) Don't use underscores in class names.
yep.


2) Don't have extra empty lines for no reason.

I count better readability as a good reason.

3) Use 2 spaces per indent.

I like 4 better

4) Don't have private methods if you don't need them.

I agree.

5) You don't need them. No, really.

You sometimes do, if you want to be DRY.

All those styling conventions are 100% subjective. [removed styling advice]

Although you didn't ask for styling guide, here we are again... :)
It's too damn easy to slip into that topic... I had already written 3
paragraphs.
 
P

Pascal J. Bourguignon

Fabian Streitel said:
I count better readability as a good reason.

If you need to improve readability by separating sections of a method
with empty lines, then it's a sure sign that you should have split
that method!


I like 4 better

Do not store indentation in files. Have your editor automatically
re-indent when opening the file.

(defun pjb-indent-meat ()
;; If pjb-indent-meat is not in last position,
;; then move it over to last position.
(let ((p (position (function pjb-indent-meat) find-file-hook)))
(when (and p (< (1+ p) (length find-file-hook)))
(setf find-file-hook
(append (remove (function pjb-indent-meat) find-file-hook)
(list (function pjb-indent-meat))))))
;; Work only on some modes:
(when (member major-mode '(lisp-mode common-lisp-mode emacs-lisp-mode
perl-mode shell-script-mode ruby-mode
scheme-mode c-mode c++-mode objective-c-mode))
(if buffer-read-only
(unwind-protect
(progn (toggle-read-only)
(indent-region (point-min) (point-max))
(pop-mark))
(toggle-read-only))
(progn (indent-region (point-min) (point-max))
(pop-mark)))
(set-buffer-modified-p nil)))

(setf find-file-hook
(append (remove (function pjb-indent-meat) find-file-hook)
(list (function pjb-indent-meat))))
 
D

David A. Black

Hi --

All those styling conventions are 100% subjective. [removed styling advice]

Not really. It's not enforced by the parser, but there is a
conventional, traditional Ruby style. I try to follow Matz's example
on this stuff, and to make my code blend into the conventional look
(which is to a large extent what grabbed my attention about Ruby
originally).


David

--
David A. Black / Ruby Power and Light, LLC / http://www.rubypal.com
Ruby/Rails training, mentoring, consulting, code-review
Latest book: The Well-Grounded Rubyist (http://www.manning.com/black2)

September Ruby training in NJ has been POSTPONED. Details to follow.
 
R

Ryan Davis

Hi --

All those styling conventions are 100% subjective. [removed styling =20=
advice]

Not really. It's not enforced by the parser, but there is a
conventional, traditional Ruby style. I try to follow Matz's example
on this stuff, and to make my code blend into the conventional look
(which is to a large extent what grabbed my attention about Ruby
originally).

Fabian seems to have missed a point he made himself:

convention |k=C9=99n=CB=88ven ch =C9=99n|
noun
1 a way in which something is usually done, esp. within a particular =20
area or activity :the woman who overturned so many conventions of =20
children's literature.
=E2=80=A2 behavior that is considered acceptable or polite to most =
members of =20
a society : he was an upholder of convention and correct form | social =20=

conventions.

subjective |s=C9=99b=CB=88jektiv|
adjective
1 based on or influenced by personal feelings, tastes, or opinions : =20
his views are highly subjective | there is always the danger of making =20=

a subjective judgment. Contrasted withobjective .

ABSOLUTELY. I think most of us got into ruby because the way in which =20=

ruby was usually done harmonized with our personal feelings, tastes, =20
and opinions.

I've never seen a programming language who's "styling conventions were =20=

100% objective" but I don't think I'd like it.=
 
R

Ryan Davis

You sometimes do, if you want to be DRY.

No. I _never_ do. I can't remember a single time in my 9 years of ruby
that I've needed or even wanted private method visibility.

Method visibility has nothing to do with code duplication.
 
J

Josh Cheek

Ryan Davis:
4) Don't have private methods if you don't need them.
5) You don't need them. No, really.

I=92ll bite. Note: I consider myself a beginner Rubyist and I=92d love to
hear your (and others=92!) reasons for the above and/or against the below= :)

I use private methods when I factor them out of my public methods (once
the public methods have decent spec coverage). This makes me think
harder on the (hopefully =96 minimal) public API of my objects and
prevents me from calling such methods =91in just that single place
where it would be useful=92; a method=92s either useful to the outside
world (and should be promoted to public API with individual, descriptive
spec coverage) or not, period. Using private methods helps me keep
checks on this.

I also use protected attr_readers so that my objects can tell whether
they =3D=3D others of the same kind without exposing their instance
variables to the outside world; an attr_reader on an Array/Hash/Set
does not guarantee that the given Array/Hash/Set is not modifiable from
the outside world=B9, hence I=92d rather not expose such instance variabl= es
more than necessary.

=B9 It=92s one of the few places where Ruby diverges from the principle
of least surprise; I can see certain lovely symmetry and simplicity
in attr_reader working the same for all variables, but I found the name
a bit misleading when I started to learn Ruby =96 my thoughts were that
it should either not be called a reader or should return a dup of the
variable in question=85 (I did get used to this since then, though, and
realised that other languages=92 generic getters usually do the same.)

=97 Shot
--
Born to be mild. [elpanda]

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkqcRXAACgkQi/mCfdEo8UpIWwCeNYQ+NZNW895936Gbnwj3btMA
ylYAnRbvAkMrzP0Ep6SW1y6kl07id7aV
=3D0fIP
-----END PGP SIGNATURE-----
I do the same thing, I use private methods to encapsulate internal logic.
Sure something _could_ be used elsewhere, or for reasons that I haven't
considered, but it pollutes the public namespace, and obfuscates the API.
The outside world doesn't need (or probably want) to be subjected to the
internal logic of my code. Even I, using my own code later, prefer this
approach, because it simplifies use.

Take the Array class as an example, it has 96 private methods, and 85 publi=
c
methods. The public ones are the ones I almost certainly am looking for, ho=
w
burdensome would it be if they made them all public and I had to look at 18=
1
methods, more than half of which are irrelevant, every time I was trying to
find something.

This is the main reason I use private methods. I also use Rails, in which
private vs public is relevant because it affects behaviour. For example, a
public method in a controller will try to render a template after it has
been called.

I have, however, experienced situations where things are irritating as a
result of private methods, for example, in the API for define_method
http://www.ruby-doc.org/core/classes/Module.html#M001654 it says "This bloc=
k
is evaluated using instance_eval, a point that is tricky to demonstrate
because define_method<http://www.ruby-doc.org/core/classes/Module.html#M001=
654>is
private <http://www.ruby-doc.org/core/classes/Module.html#M001641>. (This i=
s
why we resort to the send hack in this example.)" So it can make things
difficult, as well.
 
T

Tony Arcieri

I also use private methods to separate out internal implementation details
that I expect to change (e.g. if we decide to switch to a different
algorithm). I also decompose into small functions a lot, perhaps a side
effect of Erlang on the brain.

However, the instant I feel the urge to use __send__ to call a private
method I make that method public.

Ryan Davis:


I=92ll bite. Note: I consider myself a beginner Rubyist and I=92d love = to
hear your (and others=92!) reasons for the above and/or against the bel=
ow.
:)

I use private methods when I factor them out of my public methods (once
the public methods have decent spec coverage). This makes me think
harder on the (hopefully =96 minimal) public API of my objects and
prevents me from calling such methods =91in just that single place
where it would be useful=92; a method=92s either useful to the outside
world (and should be promoted to public API with individual, descriptiv= e
spec coverage) or not, period. Using private methods helps me keep
checks on this.

I also use protected attr_readers so that my objects can tell whether
they =3D=3D others of the same kind without exposing their instance
variables to the outside world; an attr_reader on an Array/Hash/Set
does not guarantee that the given Array/Hash/Set is not modifiable from
the outside world=B9, hence I=92d rather not expose such instance varia= bles
more than necessary.

=B9 It=92s one of the few places where Ruby diverges from the principle
of least surprise; I can see certain lovely symmetry and simplicity
in attr_reader working the same for all variables, but I found the name
a bit misleading when I started to learn Ruby =96 my thoughts were that
it should either not be called a reader or should return a dup of the
variable in question=85 (I did get used to this since then, though, and
realised that other languages=92 generic getters usually do the same.)

=97 Shot
--
Born to be mild. [elpanda]

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkqcRXAACgkQi/mCfdEo8UpIWwCeNYQ+NZNW895936Gbnwj3btMA
ylYAnRbvAkMrzP0Ep6SW1y6kl07id7aV
=3D0fIP
-----END PGP SIGNATURE-----
I do the same thing, I use private methods to encapsulate internal logic.
Sure something _could_ be used elsewhere, or for reasons that I haven't
considered, but it pollutes the public namespace, and obfuscates the API.
The outside world doesn't need (or probably want) to be subjected to the
internal logic of my code. Even I, using my own code later, prefer this
approach, because it simplifies use.

Take the Array class as an example, it has 96 private methods, and 85
public
methods. The public ones are the ones I almost certainly am looking for,
how
burdensome would it be if they made them all public and I had to look at
181
methods, more than half of which are irrelevant, every time I was trying = to
find something.

This is the main reason I use private methods. I also use Rails, in which
private vs public is relevant because it affects behaviour. For example, = a
public method in a controller will try to render a template after it has
been called.

I have, however, experienced situations where things are irritating as a
result of private methods, for example, in the API for define_method
http://www.ruby-doc.org/core/classes/Module.html#M001654 it says "This
block
is evaluated using instance_eval, a point that is tricky to demonstrate
because define_method<
http://www.ruby-doc.org/core/classes/Module.html#M001654>is
private <http://www.ruby-doc.org/core/classes/Module.html#M001641>. (This
is
why we resort to the send hack in this example.)" So it can make things
difficult, as well.



--=20
Tony Arcieri
Medioh/Nagravision
 
S

steve

Ryan said:
I've never seen a programming language who's "styling conventions were
100% objective" but I don't think I'd like it.

RPG III? And I didn't like it.

Steve
 
F

Fabian Streitel

[Note: parts of this message were removed to make it a legal post.]
Fabian seems to have missed a point he made himself:
Alright, point taken, "subjective convention" wasn't well formulated. But I
remember
many many "4 spaces is better than 2 tabs" discussions (and the like),
all of which seemed very pointless to me, since in the end, everyone did
what he thought
was best anyways. It's like discussing the Zelda timeline -- you're never
gonna reach a
definite answer.


No. I _never_ do. I can't remember a single time in my 9 years of ruby that
I've needed or even wanted private method visibility.

Well, I do. Maybe you're a better programmer than me and don't write stuff
that needs
it, but I sure do. And not using them would have either meant code
duplication or putting
functionality into public methods that wasn't meant to be publicly called.

Like you yourself said:

If you need to improve readability by separating sections of a method
with empty lines, then it's a sure sign that you should have split
that method!

And I agree!
But I don't want internal class functionality accessible as public methods,
because that
will expose the interal code to a public interface, which is definitely not
what I want.
So i make it private/protected. And what's the harm?
Or am I missing some better solution here?

Greetz!
 
F

Fabian Streitel

same as you said :)

I'm excited to hear Ryan Davis's approach since he claims to never use
private
methods at all.

2009/9/1 Tony Arcieri said:
I also use private methods to separate out internal implementation detail= s
that I expect to change (e.g. if we decide to switch to a different
algorithm). I also decompose into small functions a lot, perhaps a side
effect of Erlang on the brain.

However, the instant I feel the urge to use __send__ to call a private
method I make that method public.

Ryan Davis:

4) Don't have private methods if you don't need them.
5) You don't need them. No, really.

I=92ll bite. Note: I consider myself a beginner Rubyist and I=92d lov= e to
hear your (and others=92!) reasons for the above and/or against the
below.
:)

I use private methods when I factor them out of my public methods (on= ce
the public methods have decent spec coverage). This makes me think
harder on the (hopefully =96 minimal) public API of my objects and
prevents me from calling such methods =91in just that single place
where it would be useful=92; a method=92s either useful to the outsid= e
world (and should be promoted to public API with individual, descriptive
spec coverage) or not, period. Using private methods helps me keep
checks on this.

I also use protected attr_readers so that my objects can tell whether
they =3D=3D others of the same kind without exposing their instance
variables to the outside world; an attr_reader on an Array/Hash/Set
does not guarantee that the given Array/Hash/Set is not modifiable fr= om
the outside world=B9, hence I=92d rather not expose such instance var= iables
more than necessary.

=B9 It=92s one of the few places where Ruby diverges from the princip= le
of least surprise; I can see certain lovely symmetry and simplicity
in attr_reader working the same for all variables, but I found the na= me
a bit misleading when I started to learn Ruby =96 my thoughts were th= at
it should either not be called a reader or should return a dup of the
variable in question=85 (I did get used to this since then, though, a= nd
realised that other languages=92 generic getters usually do the same.= )

=97 Shot
--
Born to be mild. [elpanda]

-----BEGIN PGP SIGNATURE-----
Version: GnuPG v1.4.9 (GNU/Linux)

iEYEARECAAYFAkqcRXAACgkQi/mCfdEo8UpIWwCeNYQ+NZNW895936Gbnwj3btMA
ylYAnRbvAkMrzP0Ep6SW1y6kl07id7aV
=3D0fIP
-----END PGP SIGNATURE-----
I do the same thing, I use private methods to encapsulate internal logi= c.
Sure something _could_ be used elsewhere, or for reasons that I haven't
considered, but it pollutes the public namespace, and obfuscates the AP= I.
The outside world doesn't need (or probably want) to be subjected to th= e
internal logic of my code. Even I, using my own code later, prefer this
approach, because it simplifies use.

Take the Array class as an example, it has 96 private methods, and 85
public
methods. The public ones are the ones I almost certainly am looking for= ,
how
burdensome would it be if they made them all public and I had to look a= t
181
methods, more than half of which are irrelevant, every time I was tryin=
g
to
find something.

This is the main reason I use private methods. I also use Rails, in whi= ch
private vs public is relevant because it affects behaviour. For example=
,
a
public method in a controller will try to render a template after it ha= s
been called.

I have, however, experienced situations where things are irritating as = a
result of private methods, for example, in the API for define_method
http://www.ruby-doc.org/core/classes/Module.html#M001654 it says "This
block
is evaluated using instance_eval, a point that is tricky to demonstrate
because define_method<
http://www.ruby-doc.org/core/classes/Module.html#M001654>is
private <http://www.ruby-doc.org/core/classes/Module.html#M001641>. (This
is
why we resort to the send hack in this example.)" So it can make things
difficult, as well.
 
M

Michal Suchanek

2009/8/31 Shot (Piotr Szotkowski) said:
Ryan Davis:


I=E2=80=99ll bite. Note: I consider myself a beginner Rubyist and I=E2=80= =99d love to
hear your (and others=E2=80=99!) reasons for the above and/or against the= below. :)

I guess this depends on the size of your classes. I only write
relatively small things in Ruby so I can track which methods are what
without this hint. I also have methods that are "private" in a sense
that is not possible to express with the private or similar keyword in
any language I know - they span multiple classes and work nicely
together but not necessarily by themselves - ie. inspect variant that
produces HTML representing a structure involving multiple classes and
which also needs to get the top-level HTML header/footer somewhere to
work well.

I would think that you should not get classes so large that you need
private methods to make the class usable but Array mentioned in
another email is a good counterexample.

The other reason would be when writing a library there is no easier
way to express which methods are intended for outside use and which
not. The user can still get at the private ones but they should not be
surprised if they disappear or work in a completely different way in
next version of the library.

So would suggest to decide which methods *should* be private and
document that. Adding the actual keyword is optional and may be useful
in some cases and get in your way at other times.

Thanks

Michal
 
R

Robert Klemme

2009/8/31 Shot (Piotr Szotkowski) said:
Ryan Davis:


I=92ll bite. Note: I consider myself a beginner Rubyist and I=92d love to
hear your (and others=92!) reasons for the above and/or against the below= :)

I use private methods when I factor them out of my public methods (once
the public methods have decent spec coverage). This makes me think
harder on the (hopefully =96 minimal) public API of my objects and
prevents me from calling such methods =91in just that single place
where it would be useful=92; a method=92s either useful to the outside
world (and should be promoted to public API with individual, descriptive
spec coverage) or not, period. Using private methods helps me keep
checks on this.
+1

I also use protected attr_readers so that my objects can tell whether
they =3D=3D others of the same kind without exposing their instance
variables to the outside world; an attr_reader on an Array/Hash/Set
does not guarantee that the given Array/Hash/Set is not modifiable from
the outside world=B9, hence I=92d rather not expose such instance variabl= es
more than necessary.

-0 - you cannot really prevent access to internals and if you include
attributes in the equivalence relation you usually want to access them
from the outside.

My 0.02 EUR...
=B9 It=92s one of the few places where Ruby diverges from the principle
of least surprise; I can see certain lovely symmetry and simplicity
in attr_reader working the same for all variables, but I found the name
a bit misleading when I started to learn Ruby =96 my thoughts were that
it should either not be called a reader or should return a dup of the
variable in question=85 (I did get used to this since then, though, and
realised that other languages=92 generic getters usually do the same.)

This is not necessary as a general functionality because there are
immutable classes, others can be frozen and last but not least
sometimes you want to give someone access to internals.

Kind regards

robert


--=20
remember.guy do |as, often| as.you_can - without end
http://blog.rubybestpractices.com/
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,767
Messages
2,569,570
Members
45,045
Latest member
DRCM

Latest Threads

Top