What is the ruby conventions to name private method?

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

On Aug 30, 2009, at 23:48 , pierr wrote:

    #....

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.

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.

  1. Don’t have extra empty lines for no reason.

I count better readability as a good reason.

  1. Use 2 spaces per indent.

I like 4 better

  1. Don’t have private methods if you don’t need them.

I agree.

  1. 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… :slight_smile:
It’s too damn easy to slip into that topic… I had already written 3
paragraphs.

Fabian S. [email protected] writes:

  1. Don’t have extra empty lines for no reason.

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!

  1. Use 2 spaces per indent.

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))))

Hi –

On Mon, 31 Aug 2009, Fabian S. wrote:

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 (The Well-Grounded Rubyist)

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

On Aug 31, 2009, at 03:00 , David A. Black wrote:

(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ənˈven ch ən|
noun
1 a way in which something is usually done, esp. within a particular
area or activity :the woman who overturned so many conventions of
children’s literature.
• behavior that is considered acceptable or polite to most members of
a society : he was an upholder of convention and correct form | social
conventions.

subjective |səbˈjektiv|
adjective
1 based on or influenced by personal feelings, tastes, or opinions :
his views are highly subjective | there is always the danger of making
a subjective judgment. Contrasted withobjective .

ABSOLUTELY. I think most of us got into ruby because the way in which
ruby was usually done harmonized with our personal feelings, tastes,
and opinions.

I’ve never seen a programming language who’s “styling conventions were
100% objective” but I don’t think I’d like it.

Ryan D.:

  1. Don’t have private methods if you don’t need them.
  2. You don’t need them. No, really.

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

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 – minimal) public API of my objects and
prevents me from calling such methods ‘in just that single place
where it would be useful’; a method’s 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 == 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¹, hence I’d rather not expose such instance variables
more than necessary.

¹ It’s 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 – my thoughts were that
it should either not be called a reader or should return a dup of the
variable in question… (I did get used to this since then, though, and
realised that other languages’ generic getters usually do the same.)

— Shot

On Aug 31, 2009, at 01:55 , Fabian S. wrote:

  1. You don’t need them. No, really.

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.

On Mon, Aug 31, 2009 at 4:49 PM, Shot (Piotr S.)
[email protected]wrote:

harder on the (hopefully – minimal) public API of my objects and
the outside world¹, hence I’d rather not expose such instance variables
— Shot

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
class Module - RDoc Documentation it says “This
block
is evaluated using instance_eval, a point that is tricky to demonstrate
because
define_methodhttp://www.ruby-doc.org/core/classes/Module.html#M001654is
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.

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 D. wrote:

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

same as you said :slight_smile:

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

2009/9/1 Tony A. [email protected]

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!

2009/8/31 Shot (Piotr S.) [email protected]:

harder on the (hopefully – minimal) public API of my objects and
prevents me from calling such methods ‘in just that single place
where it would be useful’; a method’s 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 == 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¹, hence I’d rather not expose such instance variables
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…

¹ It’s 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 – my thoughts were that
it should either not be called a reader or should return a dup of the
variable in question… (I did get used to this since then, though, and
realised that other languages’ 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

2009/8/31 Shot (Piotr S.) [email protected]:

Ryan D.:

  1. Don’t have private methods if you don’t need them.
  2. You don’t need them. No, really.

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

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

Robert K.:

2009/8/31 Shot (Piotr S.) [email protected]:

I also use protected attr_readers so that my objects can tell whether
they == 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¹, hence I’d rather not expose such instance variables
more than necessary.

-0

:slight_smile:

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.

I guess this is true in most cases. In my main case, though, I’m using
a math/logic representation of a finite state machine and the ‘outside
world’ should really only be interested in certain aggregated properties
of the FSM; at the same time, direct comparison of two FSMs’ instance
variables’ states is the best way of assessing their equality.

In the case of FSMs I simply freeze the ivars upon instantiation, so it
wouldn’t hurt to expose the attr_readers (although nothing else should
really use them, and I don’t feel like writing specs for the accessors),
but there are other objects in my code where I can’t freeze the ivars
(graphs change their vertices and edges over time), I don’t want to
expose them and still the best way to compare two such objects to each
other is to check their ivar state (and here protected attr_readers work
lovely for me).

(As for the ‘you cannot really prevent access to internals’ – that’s
true, but I can make sure it looks like a code smell when one accesses
my classes’ internals directly.)

¹ It’s 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 – my thoughts were that
it should either not be called a reader or should return a dup of the
variable in question… (I did get used to this since then, though, and
realised that other languages’ 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.

Yes, and to add another example, sometimes the ivars represent
singleton objects which really shouldn’t be duped by attr_reader.

I think my main point was that saying ‘attr_reader is for read access to
an ivar and attr_writer is for write access to it’ (which is one of the
way of understanding the attr_* stuff) should be usually accompanied
with the ‘instance.ivar << something’ example showing that the
‘read access’ shouldn’t be taken as ‘read-only access’, but rather
as ‘here, look, that’s the object behind the ivar, you can do anything
to it’ access.

— Shot