Beefy Boxes and Bandwidth Generously Provided by pair Networks
Do you know where your variables are?
 
PerlMonks  

OO 2 death?

by Cestus (Acolyte)
on Dec 06, 2001 at 19:37 UTC ( [id://129935]=perlmeditation: print w/replies, xml ) Need Help??

Recently, in my Gr 12 programming class, we had to do a web based project. That was cool - I could use Perl to do it, not the panzy JavaScript we had been using! I submitted my proprosal to make something to generate a new page through form submission. It got oked. I then attempted to persuade my teacher to let me use Perl. After much arguing, I was finally allowed to - great! Just a simple top->down script to do my bidding. No mess, no nothing. However, my teacher, fool that he is, forced me to do it in OO syntax! Now, my nice little 2 page script has ballooned out into a dozen modules and about 20 pages worth of code. Mostly due to having to make constructors and their ilk for about 10 different objects, but all the same, OO was not the right choice for the job.

Question: Should a line be drawn for use of OO code? Yes, I can re-use some of my modules, but most of them were special-purpose, so much so that not even extensive use of polymorphism (love that word) could save them. Should OO stop at some point?

Cestus

Microsoft and Shinra are the same. They're both killing the planet.

Replies are listed 'Best First'.
(tye)Re: OO 2 death?
by tye (Sage) on Dec 06, 2001 at 20:15 UTC

    Sounds to me like mostly a poor choice of objects. If you could do all of the work in a couple of pages, then designing a dozen modules is certainly overkill.

    I think it'd be interesting to see your original version and the OO version (even as large as it is) to let people offer alternate designs that are still OO but not so bloated.

    And, yes, you shouldn't be made to feel bad about writing a single script without using any OO. Now, if this was to be the first of many scripts that were going to be extended and maintained for years, then selecting a design philosophy that would almost certainly make the first script larger and take longer to write might well pay off in the long run. In such a case, in Perl, OO might well be the best choice for many of the components.

    But even then, there is some merit to the idea of getting a working "prototype" up and running quickly if for no other reason than to help solidify your understanding of the situation, in hopes of helping to improve the design. Over-designing too early can certainly be as much of a problem as under-designing.

    My strong preference for OO in Perl has little to do with OO (Perl's OO isn't very OO) and more to do with it being a good way to control namespace collisions and to make modules that can be flexible while being easy to use and being able to fit in a large project where they are likely to be used in more than one place in possibly conflicting ways.

    I'll also add my OO pet peeve: Inheritance should mostly be considered a last resort (especially in Perl) despite the fact that nearly every elementary OO book makes it sound more like it should be your first choice.

            - tye (but my friends call me "Tye")
      No worries about this hanging around for a long time ... it's for the school website, which gets re-written every year. I'll see about posting the bloated/simple versions of my script - I'm going into version 2 right now, so maybe in a couple weeks ....

      Don't really agree with your point on inheritance - Perl's use is frustrating, but it can be a great power tool. The ability to tweak something at the top of a hierarchy, and have that make mass changes is appealing - but only in larger projects that you've actually bothered to document. Otherwise it gets a bit ridiculous, I concur.

      Cestus

      Microsoft and Shinra are the same. They're both killing the planet.
Re: OO 2 death?
by Fletch (Bishop) on Dec 06, 2001 at 19:57 UTC

    Short answer: Yes, OO can be the wrong tool for some jobs. C.f. Java "hello world" programs.

    And as for having to write a plethora of constructors, take a look at Class::MethodMaker which can automate the bulk of your OO plumbing (constructors, accessors, et al) and let you conentrate on writing the parts that do real work.

Re: OO 2 death?
by mortis (Pilgrim) on Dec 06, 2001 at 20:08 UTC
    My personal experience has been that when I code using OO techniques, I actualy write less (usualy significantly less) code.

    The specific itch you mentioned was having to write constructors for each of your objects. Could that have been solved via inheritence?

    In most of the OO projects I've worked on, we create a Base class that has an inheritable constructor that most or all of the objects inherit from.

    package Base; use strict; use warnings; our @ISA = qw(); sub new { my $this = shift; my $class = ref($this) || $this; my $self = {}; bless $self, $class; $self->init(@_); return $self; } # default init, does nothing... sub init {1;} # get/set a scalar member variable sub _gss { @_ > 2 ? $_[0]->{$_[1]} = $_[2] : $_[0]->{$_[1]}; } sub throw { my $self = shift; my($p,$f,$l) = caller(); die "Exception at: ",$p,"->$f($l)\n ",join('',@_); } 1; ######################################## package MyObject; use strict; use warnings; our @ISA = qw(Base); sub init { my($self) = @_; $self->someSetting('default value'); return 1; } sub someSetting {shift->_gss('_myObject__someSetting',@_);} sub someAction { my($self) = @_; print "setting: ", $self->someSetting(), "\n"; } 1; ######################################## package main; use strict; use warnings; my $obj = MyObject->new(); $obj->someAction(); $obj->someSetting('new setting'); $obj->someAction(); exit 0;
    In that example, MyObject doesn't need it's on explicit constructor, as it will inherit the one from Base.

    Is this applicable to your project, or am I missing the point?

    Best regards,
    Kyle

      Not really - what I was doing was simple - formatting a week at a glance page. Stuff for each day comes in, HTML goes out. However, my teacher is schizoid on being able to easily modify code - he wouldn't let me have Monday and Tuesday be the same. I had to seperate those into seperate classes. I used inheritance as much as I could, but that was because he placed a 1.5 page limit (with comments and whitespace) on my modules. I couldn't cram a constructor, initializer and actual code into the module like I wanted to. I frequently use inheritance, but this case was so simple it was overkill - I didn't even need the most basic of OO tools to do this. Ridiculous thing is, while I'm taking this course I'm doing a coding co-op, and my employer openly encourages the simple solution - top->down, reuse, 3rd party stuff ... I've done much more complicated projects in less time than that dumb one.

      So, no, there wasn't anything I could really do in that instance - OO was forced, to a negative end. I'm pretty sure it sucks more resources than it needs as well.

      Cestus

      Microsoft and Shinra are the same. They're both killing the planet.
        "he wouldn't let me have Monday and Tuesday be the same. I had to seperate those into seperate classes"

        Aha! Rather than having seven different classes, you should have used one (over-simplified and untested code):

        package Day; sub new { my ($class,$dayname) = @_; my $self = { day => $dayname }; return bless $self, $class; }
        And then you instantiate them like so:
        my @days = map { Day->new($_) } qw(Sun Mon Tue Wed Thur Fri Sat);
        Sometimes you don't need seperate classes, just seperate object instantiations.

        jeffa

        L-LL-L--L-LL-L--L-LL-L--
        -R--R-RR-R--R-RR-R--R-RR
        F--F--F--F--F--F--F--F--
        (the triplet paradiddle)
        
        Ah. Your problem is simple then.

        You have a stupid teacher. I completely sympathize. I have had to deal with the same problem.

        While there are good reasons to limit a function to a page, there is no good reason to so limit an entire module. Furthermore your teacher's insistence on separating out similar things in the name of "modifiability" is just plain silly. What you are doing is, as you discovered, guaranteeing spending a lot of time writing similar code. More code means more room for mistakes. Most code means that any change has to be made in more places, and the opportunity for doing so means more room for mistakes. More code that is very similar means that you will spend time doing cut-and-paste code. Cutting and pasting is a guarantee that if you catch a mistake, you are going to have a fun time trying to fix it in every other place where it appears.

        Instead it is far better to find ways to put each piece of real information in as few places as possible (hopefully 1). That means gathering together similar things, having common execution paths, etc. This does not preclude any kind of later modification. In fact it makes it easier. Should you need to split things farther, you can do so later at no more work than it would be to do now. Should you need to reorganize or change common functionality, you will find that easier than it would otherwise be.

        I therefore encourage you to look past the bad and counter-productive restrictions placed on you by your teacher, and continue (even if you have to do it on your own) learning how to program well, including how to code OO well.

        Ah well, just think of it as a learning exercise, getting arbitrary restrictions put on you, and having to get by as well as possible. Kind of like playing chess with no queens, or twelve tone music. In this case, your restriction is that it must please your stupid teacher :-)
(jeffa) Re: OO 2 death?
by jeffa (Bishop) on Dec 06, 2001 at 20:40 UTC
    Of course!

    But that's no excuse not to learn it. Without knowing what the problem domain was, i can't agree that OO was not the right choice for your job.

    "Yes, I can re-use some of my modules, but most of them were special-purpose..."

    What's good about OO is that it teaches you how to make those decisions: when to generalize, when to specialize.

    "...script has ballooned ... Mostly due to having to make constructors ... for about 10 different objects"

    Don't forget the one line constructor:

    sub new { bless {}, shift }
    Sorry you now have a bad taste for OO. To be honest, i would rather teach someone OO in a language like Ruby or even Java before throwing them into Perl. Perl's OO is, in my opinion, more difficult to grasp than other languages. It's easy to turn OO into a big ball of mud, it's very easy to do that with Perl OO - but, personally, i love Perl OO!

    Any chance of you throwing a couple of these objects on your scratchpad? I'm really curious to see what you have done. And congrats for finishing the project!

    jeffa

    L-LL-L--L-LL-L--L-LL-L--
    -R--R-RR-R--R-RR-R--R-RR
    F--F--F--F--F--F--F--F--
    (the triplet paradiddle)
    
      :) - Actually, I did learn OO in Java b4 trying to learn it in Perl. Perl's syntax is a lot more difficult, and not as powerful - multilpe parents just aren't a good idea. I'll chuck up some objects when I get the chance, sure. I could have made it with better inheritance, but I encountered problems when using an initializer in the superclass. Had to move it down to bottom of class hierarchy. Generalizing was what I wanted to do - unfortunately my teacher saw otherwise. He also thinks that Austin Powerrs is still in (shudders *repressed memories surface*). Prob with one-line constructor is that it's 'bad form' - teacher hates not pre-declaring variables. That's what you do in Java constructors, so illogically you do that in Perl as well. I had my constructors loaded with undefs and dumb comments saying what I was doing. I'll be sure to get that on my scratchpad soon.

      Cestus

      Microsoft and Shinra are the same. They're both killing the planet.
        "Perl's syntax is a lot more difficult, and not as powerful..."

        I agree with the first statement, although understand that it gets easier with time and experience. The second statement is just plain wrong, however. The reason Perl's syntax is more difficult is because Perl IS powerful. I didn't 'get' Perl until about 2-3 years of using it.

        Remember, tye said that inheritence should mostly be considered as a last resort, and he is dead on the money. The buzz term is "favor aggregation over inheritence". Inheritance is not the best answer, as you see when you realize that a mistake was made in the parent class.

        My opinions on pre-declared variables: a maintenance nightmare. However, i do like thing such as:

        sub new { my $class = shift; my $self = { day => '', some_list => [], some_hash => {}, }; return bless $self, $class; }
        If your variables are named appropriately, you shouldn't have to add comments to explain what they are. Comments should be reserved to ideas that can't be immediately gleaned from the code, code such as this:
        # grab the pk if found, remove it and store for later use # and remove it's column from the table if (exists $self->{'pk'}) { $self->{'pk_index'} = delete $self->{'fields_hash'}->{$self->{'pk'} +}; splice(@{$self->{'fields_arry'}},$self->{'pk_index'},1) if defined $self->{'pk_index'}; }

        And yes, that one-liner constructer is bad form. If you thought that was bad, then how about this:

        sub get_attrib { shift->{shift} }
        ;)

        jeffa

        Austin Powers / 0

Re: OO 2 death?
by dragonchild (Archbishop) on Dec 06, 2001 at 20:02 UTC
    Longer answer - OO done badly is worse than spaghetti code. Not even 6" meatballs would save it then!

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

    Don't go borrowing trouble. For programmers, this means Worry only about what you need to implement.

Re: OO 2 death?
by maverick (Curate) on Dec 06, 2001 at 22:37 UTC
    From reading your additional posts about the constraints placed upon how you had to do this project: This may sound a bit harsh, but I'm sure there are others here thinking it.

    /me straps on his nuclear accelerated flame thrower...

    Either the professor was trying to keep you from succeeding at this project on purpose, or he is a screaming moron.

    You had to create a separate type of object for each day of the week? As jeffa rightly points out, you should make a 'day' object and then instanciate one for each day of the week. Why have different classes? The last time I checked Monday and Tuesday were not so ratically different that they would require two different types of objects. One of the guiding principles of OO design in the first place is to make a object to represent some number of like things. Days of the week are most certainly like things.

    As for program size limitations. I have never, never, NEVER been told that my program couldn't be over a certain number of lines. My professors were concerned with 1) does it work 2) is it designed well 3) is the code maintainable and well documented.

    /me loans flame thrower to Cestus....you'll be needing this the next time you go to class.

    Choose the right tool for the job. At this point you may not know what the right tool is, but it seems like you're starting to see. There are some times when OO is the right way. There are some times when OO isn't. But there is never a time when a poor design OO or otherwise is the right way (especially if thrust upon you).

    When in doubt, seek other's opinions...your professor isn't always right.

    /\/\averick
    perl -l -e "eval pack('h*','072796e6470272f2c5f2c5166756279636b672');"

      mmm .... flamethrower. However, I do own a sword - all I have to do is sharpen it and remove the safety tip (for all you fencers, it's a practice foil (not electric) with a long belgian pistol grip). A lot of what my prof seems to preach is based on this Java course he took, and here I quote "I lost all of my marks because I did not properly comment the purpose of each variable"? At my workplace I have been asked to redesign code that goes on for hundreds of lines sans comments. He also said that his university prof limited the size of his classes to at most two pages. I think the problem is that my teacher is not very intelligent in the first place, and then he went to take a university course with a crazy prof. You guys are right, the splitting up the week thing should be totally unenecessary, but to him it is - otherwise how could we get Monday different from Tuesday! Why would we? It's only going to get worse now, however - I'm adding on security measures, which will, of course, have to be placed into modules as well, and some other stuff which will have to be modularized. As it stands right now, I've got one cgi and 11 module files. One is a cgi parser (CGILite), 6 are for the days of the week, 3 are for sports, and one is for generating hyperlinks. If I were to use OOP for real, there would be a total of 4 modules - one for a day of the week, one for a sport, one for making hrefs (it's actually kinda handy - what OOP should be) and the CGI parser. Like I said, I'll try and get that code up on my scratchpad, but I'm kind of distracted by the prospect of upgrading my sys right now (P4 ..... drool ......)

      Cestus

      Microsoft and Shinra are the same. They're both killing the planet.
Re: OO 2 death?
by stefp (Vicar) on Dec 07, 2001 at 01:49 UTC
    The goal of an exercice is often not so much to get a job done but to learn and master some imposed method(s). By nature an exercice is often so simple that it can be often solved more easily by other methods than the imposed one.

    Then, one have to learn for a specific problem which method is appropriate. You already do! The problem is that bondage languages like Java don't let programmers choose and force on them the OO methodology that is overkill for small programs.

    So, as a Zen perlmonk, see this exercise as a preparation to more complex problems instead of complaining that OO imposed on you is not optimal here.

    -- stefp

Re: OO 2 death?
by Aristotle (Chancellor) on Dec 07, 2001 at 04:10 UTC
    I think what happened here is a combination of two things.

    For one, undeniably, your teacher made silly restrictions and demands. I've met a lot of people who teach a subject they know well, but don't understand well. They have learned a few dogmata like mantras, and apply them regardless of cost or situation. So long as they stick to the environment these dogmata were made for, that usually is not a problem, however as you have seen, it can crash and burn big time as soon as you have to adapt..

    And then I also believe you tried to translate your simple script too straightly to OO. I don't see how a simple task can require so much copypaste code if you start out with the proper design right away. Throw away the concepts of the initial script and ask yourself how to model your task using classes - you should end up with a lot less code. OO design is very different from writing straight procedural code.

    Of course, without nothing to actually look at, I can't know for sure.. but from the looks of it, it's both.

      For one, undeniably, your teacher made silly restrictions and demands.

      You assume that the point of the instructor's exercise was to build a web application in the most efficient way possible. What if the instructor was hoping to use this exercise as a means to teach some good OO design? Suddenly his requirement doesn't seem so silly after all... We don't know what languages the other students were working in, or whether or not all of them got to pick their language of choice. It's very possible the language of choice here just happens to be an OO language. If that's one of the goals of the course, I would expect to have to have that reflected in the languages the instructor would permit me to use.
        Thank you Fastolfe.

        I just found this thread and started reading the replies. I find it hard to believe that most people just assume there is no other motive behind this assignment. While it is very possible that the constraints placed on the project are just plain silly, there is also a reasonable chance that there are other lessons being taught.

        I have a close, talented friend who flunked out of Carnegie Mellon because he felt he could improve his projects and that his CS profs were "silly" with some of their assignments.

        The "silly restrictions" referred to things like module length and using different classes for each day. Try as I might, I cannot see any valuable lesson being taught there. I am very well aware of the fact that a lesson to be taught may not be what would under other circumstances have been the optimal solution.

        Pay attention: I am not critizing the teacher's choice of restrictions with respect to the problem at hand; I am questioning their worth as such. (Maybe I should have been clearer?)

        I am in fact biased towards OO; I would tend to use it in projects that could be done without OO simply because solutions tend to stick around and grow, regardless of how short term they were planned, and I'd rather be working with organic growth in an OO approach than a procedural one.
(podmaster) Re: OO 2 death?
by PodMaster (Abbot) on Dec 07, 2001 at 10:38 UTC
    ...in my Gr 12 programming class...

    That's high school right? If anything I can truly tell from the "constraints" imposed upon you by your teacher is, regardless of what the other monks says, he's teaching you at least one very important lesson: in programming, as in life, a lot of choices are not up to you, and you have to fight to get as much of your "wisdom" as you possibly can, in where it counts.

    I sugguest, after ensuring there was no miscommunication, which can often happen, and after you've completed this project, that you inquire as to the "reasoning" behind the constraints placed upon you.

    Look on the bright side, the next time you have to do something like this, you'll probably get paid ;D
     

    ____________________________________________________
    ** The Third rule of perl club is a statement of fact: pod is sexy.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others rifling through the Monastery: (3)
As of 2024-04-25 07:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found