Absolutely having class methods/data is ok.

This does not break encapsulation. You're simply calling the method on the class, instead of an instance (object) of the class.

This in fact is quite common. Imagine you have a class that counts its objects. The count variable would be a class var, and you could just write a class method that returns that value. Note here that when writing class methods, you have to realize that the first param will be the module name, not a blessed instance, so you won't have $self to operate on.

Class methods don't break encapsulation, and if you ever changed $count, you'd refactor the class method to return the right thing, instead of changing scripts that reference $Module::count directly.

Class methods also provide you the ability to do things with a module without having to instantiate a new object:

sub new { return bless {}, shift; } sub add { shift; # throw away object/class; not needed my ($x, $y) = @_; return $x + $y; }

Now you can add() in either of these ways:

my $res = Module->add(1, 2); # or my $obj = Module->new; my $res = $obj->add(1, 2); # or even my $mod = 'Module'; my $res = $mod->add(1, 2);

I use the latter form of calling class methods in my unit tests, especially when creating numerous objects within the same test file:

my $mod = 'My::Long::Module::Name'; { # test 1 my $obj = $mod->new; } { # test 2 my $obj = $mod->new; } # etc

In reply to Re^3: Passing the logger's object (updated) by stevieb
in thread Passing the logger's object by v_melnik

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.