Well, I'll have to think about a more elegant and efficient way, but so far I don't see any serious problem with what you are doing. Remember the saying "a sufficiently encapsulated hack is no longer a hack." The questions to ask are: "is this really causing efficiency problems?" and "is there a more maintainable solution?" If it suits your needs, don't fix it without good reason. This is a Bad Idea.

Elaborating: let's say you make this method 50% more efficient in terms of "time" (loosely speaking). If you find out that it's only taking up 1% of your programs runtime, you possibly have wasted time making a non-issue more performant. Further, I find for myself that when I start worrying about performance issues, even on systems I've built from the ground up, I almost always guess wrong about where the performance bottlenecks are (even the "obvious" database performance issues may be memory bound, IO bound or just bloody awful queries).

That being said, I would personally create a private $can_contain method.

my $can_contain = sub { my ( $self, $object ) = @_; $self->container_type eq $object->container; }; sub insert { my ( $self, $object ) = @_; unless ( $self->$can_contain( $object ) ) { die "I can't hold that object!"; } push @{$self}, $object; }

With private methods like that, you can be guaranteed that no on else will inherit them, no one outside of your class will see the data they don't need to see and if anything else in the method needs to know if it "can contain" something, you're safe.

Though I still wouldn't fix it until it merits the fix :)

Cheers,
Ovid

New address of my CGI Course.


In reply to Re: "polymorphism" hack: nuts or wise? by Ovid
in thread "polymorphism" hack: nuts or wise? by rvosa

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.