[ABE.pm] Accessing parameters in OOP

Ricardo SIGNES rjbs-perl-abe at lists.manxome.org
Wed Jan 10 05:19:16 PST 2007


* "Faber J. Fedor" <faber at linuxnj.com> [2007-01-09T22:09:00]
> I just went throughthe 2006 archives looking for an OOP thread to
> refresh my fuzzy memory and I couldn't find it, so I'll ask again.
> 
> Internally, I access the object's internal data like this:
> 
>     $where = "where name = $self->{name} " ;
> 
> IIRC, this is A Bad Thing, right?  

Right.  It means that if later you decide that an object's name is computed,
you have to go change verything that did that, for example.

> Do I write an method like 
> 
>     sub name {
>         my $self = shift;
>         if (@_) {
>             $self->{name} = lc(shift);
>         }
>         return $self->{name};
>     }

That looks reasonable.

> and then call it like this
> 
>     $where = "where name = name() " ;
> 
> or maybe 
> 
>     $where = "where name = ". name() ;

The first one wouldn't interpolate (only the three basic data types do, and
hashes only do if you're subscriping them).  The second one would fail,
beacuse, as you wonder:

> How does the object know which name() to look for?

It wouldn't.  You need to give it an invocant:

  $where = "where name = " . $self->name;

> And another thing, if I'm inside my object and I call another function
> inside my object, why do I explicitly have to pass $self?  Why isn't it
> automagically passed in like it is with name() above?

Because it isn't in your name() example, either!  Routines defined in classes
are not special, because perl doesn't know what package is a class and what
isn't.  It decides whether you're calling a method or routine based on whether
you called "whatever()" or "$invocant->whatever()"

If you write code inside your class and that routine expects an object as the
first argument, it should be called as a method.  If you write code in your
class that doesn't take the object as the first argument, that is probably a
mistake.

-- 
rjbs
> 
> 
> -- 
>  
> Regards,
>  
> Faber Fedor
> President
> Linux New Jersey, Inc.
> 908-320-0357
> 800-706-0701
> 
> http://www.linuxnj.com
> 
> 
> 
> _______________________________________________
> ABE-pm mailing list
> ABE-pm at pm.org
> http://mail.pm.org/mailman/listinfo/abe-pm
> 


More information about the ABE-pm mailing list