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

Right job for the tool.

by AltGrendel (Acolyte)
on May 28, 2014 at 12:29 UTC ( [id://1087643]=perlquestion: print w/replies, xml ) Need Help??

AltGrendel has asked for the wisdom of the Perl Monks concerning the following question:

In my years of working with Perl, it has always proved to be a great tool for almost any job. But one thing has always eluded me.

When would you use OO Perl?

What types of tasks is it best suited for? Sometime I feel like I'm missing some opportunity when it would be perfect for the matter at hand.

Please enlighten me.

Replies are listed 'Best First'.
Re: Right job for the tool.
by InfiniteSilence (Curate) on May 28, 2014 at 14:09 UTC

    Aha! Good question (although I probably would have technically classified this as a Meditation).

    My answer is this: you use OO programming techniques when the analysis methods you've used to scope the problem at hand make OO implementation a logical choice.

    Let me elaborate. Some people believe that they are using OO programming when they are actually only utilizing one of the aspects of OO -- encapsulation. Although this is a good place to start this, by itself, is not OO programming.

    There are may different approaches toward decent OO design, but the one that often makes sense to me goes something like this: identification of objects in a use case/story (nouns == objects; verbs == methods); sequence diagramming; and class diagrams. I've learned to despise using graphical tools to do this work so I started diagramming these in dot and most recently have switched to using PlantUML.

    Here are a couple of problems doing this in Perl:

    • You shouldn't use heavy OO analysis for every problem. This is typically only necessary when the scope of the problem goes beyond several classes that need to work together or the problem space is fairly unfamiliar so it would be a good idea to do this analysis as an aid to learning.
    • The popular OO design paradigms are unfamiliar with CPAN and, as such, do not stress that you should actually go shopping for modules that fit your bill after identifying your needs but before programming. Evaluating someone else's code takes time which needs to be added to your overall timeframe.
    • Get into the habit of writing tests for your code early and often or you will learn how easy it is to need to make a change in one class that can totally destabilize your system.
    • There is a measure called cyclomatic complexity that can aid in maintainability. For instance, if you insist that all submitted coded methods have a complexity number of fewer than 20 for instance you will find it easier to understand code later on.
    • Alternatives exist to h2xs -XAn for building more complex hierarchies of classes. You might want to research ExtUtils::ModuleMaker or other utilities.
    • Have fun. OO analysis sucks and is boring when compared with writing interesting, terse pieces of code.

    Celebrate Intellectual Diversity

Re: Right tob for the jool.
by choroba (Cardinal) on May 28, 2014 at 12:45 UTC
    I usually use OO for any larger project (more than 1 file, 100 lines, but YMMV). It's useful when the project deals with complex data structures, there are several types of them, and each type can have many instances. I can't imagine we'd be ever able to build something like PML-TQ without objects.

    (jeffa) Re: OOP is one of the nodes that Search returns for "OOP", it seems to summarize the advantages clearly.

    لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ
Re: Right job for the tool.
by andal (Hermit) on May 28, 2014 at 14:12 UTC

    Well, if you can solve your tasks without OO, then probably you don't need it :)

    I use blessed variables mostly when I work with set of objects that might be of different class, but provide certain common values/operations. In Java terminology "implement common interface". This allows simpler "divide and conquer" approach to solving problems. But YMMV.

    So, OO mostly comes in for complex and large programs. Simple ones are much better without any OO. IMHO :)

      I have used OO programming in Perl for real projects only relatively rarely, mainly for building modules, but I agree with the above, if the programs are simple, don't bother. But if you want to build a complex hierarchy of entities and behaviors, then it is a different story, OO programming really becomes handy. So, at the end of the day, it really depends on what you are doing with Perl.

      And, frankly, I find the functional programming paradigm (à la Higher Order Perl) to be most of the time more efficient. But that only my own personal and limited opinion.

Re: Right job for the tool.
by Your Mother (Archbishop) on May 28, 2014 at 15:25 UTC

    I'd say a slight majority of the non-pragma modules I use are OO so it seems odd that you've managed to escape it. Here are some examples, though a few sport non-OO interfaces too-

    In their own realms, they offer great examples of when one might use OO. And when you are using 60 modules in a script, OO is nice for the simple fact that you have inlined, by the object's name, a good map to the functionality's origin. $mech->get(...) is easier to grok and backtrack to perldoc WWW::Mechanize than get(...) would be in a couple thousand lines of code.

    Perl's OO ecosystem is excellent. If you're just starting out with it and want a leg up, I'd point you at Moo before Moose.

Re: Right job for the tool.
by BrowserUk (Patriarch) on May 28, 2014 at 23:11 UTC
    When would you use OO Perl?

    If the module/library needs to retain state, then OO is the natural way to provide for that.

    However...

    When would you use OO Perl?

    Only if the module/library needs to retain state, and, performance is not a consideration for that module/library.

    If performance is a consideration, and the functional requirements are such that moving (the critical parts) to C or C++ would be laborious relative to a native Perl implementation; then I will eschew OO and go with a procedural design, manually passing a 'handle' (aka: a dynamically allocated memory address), returned by the 'initialisation' function, to subsequent calls to allow internal state to be retained .

    In all coding, in all languages, the functional requirements should drive the design semantics; not the other way around.

    OO for its own sake is as destructive as any other dogma.


    With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
    Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
    "Science is about questioning the status quo. Questioning authority".
    In the absence of evidence, opinion is indistinguishable from prejudice.
Re: Right job for the tool.
by Discipulus (Canon) on May 29, 2014 at 08:22 UTC
    In addition to wiser monks's words, i suggest you to read Damian Conway's ten rules for when to use OO.
    Also, (consider that me i'm a self-made programmer, with no real experience in OO writing, only some aMooseMent..), it seems to me OO become useful in multi programmer env: the layer created by the OO design separates logic from interface (to the software). Programming is definetively an interface matter.

    Consider another feeling: Perl is very democratic. When you approach a problem to resolve, you could be naturally inclined to describe it in a OO fashion: no problem: write down some Moose class, and run some instancieted voodoo against them.
    Or by other hand you suddenly visualize a cached multilevel datastrcture returned by a closure and a jaggling way to manipulte it and to serialize it... go on on your way.

    Another thing: when you'll need to maintain the code, what do you prefere? puzzling in possibly big a complex file or be mazed in a directory tree and in a meta-file hierarchies?

    HtH
    L*
    There are no rules, there are no thumbs..
    Reinvent the wheel, then learn The Wheel; may be one day you reinvent one of THE WHEELS.
Re: Right job for the tool (When would you use OOP?)
by Anonymous Monk on May 28, 2014 at 22:11 UTC

    When would you use OO Perl ?

    There, I fixed it for you, now you've got the right question :) When would you use OO ?

    In perl use it whenever I think, hey, maybe this part should be override-able .. and foo( $hash); turns into $hash->foo;

    Even when I figure I probably won't ever need to override any part of this, if I'm passing around a reference to everything, I make it OO

    No, my OOP Perl doesn't have accessor methods, I access the members directly ... its for small programs :) and yes its technically OOP

    https://en.wikibooks.org/wiki/Object_Oriented_Programming

Re: Right job for the tool.
by GrandFather (Saint) on May 30, 2014 at 01:47 UTC

    I use light weight OO (mostly just for encapsulation) in almost every significant script (say 100 lines or more) I write. I consider it a cleaner alternative to using a bunch of global variables or passing a bunch of state around as parameters.

    After a while you tend to build up a code tool kit. If that is OO based it's easier to wrangle into a new shape for specific applications and you get more mileage from the toolkit.

    Perl is the programming world's equivalent of English

      I have a little mental model of scripters (as opposed to module writers. I script more than write modules). The amount of OO we use as a function of experience is something like a bell curve.

      Start with simple procedural scripts, with global variables to be able to tweak things. Eventually use subroutines to organize the code a bit. Use subroutines for things that are repeated. Pass parameters to those subroutines to control their behavior. You're climbing the curve!

      Keep adding parameters for things you didn't realize you needed (or changing requirements), till you have 6-, 7-, ..., 10-parameter subroutines. The requirements change so much that you try to generalize things, usually overly and/or incorrectly. Pass some parameters through the command-line, because it gets tedious changing the code. Eventually, after you tried several homemade systems of command-line parsing, you invent some "App" module. This is where you've discovered OO. You realize other people probably did this before, so you look for a module to take care of command-line parsing and passing around that one object with all your app state. You might go through several of those modules. Eventually you're trying MooseX::Getopt or whatever and create the most unmaintainable, abstract code possible. You've neared the peak of the bell curve and begun a nervous breakdown.

      A year or two of your life passes, which you can't recall, but you can't believe you used to write code like that. You're on the downside of the curve, the path to recovery and wisdom. You realize (or have to believe for your sanity) nobody could ever have cleanly maintained this stuff anyway, so you avoid OO, you avoid frameworks. You're convinced that it makes business sense anyway. You write 1000-line stream of thought one-off code with no illusion of "organization" or "logic", since that doesn't exist in your world. You spit the phrase "project owner". While reviewing others' code you might advise avoiding using globals or give tips about how to make the code clearer by.... oh, what's the use: deep inside you know it doesn't matter. You've lived the horror. You'll live in a log cabin soon. Logs are real objects. Squirrels don't have business needs.

      :P

Re: Right job for the tool.
by sundialsvc4 (Abbot) on May 28, 2014 at 12:57 UTC

    In the Perl environment, OO is relatively simple:   it consists of the notion of “blessing” an otherwise-ordinary data structure (usually a hashref), which causes that now-object to be associated with a particular package such that Perl now understands what to do whenever it sees the $varname->methodname(arguments ...) syntax.   Whenever this is used, Perl sees that $varname has been blessed, therefore it knows what package it should be able to find sub methodname in.   It calls that subroutine with $varname as the implied first argument to the call.

    There are details that I have purposely left out, of course, but the essence is there:   a data structure is implicitly associated with a package of subroutines, such that subroutines within that package will be called with the data structure as the first argument.   So, now you have the two things that you need most:   executable code to call to do things and to get answers, and a clearly-defined very-convenient place to put them.   The clients of all that goodness, elsewhere in the program, do not have to be concerned with extraneous details, knowing that those details will be resolved at runtime.   This gives you most of the essential features and benefits of OO, and Moose builds upon that same foundation to give you even more.   It is a very natural and expressive way to work, which is why I think it became so universally popular.

Re: Right job for the tool.
by einhverfr (Friar) on May 31, 2014 at 13:10 UTC

    First, this is an excellent question. It can generally be generalized to "where would one use OO programming?" Obviously not every task.

    Let's start by looking at what OO programming gives you. This is, basically, a way of abstracting behavior around state. This is useful where you have a midsized project and want to make sure that you can more easily de-couple components (but don't want to go as far as, say functional programming). For small projects, the overhead in design makes it an unattractive choice. For very complex projects with complex concurrency issues you probably want to go with functional programming as your primary paradigm (you can mix OO and functional programming though).

    So let's look at basically three models of managing state: Imperative, Object-oriented, and Functional

    Imperative is basically summed up as "You do something with state. Object-oriented can be thought of as "state is responsible for its own behavior" and functional programming is "avoid state if you possibly can."

    In general highly complex, highly concurrent systems will benefit from functional programming, and extremely simple systems will benefit from imperative programming. It's in the middle where object oriented delivers its best benefits.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (4)
As of 2024-03-28 18:20 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found