in reply to RFC: Practical closure example: Spreadsheet writer

Nice node, but why closures rather than light weight OO? Consider an OO variant of your first example:

use strict; use warnings; package Fruit; sub new { my ($class, $fruit) = @_; return bless {total => 0, fruit => $fruit}, $class; } sub Add { my ($self, $number) = @_; $self->{total} = $self->{total} + $number; return "$self->{total} $self->{fruit}" . ($self->{total} != 1 ? 's' + : ''); }; package main; my $apple = Fruit->new ('apple'); my $orange = Fruit->new ('orange'); print $apple->Add (1)."\n"; print $apple->Add (3)."\n"; print $orange->Add (1)."\n"; print $apple->Add (5)."\n"; print $orange->Add (1)."\n";

Prints:

1 apple 4 apples 1 orange 9 apples 2 oranges

Ok, a little more verbose, but now you can add more functionality to your fruit object by adding member functions or sub-classing Fruit.


DWIM is Perl's answer to Gödel

Replies are listed 'Best First'.
Re^2: RFC: Practical closure example: Spreadsheet writer
by clinton (Priest) on Aug 05, 2007 at 00:00 UTC
    Good point, and actually, while I was typing the node, I kept on writing $writer->write($value) rather than $writer->('write',$value). This made me ask myself the same question: why not OO?

    And really, no reason - I would say (and I stand under correction) that really it is just a question of scale. A small job may be more easily (less verbosely) achieved with closures, while OO gives you more room to expand. Also, I would guess that using references to anonymous subs avoids most of the penalty hit of using OO (micro-optimization anyone?).

    So I would say that it is probably a different technique to achieve the same thing.

    I'd be interested in differing opinions though

    Clint

      Also, I would guess that using references to anonymous subs avoids most of the penalty hit of using OO (micro-optimization anyone?).

      There may be a tiny benefit from avoiding potential dispatch lookup, but the benefit is fairly small. If anything, you're more likely to see memory savings (in the order of a few kilobytes). (Closures save the same CV but use different lexpads. If you reuse the closure, all references share the CV rather than constructing their own.)