Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic
 
PerlMonks  

Re: Re: Re: Re: Reducing Perl OO boilerplate

by flyingmoose (Priest)
on Feb 18, 2004 at 15:12 UTC ( [id://329927]=note: print w/replies, xml ) Need Help??


in reply to Re: Re: Re: Reducing Perl OO boilerplate
in thread Reducing Perl OO boilerplate

Ok, I'll make up an example to explain why I'd like named parameters...pardon syntax errors, this is all untested. There *will* be syntax errors. Also, please don't study my problem space too much, as I'm just coding up a random example out of my head. I'm not actually coding a Chess program -- it's a generic question. You should see, though, from this example that I am not going after "HashesThatDoStuff", exactly, but rather something else stylistically.

Rationale for named parameters -- One of the things I often don't like about OO sometimes is that parameter order matters. When folks put more than a few methods in a constructor, it's rarely obvious which is which. So named parameters (as in, say, Python? Others?) allow the code to be a bit more readable.

my $board = ChessBoard->new('start'); my $game = GameState->new( -white => ChessPlayer->new( -board => $board, -controller => Human->new( -name => 'Larry', -coffee => 1, ), ), -black => ChessPlayer->new( -board => $board, -controller => Computer->new( -level => 5, -ply => 3, -timecap => 60, -style => 'Nimzovitch', ), ), -board => $board, -rules => new ChessRules('suicide'), );

In the above example, timecap, ply, and level are all numbers, but I can easily tell them apart by the names, without having to know the order of the parameters as required. If I get the order wrong, it won't matter.

I'll admit the example above is contrived (I wouldn't normally construct my entire object model in one statement), but it shows what I'm getting at.

My OP question was, essentially, what are better ways to implement the above goal in Perl? How can we do this without creating mammoth constructors, yet still support inheritance and so on? MethodMaker will go a ways to keeping from writing accessor boilerplate and variable declarations, but constructors...that's the hardest part to keep elegant.

Thanks to everyone for the help and insight though. This is very good help for someone who is experienced in OO but still not quite getting it to come out elegantly in Perl. Appreciate it.

Replies are listed 'Best First'.
Re: Re: Re: Re: Re: Reducing Perl OO boilerplate
by dragonchild (Archbishop) on Feb 18, 2004 at 19:13 UTC
    You're mixing concepts. How you pass the parameters to the constructor is completely orthogonal to how you create the object. In Perl, a constructor is just another function. Its first parameter is either the classname or the blessed reference that called the method. The rest of @_ are the parameters passed to the constructor. The only thing a constructor is usually expected to return is a blessed reference to something (or undef, if an error was encountered). IT DOESN'T HAVE TO BE THE SAME CLASS. For example, DBI doesn't return an object blessed into the DBI class.

    Mammoth constructors have absolutely nothing to do with inheritance. Inheritance is, for all practical purposes, determined when using the two-part form of bless. Nothing more, nothing less. Here's an example:

    package Foo; sub new { my $class = shift; my %options = @_; my $self = {}; # Do 1000 lines of stuff with %options return bless $self, $class; } package Bar; use base 'Foo'; # A bunch of stuff goes here, but NO new() method! package main; my $object = Bar->new( # A bunch of named parameters go here );

    Named parameters, inheritance, and a bunch of stuff in a constructor. No sweat.

    Now, if you wanted to have all your objects use a very basic constructor, let me show you the basics of what I do:

    package My::Base::Class; sub new { my $class = shift; my $self = bless {}, $class; (@_ % 2) && die "Odd number of parameters passed to new()"; my %options = @_; while (my ($k, $v) = each %options) { next unless $self->can($k); $self->$k($v); } return $self; }

    I assume that a mutator has been created with the same name as the parameter being passed in and that you want to assign the value to the attribute corresponding to the mutator. Very simple, very easy ... no fuss - no muss. If everything inherits from My::Base::Class, then everything gets that constructor. Named parameters, inheritance, and no boilerplate constructor.

    Now, you're going to want more flexibility than that, so you might create an init() hook. You might auto-generate mutators based on a method call at compile time. There's all sorts of sugar you can add to this. But, at the heart, this is all you really need.

    ------
    We are the carpenters and bricklayers of the Information Age.

    Please remember that I'm crufty and crochety. All opinions are purely mine and all code is untested, unless otherwise specified.

      Mammoth constructors have absolutely nothing to do with inheritance. Inheritance is, for all practical purposes, determined when using the two-part form of bless. Nothing more, nothing less. Here's an example:

      No offense, but when I mix concepts, I *mean* to mix concepts :) I don't need the CS 1 / CS 2 intro to OO class. I could teach the class (just not in Perl). Perl's OO syntax isn't pure as it should be (yet), so it takes some effort to figure out the idioms -- which has never been the case in any other language supporting OO that I've picked up.

      But yes, the init hook suggested in the above replies (especially Class::Method_Maker) is what I want. Java and C++ can make use of super constructors, the init hook is exactly what I was asking about, as my named parameter implementation as the OP (sans init hook), had a few glitches that would not provide the things init() provides.

      Essentially my requirements were three-fold: (A) keep the code clean (solved: MethodMaker), (B) No long mamoth constructors, so named params help (solved: hash), (C) need instructors to benefit from inheritance (solved: init hook). Success. However arriving at this was an experience!

Log In?
Username:
Password:

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

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

    No recent polls found