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

Re: Re: Tutorial: Introduction to Object-Oriented Programming

by jreades (Friar)
on Dec 11, 2002 at 18:25 UTC ( [id://219142]=note: print w/replies, xml ) Need Help??


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

Abigail-II, you make several pertinent points, but there are also a couple on which I'd like to hear a little more about your thinking before I make changes to the tutorial (which I'd be happy to do).

1. 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.

I was trying not to clutter the tutorial with any code that was not directly relevant to the OO aspects of the tutorial, so while I agree that all of these examples should use strict I was rather on the fence as to whether it would just be a distraction to the reader. Putting it the way you have makes me think I should stop being lazy with my examples.

2. 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.

3. 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.

4. I realized that I was contradicting myself by saying that an inheriting class should never call a super class' private methods and then structuring my calls so that they *could* in fact call an inherited class' private method first, but wasn't thinking about the consequences of that decision in the way that you outlined them and was just trying to stick to the OO-style as a way of reinforcing usage.

Anyway, I agree with you and I think that I will change my code to use subroutine calls rather than method calls as soon as I can.

5. Use a different language -- I know what you're getting at here, but I think that pretending OO features don't exist in Perl is only going to lead to people doing BAD THINGS when they eventually discover it. People may pick up some bad habits here and there, but for the most part they (and those who have to maintain their code) will benefit from this feature more than they will suffer.

Replies are listed 'Best First'.
Re: Tutorial: Introduction to Object-Oriented Programming
by Abigail-II (Bishop) on Dec 12, 2002 at 17:23 UTC
    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.

    Abigail

      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."

        Abigail

        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.

        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.

        --
        http://fruiture.de

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others browsing the Monastery: (4)
As of 2024-04-23 06:30 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found