Generally speaking, you will want to call the _topsecretsort sub as a method, not as a function. The primary reason would be that _topsecretsort may need access to $self (perhaps so that it can call further methods), and even if the current implementation of _topsecretsort does not require access to $self, future rewrites of it may.

That said, I'd hesitate to call _topsecretsort a "private method". It is not a private method in the same sense that programming languages with true privacy would understand it. _topsecretsort can be called and overridden by superclasses, and by code entirely external to the class. I think the best term for this sort of sub would be an "undocumented method", not a "private method".

(In fact, getting back to whether the sub should be called as a function or as a method... the one advantage of calling the sub as a function instead of a method, would be that it would prevent superclasses from accidentally or deliberately overriding it.)

The best way to approximate true private methods in Perl is to use coderefs:

my $_topsecretsort = sub { my $self = shift; my ($x, $y) = @_; return 42; }; sub count_sorted_foobars { my $self = shift; my @results = $self->$_topsecretsort('foo', 'bar'); return scalar(@results); }

In Moops I've even created a shortcut for this pattern:

use Moops; class FooBar { method my $_topsecretsort ($x, $y) { return 42; } method count_sorted_foobars () { my @results = $self->$_topsecretsort('foo', 'bar'); return scalar(@results); } } say FooBar->new->count_sorted_foobars;
use Moops; class Cow :rw { has name => (default => 'Ermintrude') }; say Cow->new->name

In reply to Re: OOP private functions by tobyink
in thread OOP private functions by zeltus

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.