Beefy Boxes and Bandwidth Generously Provided by pair Networks
"be consistent"
 
PerlMonks  

To use or not to use OO Perl

by monkfan (Curate)
on Oct 22, 2004 at 14:24 UTC ( #401489=perlquestion: print w/ replies, xml ) Need Help??
monkfan has asked for the wisdom of the Perl Monks concerning the following question:

Beloved Monks,

We can write any code in functional(structural) Perl, with all its prowess, it seems to me it can do anything.
I am new in programming in general, just fascinated more and more everyday with Perl,
and would like to get to know the OO aspect of it better. Here are some issues I would like to know more.

My question are:
1. On what circumstances we should use Object-Oriented (OO) instead of functional Perl? What's the trade-off?
2. Is it preferred that we use OO Perl as much as we can?

I hope you don't mind answering these silly and simple questions.

Regards,
Edward WIJAYA

P.S: Any pointer to existing PM node in line of this discussion would also be welcomed.

Comment on To use or not to use OO Perl
Re: To use or not to use OO Perl
by kutsu (Priest) on Oct 22, 2004 at 14:40 UTC

    These are not silly question, indeed Ovid wrote an interesting Tutorial on this very subject (Often Overlooked OO Programming Guidelines). As for myself the main reasons I use OO programming is when I want to re-use the code with multiple programs (which means modules are usually in OO) or if the code is very large and by putting it in OO I make it more readable (at least more readable by me).

    "Cogito cogito ergo cogito sum - I think that I think, therefore I think that I am." Ambrose Bierce

      I always write modules with OO interfaces (instead of exporting functions), but I find that only about 1/5 of my modules actually count as real OO. What does this mean? It means I use new and self, but other than keeping track of instance data, I'm not using any major OO constructs. Just using new means I don't have to pass the same datastructure argument to each function in my module each time. So that's pretty basic. My modules are usually more indicative of functional (do *not* read as "procedural") programming than OO itself.

      Code-reuse is not really something that is unique to object oriented development, and it's a shame that people think OO invented code-reuse. It did not. In the wrong hands, OO subclassing actually allows for reuse-avoidance, or even copy-and-paste development in a politically correct format. Furthermore, it is a shame that the philosophy-of-uber-inheritance is so tightly coupled with OO thought that most OO programs instantly grow a tremendous class-hierachy. This too, need not be the case.

      Anyhow, OO is fine -- but don't think it's about reuse or maintainability or massive inheritance hierachies or anything like that. It's mostly about state and clean interfaces -- or, at least -- that's how it SHOULD be. The number of real world problems correctly modelled by massive inheritance trees are few and far between.

        Nearly all my modules are based on some form of encryption, which means I can reuse a lot of OO constructs as is. I did not specify this because the main point of my post was the link to Ovid's tutorial and the link inside it to Damian Conway's ten rules for when to use OO. Having said this, I still prefer to use OO when projects are similiar, as it easier for me to "cut&paste" or reuse code as I can and it is much easier for those I work with to understand and work with OO code - which is why the main point was the Often Overlooked OO Programming Guidelines and Damian Conway's ten rules for when to use OO both of these explain a situational problem (why to use OO) in a much more complete fashion then the small node I wrote in the time I had.

        "Cogito cogito ergo cogito sum - I think that I think, therefore I think that I am." Ambrose Bierce

        Anyhow, OO is fine -- but don't think it's about reuse or maintainability or massive inheritance hierachies or anything like that. It's mostly about state and clean interfaces -- or, at least -- that's how it SHOULD be. The number of real world problems correctly modelled by massive inheritance trees are few and far between.

        If you ask me, OO is a method for modelling problems that are based on interactions between Things. Not all problems are easily or properly modelled this way. When used for suitable problems, object-oriented code can be stunningly elegant; when used for unsuitable problems, it's usually a steaming heap of crap unnecessary complexity.

        tilly argued this point better and more completely: The world is not object oriented.

        --
        Yours in pedantry,
        F o x t r o t U n i f o r m

        "Lines of code don't matter as long as I'm not writing them." -- merlyn

Re: To use or not to use OO Perl
by perlcapt (Pilgrim) on Oct 22, 2004 at 14:40 UTC
    I am probably getting in trouble here, being only a scribe, but I would like to express my feelings on these very worthy questions.

    I end up using OO-Perl:
    When I find that the structures that I am using in my program have inherent subroutines (methods) associated with them, or when the structures build on substructures in a logical way. I also have found that I will rewrite some procedural hack as a module (OO prefered here) when the hack looks like it might actually be useful to several applications or to other folks.

    Question 2: I do whole lot of precedural hacks, maybe 1-100 lines of code. I wouldn't use objects on these, unless, of course, I am using a Perl Module that lends itself to an object/method model. (Most do!)

Re: To use or not to use OO Perl
by TedPride (Priest) on Oct 22, 2004 at 14:54 UTC
    You use OO when the code is likely to be reused, or when the project is large and you need a fairly rigid structure to make testing and documentation possible.

      Surely that explanation applies to modules in general - not just of the OO flavour?

      Modules are by nature designed to facilitate code reuse and naturally they (should) come with their own documentation.

      How OO lends to a "fairly rigid testing structure" I'm not sure as, again, this seems to come under the heading of modules in general.

      --- Jay

      All code is untested unless otherwise stated.

      That is generally true of functional programming as well, no? I feel OOP is great when you can seperate you can draw clear lines between your various forms of data and behaviorrs to be taken out on them. Parsers for instance, do not easily fall into this, as you might wind up witha single class called "parser" and a bunch of supporting functions.

      My counter example, is when I thought doing tests for a theory related project, graph colouring, would be silly to do as OOP. But if I can pass the different cases around as objects and the types of tests as classes, then it's a lot cleaner, to pass around the data and have functions available to call on them. Im not able to mix up a behavior with a piece of data. -s

      ----
      Then B.I. said, "Hov' remind yourself nobody built like you, you designed yourself"

Re: To use or not to use OO Perl
by gothic_mallard (Pilgrim) on Oct 22, 2004 at 15:11 UTC

    I do actually use OO quite a lot when I'm building modules. I'll be first to admit that I'm perhaps guilty of looking to the OO option first as I prefer the style, but I also (I believe) know those times when a vanilla module would fit the bill just as well.

    As to when to use OO it normally follows that I do it in the situations where I can visualise the problem as an object.

    When I built my email module it seemed natural to me that it should be an object - an email is a "thing" (read: object) that has properties associated with it ("to" address, body text et al) and methods that apply ("create email","add attachment","send" etc).

    The email is the central object around which it hinges.

    On the flip side, consider the example of the Math::Trig module. Where would the object be? The input value? - but there may be more than one. The result? - but until it runs there isn't one. Instead it creates a set of functions that can be used more generally.

    To your second question - I wouldn't say that OO is "prefered". It's all very much dependant on the application concerned - it's quite possible that in one context using OO is the way to go, whereas in another on the same problem it may be viewed as overkill.

    This is just my view, but I hope this helps.

    --- Jay

    All code is untested unless otherwise stated.

Re: To use or not to use OO Perl
by demerphq (Chancellor) on Oct 22, 2004 at 15:35 UTC

    For interface sanity, clean encapsulation and maintenance purposes use OO, for run time speed use FP (functional programming), for implementation speed use Imperative programming, for fun use all of the above.

    I have this feeling however that the "functional" approach you mean is really the "imperative" approach and not what most folks here would call "functional programming"


    ---
    demerphq

      First they ignore you, then they laugh at you, then they fight you, then you win.
      -- Gandhi

      Flux8


      for run time speed use FP (functional programming)

      Huh? Functional programming tends to be pretty expensive in terms of memory and arguably slower than a more procedural style (depending on whether your language of choice does tail-call optimization). Side effect-free programming with lots of first-class functions, closures, and lambdas floating around isn't easy to optimize. The traditional check-box feature of functional programming is implementation speed. (On the other hand, ghc can produce some damn fast code; on the gripping hand, gcc can beat ghc pretty handily. IME, of course.)

      Functional programming techniques make some faster algorithms easier to write (divide and conquer, for instance; languages with lazy lists make dynamic programming absurdly easy). That's not necessarily the same thing, though.

      Maybe by "functional" programming you mean "procedural"?

      --
      Yours in pedantry,
      F o x t r o t U n i f o r m

      "Lines of code don't matter as long as I'm not writing them." -- merlyn

        No, I mean mostly code generation using closures and string eval. If you write code that writes code then you can usually make that generated code extremely efficient. A good example for me was a system that processes large volumes of records based on a config file of rules that were strongly influenced by file type. Instead of making a machine in perl that processed the records according to the rules I made a machine in perl that created perl programs that were equivelent to the rules for each type of file. Each closure was constructed to handle only the rules for each file and in an optimised way. The end result has proved to be extremely fast.

        Im not sure if im abusing the term functional programming here, but it seems to me that this kind of thing is indeed a form of it. Anyway, hope this makes some sense, im not feeling particularly expressive right now. :-)


        ---
        demerphq

          First they ignore you, then they laugh at you, then they fight you, then you win.
          -- Gandhi

          Flux8


      For interface sanity, clean encapsulation and maintenance purposes use OO,
      I do not think OO is more maintainable when you are comparing advanced programmers to advanced programmers.

      Hybrid functional development allows functional programming with objects. Even Lisp has structures.

      FP code in itself can be incredibly easy to maintain, especially because the chain of function calls is usually very short and direct ... that, and short automagical functions are encouraged.

      OO does an excellent job, though, when you really can't trust everyone in the codebase. It defines boundaries, rules, and operations ... a well defined and documented API does this in the same way, though it doesn't force a design methodology on the entire codebase and through every class/source file.

        I do not think OO is more maintainable when you are comparing advanced programmers to advanced programmers.

        True. Advanced programmers tend to push the envelope regardless of the technology involved. :-)


        ---
        demerphq

          First they ignore you, then they laugh at you, then they fight you, then you win.
          -- Gandhi

          Flux8


Re: To use or not to use OO Perl
by kiat (Vicar) on Oct 22, 2004 at 16:01 UTC
Re: To use or not to use OO Perl
by revdiablo (Prior) on Oct 22, 2004 at 17:15 UTC
    On what circumstances we should use Object-Oriented

    Here's my take on the matter: If there is some piece of data that you are constantly passing around between different subroutines, then that data should be turned into an object, and the subroutines you're passing it to should be its methods. This really shines as the data you're passing around gets more and more complex. If you are maintaining two lists in parallel, for instance. Hiding all that behind an object interface is a much nicer option than manually handling all the data structures.

Re: To use or not to use OO Perl
by ihb (Deacon) on Oct 22, 2004 at 19:19 UTC
Re: To use or not to use OO Perl
by Starky (Chaplain) on Oct 24, 2004 at 22:44 UTC
    I concur with earlier replies that OO is preferred when you (i) anticipate your code with be reused, (ii) when the code will be used as part of a team development effort, or (iii) distributed in module form.

    It is also worth mentioning that, it is a good skill set to acquire if only to improve your familiarity with and ease of use of techniques used by CPAN modules. For many (if not most) Perl programmers, the ability to make ready use of the CPAN is half their value as a Perl programmer.

    In general, I think everyone who uses Perl more than casually should take the time to create a module, if only a "Hello World", for the valuable experience it provides.

Re: To use or not to use OO Perl
by DrHyde (Prior) on Oct 25, 2004 at 10:52 UTC
    Other monks have commented about OOish code being reusable. This is a myth. Or at least, it's a myth that it is any more reusable than non-OO code. For example, look at the standard C library. It's used by everything you ever write in perl, and yet not OO. Or look at any of the hundreds of modules on CPAN which just provide some useful functions but with no OO stuff, such as Data::Compare, Language::Functional and Net::CIDR. Perl's OO doesn't even easily give you one of the other big wins often touted for OO.

    Where OO is helpful is that working with objects instead of home-grown complex data structures provides a useful layer of abstraction that lets us hide complexity from ourselves, so we have to maintain less state information in our poor little branes. That benefit alone makes it worth using.

    As for your two questions - the answer to the second is simplest. It's "no". And the reason is the answer to the first - I write OO code when I feel that it helps me solve the problem best, which I suppose is a bit wishy-washy. Sorry.

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others avoiding work at the Monastery: (6)
As of 2014-08-21 12:21 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    The best computer themed movie is:











    Results (134 votes), past polls