Beefy Boxes and Bandwidth Generously Provided by pair Networks
Welcome to the Monastery

Re: Tutorial: Introduction to Object-Oriented Programming

by Abigail-II (Bishop)
on Dec 12, 2002 at 17:23 UTC ( [id://219378]=note: print w/replies, xml ) Need Help??

in reply to Re: Re: Tutorial: Introduction to Object-Oriented Programming
in thread Tutorial: Introduction to Object-Oriented Programming

I'm a little unclear as to whether you feel that I should simply have put in use strict in all my examples, or whether your are pointing out that using a hash_ref will not enable use strict to contribute much towards debugging, or both.
No, I'm wasn't saying you should use strict in your examples. That would be pointless drivel. I'm pointing out that if you use hash keys as attributes you will not benefit from using strict. But using strict is a good practise so why advocate a coding style that cannot benefit from it.
With respect to hiding (full encapsulation via anonymous subroutines) I feel quite strongly that this belongs in an advanced OO tutorial such as this one. I don't believe that throwing closures into the mix will help people learn the fundamentals of how objects work in Perl.
Where did I say full encapsulation can only be done with anonymous subroutines? Full encapsulation doesn't belong in an advanced tutorial. Full encapsulation is where you start. It's just like driving a car. Avoiding pedestrians isn't "advanced driving" - it's part of the basics. And you can get full (data) encapulation with techniques no more difficult that using hash references.
This ties into my feeling that, while hashes have their limitations, they are the easiest way to introduce someone to OO in Perl. Are they ideal? No. Are they less complicated than arrays or closures? Yes. Again, this was never meant to be the canonical OO tutorial, just an introduction.
Did I say you need to use arrays or closures? No. Do I think you can avoid the limitations I pointed out only by using arrays or closures instead of hashes? No. I'd still use hashes.

Here's how you can write the Quote class you used in your tutorial.

package Quote; use strict; use warnings; my (%phrase, %author, %approved); sub new { bless [] => shift; # Any reference will do. } sub set_phrase { my $self = shift; my $phrase = shift; $phrase {$self} = $phrase; } sub get_phrase { my $self = shift; return $phrase {$self}; } sub set_author { my $self = shift; my $author = shift; $author {$self} = $author; } sub get_author { my $self = shift; return $author {$self}; } sub is_approved { my $self = shift; @_ ? $approved {$self} = shift : $approved {$self}; } sub DESTROY { my $self = shift; delete $phrase {$self}; delete $author {$self}; delete $approved {$self}; }

Doesn't this remarkably look like your code? Perhaps my code is even simpler, I hardly use references - only the constructor returns a reference, but we don't care what it is, or how to put data in it (or to get something out of it). The only addition is the DESTROY function. But this code is using full encapsulation. Attributes cannot be trampled over. We're not enforcing our implementation on an inheriting class. We don't even care how an inherited class is implemented (if we are inherited, or we inherit something else, we don't need our constructor to be called - cool, isn't?)

I'm convinced this way of implementing classes is actually easier to learn, and less error-phrone than the traditional "just dump everything in the same place" way by using a hashref.


Replies are listed 'Best First'.
Re: Re: Tutorial: Introduction to Object-Oriented Programming
by BrowserUk (Patriarch) on Dec 12, 2002 at 18:47 UTC

    Abigail, your method of class construction is deceptively simple and (without trying it in anger) appears very robust.

    This is a bit like asking the vendor what is wrong with the house/car/London Bridge he is about to sell you, but

    Are there any weaknesses?

    If so, what are they?

    Okay you lot, get your wings on the left, halos on the right. It's one size fits all, and "No!", you can't have a different color.
    Pick up your cloud down the end and "Yes" if you get allocated a grey one they are a bit damp under foot, but someone has to get them.
    Get used to the wings fast cos its an 8 hour day...unless the Govenor calls for a cyclone or hurricane, in which case 16 hour shifts are mandatory.
    Just be grateful that you arrived just as the tornado season finished. Them buggers are real work.

      Are there any weaknesses?
      • As was pointed out, you need to take care of possibility someone subclass will implement stringification overload. A solution was proposed - alternatively, you can document that it's forbidden for a subclass to overload stringification if you don't want to pay the penalty. I think this isn't a major issue; overloading is used, but most objects don't.
      • You have to write a DESTROY method. You can't say that you can live with the memory leak - Perl does not garantee that if you create a reference, let it go out of scope, and then create a new reference, the new one will not have the same address as the first one.
      • Serialization might be a bit harder in some cases. But calling Serialize or Date::Dumper on an object won't work in general anyway. An object might have a reference to something, and a general serialization function cannot know whether the reference needs to be shared with something else.
      • You can't use the standard Class::MethodMaker. But that doesn't mean you can't have a module giving you the same functionality. I've written a proof of concept Class::MethodMaker::InsideOut (not released) giving the same functionality as Class::MethodMaker for Inside Out objects. It'll can even do the DESTROY function and the declaration of hashes. It's using a source filter. Alternatively, you could use our to declare the attribute hashes, and write a module with the same functionality as Class::MethodMaker.
      • If you have a large class, you may want to split it over more than one file. If your attribute hashes are lexical, this will not work. Again, you could use a source filter to merge the files, or declare the attribute hashes with our.
      Just in case you are saying that making the attribute hashes package variables makes that someone else can access your attributes, that's ok. I'm not advocating my technique such that you cannot get to the attributes, I want to prevent accidents. After all: "It would prefer that you stayed out of its living room because you weren't invited, not because it has a shotgun."


        Thanks Abigail.

        And no. I had no insights as to any of the limitations.

        Until now I have had no real use for OO in my exploration of Perl, so i have basically avoided it. I have now started something that would benefit from OO which happens to coincide with this thread and your post.

        I read a couple of earlier peices on light-weight/inside-out objects, as well as several peices by you and others on the merits of OO in perl, so I just wanted to know what I was getting into. You can see my first attempt as using your method at (my?) problem with re-blessed references(?) though if your interested you'd better look at adrianh's correction of my idiocies at Re: Re: (my?) problem with re-blessed references(?).

        I'd be interested to hear your thoughts on using lvalue subs for the accessor/mutators? I've long prefered the syntax of one subname per attribute that returns the value optionally setting it if a value is passed. I hated the whole "should it be set_x/put_x or set_x/get_x debate" that rages still in the Java discussion groups. Another totally pointless, "religious-type", waste of time IMO. I also hate having to look up which convention is used for every attribute of every class I use.

        The lvalue sub seems to me to be the logical conclusion to this. One attribute, one name. Name it to use it. Assign to it to set it. In-line assign and use just like any other var. Makes perfect sense to me, but I'm sure that others have a different opinion.

        Examine what is said, not who speaks.

      Abigail-II will be better able to comment than myself, but I've been playing around with her technique on-and-off since I discovered it on perlmonks. While I've not been doing it in anger, it's not been entirely in jest either. I've been re-writing some Test::Class hierarchies that were fairly deep, and hence possible sources for hash key clashes.

      In general I've not had problems. It's a very nice hack to get around perl's lack of object attribute encapsulation. I'll probably use the technique in the next production project I do.

      Abigail-II - have you considered writing a little tutorial on the subject? :-)

      Issues that can cause problems:

      • You have to take overloading the "" operator into account. Since the attribute objects are indexed by "$self", you have to use overload::StrVal something like this:

        package Foo; use strict; use warnings; use overload; my %foo = (); sub new { my $class = shift; bless [], $class; }; sub foo { my $self = overload::StrVal shift; $foo{$self} = @_ if @_; $foo{$self}; }; sub DESTROY { my $self = overload::StrVal shift; delete $foo{$self}; };

        if there is any chance that somebody will write a sub-class that overrides "", for example:

        package Foo::Pretty; use base qw(Foo); use overload q{""} => sub { my $self = shift; my $foo = defined($self->foo) ? $self->foo : 'unde +f'; "<foo=$foo>"; }, ;
      • Having to remember to add/remove attribute hashes from the DESTROY method can be a pain. I tend to move attributes around classes a fair bit during refactoring. Forget to add an appropriate delete line to the DESTROY method and you suddenly have a nasty little memory leak. I've had this happen to me more often in the few weeks I've been playing with this technique than I've had hash/method name clashes in the several years I've been writing OO perl - but that may be lack of practice :-)

      • Object serialisation and other reflective acts become harder. No more quick'n'dirty throwing your object at Storable to serialise your object. No more throwing your object at Data::Dumper to get a snapshot of its state. This could be considered a feature depending on your point of view.

      • I've not had the chance to try teaching this method to perl/OO novices. My hunch is that it will turn out harder than hashes. Perl novices are already used to stuffing stuff in hashes, so it's a natural progression. OO novices latch onto the idea that an object is a "thing". My guess is that a single "thing" spread over several hashes goes against the naive concept of what an object is, and will therefore be harder to teach.

      • Having to list all of the attributes in the DESTROY method, as well as declare them at the top offends my sense of once and only once.

        Another issue has just come to mind. With the object attributes being keyed on "$self", which includes the name of the class, you can no longer bless an object into a sibling class to implement state transitions.

        Again, I guess some people would consider this a feature. I quite like the technique myself :-)

        To overcome you'll need to strip out the class name. Assuming nobody changes the output format of references in later perl versions something like this should work.

        package Foo; use strict; use warnings; use overload; my %foo = (); my %self = (); # we access self enough for it to be worth caching sub self { my $self = overload::StrVal shift; return $self{$self} if exists $self{$self}; $self{$self} = substr($self, index($self, '=')+1); }; sub new { my $class = shift; bless [], $class; }; sub foo { my $self = shift->self; $foo{$self} = @_ if @_; $foo{$self}; }; sub DESTROY { my $self = shift->self; delete $foo{$self}; undef %self; };

        Also, there is another advantage to Abigail-II's method. Storing the attributes in separate hashes should less expensive in memory - buckets cost less than hashes. Might make a difference if you're creating lots of objects.

      Although this is not a disadvantage, rather a reason to do it like Abigail proposes: You _will_ break things (and have subtle bugs to find) if you don't stick to documented accessor/mutator methods. Especially when you write a base class for all your classes that organizes a registry of all members of all instances(based on caller()), you'll see that if you write accessor methods for the same member with different names in two related classes, you assign different members, which is great but you probably didn't expect it because it has become a habit to have it work differently.


        Sorry fruiture, could you explain your point a bit more.

        I have read your post 3 times and keep wanting to react to it, but I'm sure I'm missing the salient point.

        I get lost right around "...a registry of all members of all instances...". Don't all members of a given class have the same members? And isn't the point of OO that one class should not know (nor care) what members another class has, related or not.

        I know C++ has that "freind" declaration, but I think even Stroustrup admitted afterwards that the whole private/protected/friend/public/static stuff was a mistake.

        "'ll see that if you write accessor methods for the same member with different names in two related classes..."

        How can you have "the same member" in "two ... classes", related or not?

        Okay you lot, get your wings on the left, halos on the right. It's one size fits all, and "No!", you can't have a different color.
        Pick up your cloud down the end and "Yes" if you get allocated a grey one they are a bit damp under foot, but someone has to get them.
        Get used to the wings fast cos its an 8 hour day...unless the Govenor calls for a cyclone or hurricane, in which case 16 hour shifts are mandatory.
        Just be grateful that you arrived just as the tornado season finished. Them buggers are real work.

Log In?

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

How do I use this?Last hourOther CB clients
Other Users?
Others perusing the Monastery: (5)
As of 2024-07-18 19:42 GMT
Find Nodes?
    Voting Booth?

    No recent polls found

    erzuuli‥ 🛈The London Perl and Raku Workshop takes place on 26th Oct 2024. If your company depends on Perl, please consider sponsoring and/or attending.