develooper Front page | perl.perl5.porters | Postings from March 2011

Re: Revising Perl's OO docs - a new OO tutorial

Thread Previous | Thread Next
From:
Johan Vromans
Date:
March 8, 2011 23:38
Subject:
Re: Revising Perl's OO docs - a new OO tutorial
Message ID:
m21v2gbv5t.fsf@phoenix.squirrel.nl
"David E. Wheeler" <david@kineticode.com> writes:

> Object::Tiny accessors are read-only, however. This may be intepreted
> as a feature, of course.

Yes. A feature that makes it use extremely limited and invites people to
use the internal structure.

    package Foo;
    use Object::Tiny qw{ bar baz };

    package main;
    my $object = Foo->new( bar => 1 );
    print "bar is " . $object->bar . "\n";

    $object->bar(2);    # doesn't do anything, doesn't complain either

    # Oh, I need this just once :)
    $object->{bar} = 2;

There's just a thin grey area between 'too limited' and 'too powerful'.

What becomes apparent is that there's a need for a simple and useful
struct builder.

A hash (or has ref) can do, but it is too liberate:

  my $obj = {};
  $obj->{foo} = 2;
  say $obj->{foo};
  $obj->{Foo} = 2;      # typo
  say $obj->{foo};      # hard to find error

Turning this into a straightforward struct builder saves typing of some
braces and protects against typos:

  my $obj = Struct qw(foo bar);
  $obj->foo = 2;
  $obj->foo(2);         # equivalent to the above
  say $obj->foo;
  $obj->Foo = 2;        # runtime error

This would suffice for a simple struct builder.

A possible extension: some form of type checking:

  my $obj = Struct qw( foo => '$', bar => '@' );

This is what Class::Struct does (except from the lvalue part).

I wonder whether the checking should be on type, or on content:

  my $obj = Struct qw( foo => 'i', bar => 's' );
  $obj->foo = 2;
  say $obj->foo;
  $obj->foo = 'bar';        # error: not an integer

Note that this is not really different from option value checking in the
style of Getopt::Long.

I think this is where a simple struct builder should end. Anything else
(more powerful accessors, logic, inheritance) should enter the realm of
class builders.

-- Johan

Thread Previous | Thread Next


nntp.perl.org: Perl Programming lists via nntp and http.
Comments to Ask Bjørn Hansen at ask@perl.org | Group listing | About