Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl Monk, Perl Meditation
 
PerlMonks  

Re^6: The future of Perl?

by Your Mother (Archbishop)
on Dec 14, 2014 at 20:26 UTC ( [id://1110328]=note: print w/replies, xml ) Need Help??


in reply to Re^5: The future of Perl?
in thread The future of Perl?

That's a great question and that’s graceful code from Ruby. We can do similar several different ways in Perl including tying an array, using an array as the object, minimal OO harnessing like Class::Accessor, or even a code ref. This kind of problem strikes me as a good candidate for a code ref. But that's not the topic :P so here are three different ways to do it. All are more verbose than the Ruby; and the least verbose of them (array object) is probably confusingly terse/unusual to most Perl hackers. The last two are FIFO, not FIFI in the example and the third is a hard fixed queue in that its length never changes. It hold undef in “empty” slots. Putting packages in <readmore/> since it’s longish–

use 5.16.2; package fQ_moonimal { use Moo; use overload '""' => sub { join $", @{+shift->items} }; has size => is => "ro", default => sub { 10 }, isa => sub { die "size must be a positive integer" unless $_[0] > 0 }; has items => is => "ro", init_arg => undef, default => sub { [] }; sub push { my ( $self, $item ) = @_; push @{$self->items}, $item; pop @{$self->items} if @{$self->items} > $self->size; } sub pop { pop @{+shift->items}; } }; package fQ_moofancy { use Moo; use MooX::HandlesVia; use MooX::late; use overload '""' => sub { join $", +shift->all }; # More are avaialbe. my @methods = qw/ push pop count all shift unshift natatime /; has size => is => "ro", required => 1, isa => sub { die "size must be a positive integer" unless $_[0] and $_[0] > 0 }; has items => is => "ro", init_args => undef, traits => ["Array"], handles => { map { $_ => $_ } @methods }, default => sub { [] }; after "push" => sub { my $self = shift; $self->shift until $self->size >= $self->count; }; after "unshift" => sub { my $self = shift; $self->pop until $self->size >= $self->count; }; sub BUILDARGS { my $class = shift; my $size = shift; die "Only one argument allowed: size" if @_; { size => $size }; } }; package fQ_FIXED { use overload '""' => sub { join $", map $_ || "_", @{+shift} }; sub new { bless [ (undef) x $_[1] ], __PACKAGE__ } sub push { my $self = shift; push @{$self}, shift; shift @{$self}; } sub pop { my $self = shift; unshift @{$self}, undef; pop @{$self}; } };

Some sample code with them and output.

eval { fQ_moofancy->new } or say $@; my $foo = fQ_moonimal->new(size => 3); my $fooncy = fQ_moofancy->new(3); my $fixed = fQ_FIXED->new(3); for ( 1 .. 5 ) { say " foo -> $foo"; say "fooncy -> $fooncy"; say " fixed -> $fixed"; $foo->push($_); $fooncy->push($_); $fixed->push($_); } __END__ isa check for "size" failed: size must be a positive integer at… foo -> fooncy -> fixed -> _ _ _ foo -> 1 fooncy -> 1 fixed -> _ _ 1 foo -> 1 2 fooncy -> 1 2 fixed -> _ 1 2 foo -> 1 2 3 fooncy -> 1 2 3 fixed -> 1 2 3 foo -> 1 2 3 fooncy -> 2 3 4 fixed -> 2 3 4

I have no doubt there are other, likely cleaner approaches. I was winging it, first drafts, all that sort of caveat.

Replies are listed 'Best First'.
Re^7: The future of Perl?
by Arunbear (Prior) on Dec 15, 2014 at 15:27 UTC

    As Lao Tzu might have said: The API that exposes inner workings is not the true API.

    Users of the queue shouldn't need to know that there's an array inside that holds the items, yet the Moo(se) examples all expose this at API level.

    The real point of the Ruby example is to show that in Ruby (also Python and Java) you aren't compelled to

    • expose an object's internals via an API
    • use a function call to get/set an attribute from inside the class

    Of course the examples that used vanilla Perl OO don't suffer from this problem, but given that Moo(se) inevitably leads to loss of Encapsulation, it can't really be considered as providing superior OOP.

      Exactly!

      Perhaps even worse, in my experience (though it took quite a while for me to fully understand how these problems were being encouraged by the same practice), the focus on accessor generation and constructors that expose attributes (and for adding other functionality with a focus on decorating accessors with before/after/around wrappers) leads to OO design that is focused on attributes first, inheritance second, and interfaces a very distant third. This leads to designs that scale over time much less well (based on my experience with quite a few concrete such designs over multi-year lifespans).

      The correct priority to use when doing OO design is interface first, attributes a distant second, and inheritance not at all.

      Your new best practices need to refine your old best practices not thwart them. Don't adopt OO practices that go against the more basic best practice of encapsulation (narrow interfaces, data hiding).

      Also, data types are of profound importance if you are stuck programming with interfaces using positional parameters. But they quite suck in many ways if you aren't stuck in that way. But I think I'll skip the long rant on that part of the topic at this time.

      - tye        

      I guess…? I’ve never shared the concern for closed, hidden OO mechanics and I might not even understand your distinction between API and native functionality. Seems academic. We do these things inside the class to prevent typo bugs and leave the “API” open and integral for the other classes that might be concerned. Inside out objects and closures (which is how I would have done the queue to begin with) are possible of course. The point of the quote wasn’t that Perl is the best vanilla OO (the Ruby example is nicer than the most simplistic/direct/synonymous Perl recipes) it was: roles, mixins, coercions, traits, class methods, dispatch, lazy creation, setter/getter/clearer/predicate/builder shorcuts, typing, after, before, around, overriding, non-overriding additions, resolution order, contract style requires, MOP, on the fly generation, etc. :P

        By exposing the 'items' attribute via a method, you are telling users of the class that they can use it like this:
        6:06% reply -I . 0> use fQ_moonimal; 1> my $q = fQ_moonimal->new(size => 3); $res[0] = bless( { 'items' => [], 'size' => 3 }, 'fQ_moonimal' ) 2> $q->push(2); $res[1] = '' 3> $q->push(3); $res[2] = '' 4> $q->push(5); $res[3] = '' 5> $q $res[4] = bless( { 'items' => [ 2, 3, 5 ], 'size' => 3 }, 'fQ_moonimal' ) 6> push @{ $q->items }, 7, 11, 13; $res[5] = 6 7> $q $res[6] = bless( { 'items' => [ 2, 3, 5, 7, 11, 13 ], 'size' => 3 }, 'fQ_moonimal' ) 8>
        So this version of the queue is not really fixed size. Encapsulation is one of the main motivations for doing OOP in the first place, and giving it up to get feature $X doesn't amount to superior OOP.
Re^7: The future of Perl?
by BrowserUk (Patriarch) on Dec 14, 2014 at 21:07 UTC

    I see little or no benefit of any of those over a bog standard perl 5 OO implementation:

    package FixedSizeQueue { sub new { my( $class, $size ) = @_; bless { max_size => $size, items => [], }, $class; } sub pop { my $self = shift; pop @{ $self->{ items } }; } sub push { my( $self, $item ) = @_; shift @{ $self->{ items } } if @{ $self->{ items } } == $self- +>{ max_size }; push @{ $self->{ items } }, $item; } 1; }; __END__ [0] Perl> $Q = FixedSizeQueue->new( 3 );; [0] Perl> $Q->push( 2 );; [0] Perl> $Q->push( 3 );; [0] Perl> $Q->push( 5 );; [0] Perl> pp $Q;; bless({ items => [2, 3, 5], max_size => 3 }, "FixedSizeQueue") [0] Perl> $Q->push( 7 );; [0] Perl> pp $Q;; bless({ items => [3, 5, 7], max_size => 3 }, "FixedSizeQueue") [0] Perl> pp %FixedSizeQueue::;; ( "new", *FixedSizeQueue::new, "push", *FixedSizeQueue::push, "import", *FixedSizeQueue::import, "pop", *FixedSizeQueue::pop, )

    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.

      We lose some error checking and ability to use it as role or put type checks or coercion (none of which I did either but some of it would be a one or two line addition) but I agree at this level. I’m not against plain old OOP and I’m not an OO fanatic.

      Traits do bring a lot more power than push/pop (see Data::Perl::Role::Collection::Array or Moose::Meta::Attribute::Native::Trait::Array) and handles is a super convenient way to expose functionality of subobject or trait/attribute to the parent in semantically pleasing ways; for example a web spider object would have a user agent but it would be pleasant to have $spider->get instead of having to write $spider->user_agent->get. All still pretty trivial examples and ultimately all the MOP stuff is about shortcuts and sensible building blocks and techniques for distinguishing and mixing them for things that are just plain Perl underneath that anyone could do anyway. The bare bones mop that may come into the core in 5.24 or something is an example of how little agreement there is on which features are crucial and which are in the way.

        We lose some error checking and ability to use it as role or put type checks or coercion (none of which I did either but some of it would be a one or two line addition)

        Any errors will be checked when the underlying array operations are performed. And the messages will be concise and informative.

        Unlike those that Moose produces!

        for example a web spider object would have a user agent but it would be pleasant to have $spider->get instead of having to write $spider->user_agent->get

        But, that can be done in one line with no modules:

        package Spider; ... *get = *{ $self->ua->get }; ...
        The bare bones mop that may come into the core in 5.24 or something is an example of how little agreement there is on which features are crucial and which are in the way.

        Oh Dog! If Perl core starts coming with a MOP; then I sure hope that they also provide a compile-time -DBukIt to throw it away.

        I mean, what good is a MOP without a BukIt :)


        With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
        Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
        "Science is about questioning the status quo. Questioning authority".
        In the absence of evidence, opinion is indistinguishable from prejudice.

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1110328]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others musing on the Monastery: (3)
As of 2024-04-20 01:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found