Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

perl OO - to use or not to use

by kiat (Vicar)
on Sep 14, 2003 at 11:40 UTC ( #291379=perlquestion: print w/ replies, xml ) Need Help??
kiat has asked for the wisdom of the Perl Monks concerning the following question:

Hi Monks,

I've read the replies to questions posed on or related OO perl. In fact, I've asked a question on OO perl vs proceduarl perl myself a while back. Hence, I was a little hesitant with this writeup but I would really like to hear your views on the followng:

1) Are there instances where OO perl is the only choice?

2) Say you've written a pretty large program written mostly in proceduaral perl. Can you easily re-write that program in OO perl later if you choose to?

3) Does anybody have any idea how perl 6's implementation of OO perl is going to be like? If so, is it going to be differnt from the current implementation?

Thanks in anticipation :)

kiat

Comment on perl OO - to use or not to use
Re: perl OO - to use or not to use
by adrianh (Chancellor) on Sep 14, 2003 at 13:14 UTC
    Are there instances where OO perl is the only choice?

    Not really. You can always write a piece of procedural code that will do the same thing as a piece of OO code.

    However, there are many times when OO is a sensible choice. For example if you've got an existing OO system that needs extending, or an OO framework that matches your application.

    Personally I find an OO approach makes most non-trivial applications simpler to develop - but this edges onto religious argument territory.

    You may find Damian Conway's ten rules for when to use OO of interest.

    Say you've written a pretty large program written mostly in proceduaral perl. Can you easily re-write that program in OO perl later if you choose to?

    Depends. Often not. Procedural code often tends to separate data and the processes applied to that data. OO tends to do the opposite.

    It is possible of course, but may be non-trivial.

    Does anybody have any idea how perl 6's implementation of OO perl is going to be like? If so, is it going to be differnt from the current implementation?

    Yes it will be different. We won't know the details until the next Apocalypse comes out. Reading the other Apocalypses gives some hints. At the very least we will see:

    • Classes as first class objects
    • Multi-methods
    • Decent encapsulation of attributes and code

    Probably a lot more.

    As I understand it the old Perl 5 style object system will still be usable, but the newer structures offer considerably more flexibility.

      Procedural code often tends to separate data and the processes applied to that data. OO tends to do the opposite.

      Often procedural code is written in pseudo-OO style. I.e when you see a lot of subs with signatures like

      sub do1($datastructure1, ..) sub do2($datastructure1, ..) sub do3($datastructure1, ..) sub do4($datastructure2, ..) sub do5($datastructure2, ..) sub do6($datastructure2, ..)
      It is relatively easily to convert to OO code. You put all subs which work on same data structures in same classes and then you apply various refactorings(like this, this and this) to get more ideomatic OO code.

      --
      Ilya Martynov, ilya@iponweb.net
      CTO IPonWEB (UK) Ltd
      Quality Perl Programming and Unix Support UK managed @ offshore prices - http://www.iponweb.net
      Personal website - http://martynov.org

        Wouldn't the example you mentioned be considered OO programming anyways? I mean, it does the exact same thing as 'traditional' OO programming, it just has a slightly different form. Do we have to have a 'class' and then create an 'object' and then call a method on the object by using specialized syntax? Why would this: $obj->meth(); be considered OO and this meth($obj) not be?
Re: perl OO - to use or not to use
by Anonymous Monk on Sep 14, 2003 at 21:32 UTC
    1) Are there instances where OO perl is the only choice?

    only when such is required by your instructor / management ;)

    2) Say you've written a pretty large program written mostly in proceduaral perl. Can you easily re-write that program in OO perl later if you choose to?

    this would depend on how your code was structured originally. if you tend to code in a procedural language with an OO style, the conversion shouldn't be too hard. even most 'proper' procedural code shouldn't prove too difficult to convert if its all broken down cleanly.

    3) Does anybody have any idea how perl 6's implementation of OO perl is going to be like? If so, is it going to be differnt from the current implementation?

    Give "Perl 6 Essentials" a whirl ( O'Reilly, ISBN 0596004990) .. the content is nothing you can't find online already, but its nicely presented and will answer this and most any other question regarding how perl 6 is shaping up. in general, perl 6 is going to be more OO at the core ( moving several steps closer to languages like Ruby ) but whether or not you take advantage of the increased OOpiness will be up to you ( moving several steps closer to being the same perl we know ( and possibly love ) )
Re: perl OO - to use or not to use
by graff (Chancellor) on Sep 14, 2003 at 21:57 UTC
    1) Are there instances where OO perl is the only choice?

    No -- just as there are no instances where perl itself is the only choice. But there are cases where programmers are much better off using OO perl, as evidenced by the many OO-style CPAN modules that have become essential tools in many a perl coder's daily activities. While a number of posts here (including some of mine) have defended the legitimacy of procedural coding and carped against "OO or die!" fetishists, there's no denying that OO should be the preferred approach for many tasks.

    2) Say you've written a pretty large program written mostly in proceduaral perl. Can you easily re-write that program in OO perl later if you choose to?

    Maybe a more pertinent question might be "can you write an app using just procedural syntax and structure, but do it in such a way that it could look like (and could be transformed pretty easily into) a `real' OO design?" Well, yes, sort of; to start with, use strict, and don't use any global variables; as you find that you need some set of subroutines that all manipulate the same data in various ways, group those subs together in one file (or inside a set of curly braces), and put the data in there with them. This is the start of building an object -- all it needs is a package statement at the top (to declare a name space), and a sub called "new" that includes a "bless" statement, and presto, it's an object. (Well, there might be a little more to it than that, but not much.)

    update: I keep forgetting about inheritance! This is something that really does come in very handy in a number of cases, and I can't imagine any way of doing it properly with just procedural tools. As I see it, this is the one thing that really sets OO design apart -- and to very good effect, because the only alternatives in a non-OO approach are not at all attractive.

    3) Does anybody have any idea how perl 6's implementation of OO perl is going to be like? If so, is it going to be differnt from the current implementation?

    So, you haven't internalized perl5's OO syntax yet (well, neither have I, really -- I still have to look up examples and man pages and Damian's beautiful OO book on those occasions when I want to make an OO module). And you're wondering if this stuff will be easier in perl6, so that maybe you should wait and not waste your time learning a soon-to-be-obsolete syntax...

    Don't wait. Learn it now, with the syntax as it is. When perl6 comes out (I haven't heard anyone holding their breath...), it's design will be intended, in part, to implement all the functionality and concepts available in perl5, and then some; it will also be intended to provide a smooth and relatively painless transition out of perl5 syntax. So getting to know the OO landscape, even with the not-so-sporty vehicle of perl5, will be time well spent.

Re: perl OO - to use or not to use
by leriksen (Curate) on Sep 15, 2003 at 05:22 UTC
    A few questions I like to ask myself when deciding on the split between procedural and OO
    • how many classes am I likely to write - if it is < 3 perhaps procedural is better
    • are there obvious inheritance relationships - '... and this report is just like that one, except that it doesn't have a totals section' - if there are, OO seems a stronger approach
    • what are the odds of the original code needing several changes/additions in future - would small objects help make these changes easier to introduce
    • would an object acting out a pattern of behaviour make the code easier to use/develop - e.g. I like to model processing record-based files with an iterator like pattern
      while (defined (my $record = $file_object->next()) { # next creates a +record object from data in the file $records->process(); }
    • do I need flexibility in applying my objects ? Will this be easier/clearer in OO or procedural ? e.g.
      # OO $object->fold()->spindle()->mutilate(); #procedural my $rc = mutilate(spindle(fold($data)));
    • if you have the knowledge - are patterns (ala GoF) going to help - these well-known solutions generally seem better in OO contexts, but that is not always so
    • how many methods will these classes have - perhaps lots of single function objects would be better as a library of functions - unless these classes are overriding specific portions of a parent class (specialising their interface)

    there are no hard-and-fast rules - except that the more experience and knowledge you have, the better your decisions will be. So, in the beginning, you can expect to make bad decisions - but as long as you view them as learning examples, then making them can be seen as encouraging.
      This may just be my take on the world, but I haven't yet found a non-trivial application that would be better written in procedural vs. OO. (OO vs. functional is an interesting debate, but I'm still trying to figure out where pure procedural is indicated.)

      Now, I do tend to write a lot of scripts, like CGI scripts. The script itself is procedural, but it will use a lot of objects. Let's face it - a non-trivial web app is going to have a lot of similar functionality in each one of its scripts. The following is an incomplete list:

      • database connectivity
      • template usage
      • parameter validation
      • business rules

      As such, those make sense to be put into objects. Some would say modules work just as well, but I always seem to run into the "Widgets are just like gizmos, except for ..." situation. Or, I do a lot of factoring, for which abstract base classes are eminently suited. So, I almost always start my designs with an OO flavor, tossing in functional and procedural as needed.

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

      The idea is a little like C++ templates, except not quite so brain-meltingly complicated. -- TheDamian, Exegesis 6

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

        To some extent I agree with you - very few non-trivial applications are easier/better in procedural vs OO (and I agree with you on the functional approach too - but just try writting a useful Haskell version of a nontrivial app - sheesh!!). It just depends on how wide your values for non-trivial are :-)
        I find I use procedural approach heavily in the startup of an app development, and once that is humming, focus on the OO from then on. E.g. I usually focus procedurally during the startup of my app on
        • reading parameters (using Getopt::Long exclusively)
        • setting up logging (using Log::Log4perl exclusively)
        • setting up filehandles (using IO::File exclusively)
        • setting up timing/stats
        • when required, setting up DBI (using DBI)

        after that I start doing the decomposition dance
        oh, and btw, I make it a rule never to write the same code twice in an app - I always factor out to a sub or method. This help highlight new candidates for classes/modules faster. And if I notice that much of the code is avariation on a theme, I stop and try to find some abstraction that allows me to parametize that code.
        I think it was Donald Knuth who said
        Every problem in computer science can be solved with either more - or less - abstraction. Experience tells you which one of those to apply.
Re: perl OO - to use or not to use
by Elian (Parson) on Sep 15, 2003 at 13:22 UTC
    To #3:

    From an end-programmer point of view, there will be no difference between perl 5 type objects and perl 6 type objects. If you treat them as opaque things (which arguably you should, though whether anyone does is a separate matter) your code won't know where objects came from. They could well be tied-in C++ or Smalltalk objects for all the difference it might make.

    In actual class declaration, things will be a bit different. While perl 5 objects are just a perl 5 variable with an "I'm an Object!" sticker slapped on them, perl 6 objects will be more structured and, more importantly, safer for subclassing.

    Each class in a perl 6 inheritance hierarchy can have its own private data elements (I think we're calling them attributes) that it inserts into the opaque object. Only methods of that class can see the attributes, and the attributes don't clash with like-named attributes from other classes in the hierarchy--all the classes in a tree can have an attribute 'foo' and they're all different attributes, only accessible from within the code of the class that declared it.

    These attributes will be fixed at compile-time, per the current thinking, so you're not supposed to be able to add new ones to a class at runtime. (I wouldn't bet too much on not actually being able to, however... :)

    Perl 6 classes will be able to inherit from perl 5 classes, and vice versa, as well as from objects from other object systems. Perl 6 classes will likely have a universal parent class, as perl 5 classes do. They won't be the same universal parent class, however. (Whether the perl 6 universal class will be the same as the ruby and python universal base class is still up in the air. We'll see)

    Most of the rest of the new toys--overridable dispatching, multimethod dispatching, class-specific multimethods, and stuff like that--will be available to perl 5 classes running under parrot, so I don't know that stuff counts for what you're looking for.

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: perlquestion [id://291379]
Approved by gjb
Front-paged by broquaint
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others imbibing at the Monastery: (20)
As of 2014-10-20 18:45 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (88 votes), past polls