Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

Perl Elitist Code vs Functional Code

by morissette (Novice)
on Aug 11, 2012 at 01:23 UTC ( #986846=perlquestion: print w/replies, xml ) Need Help??

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

So I am going to pose a simple question please do not start a super flame war.

Functional code: You wrote it in 10 minutes its under 50 lines and it performs the function you wanted it to do.

Perl Elitist code: Your code only uses 5.12 and above it forces best practices which makes it 200 lines and performs the same function as the functional code above but took you an hour to write.

So is the functional coder worse then the elitist?

Replies are listed 'Best First'.
Re: Perl Elitist Code vs Functional Code
by eyepopslikeamosquito (Bishop) on Aug 11, 2012 at 02:01 UTC

    You wrote it in 10 minutes its under 50 lines and it performs the function you wanted it to do.
    Your program is successful, so its users ask for enhancements and new features, so you add another 50 lines, and another, and another ... your little program grows to be so successful that it becomes critical to your company ... and then you leave the company.

    For small throw-away scripts, written by and for a single person, your approach is fine. But it doesn't scale, especially for production software maintained by teams.

    Moreover, in my experience, small throw-away scripts, especially successful ones, have a way of growing into thousands and thousands of lines of critical functionality. This sort of code tends to be fragile and difficult to maintain. Yet the code "works", so getting approval to improve its design and maintainability can be problematic. After all, where is the ROI in rewriting a working system? The cost of rewriting, the opportunity cost of not working on something else, changing the code risks breaking critical functionality (especially likely without unit tests). This topic is touched on in Unix shell versus Perl.

      Following certain J language best practices. 1000s of classes. No method may be longer than 25 lines. Inheritance charts that must be printed on the DesignJet. Abstraction for the sake of making work. Public properties are forbidden. No flags or options permitted, only derived classes. All getters and setters methods. Main logic placed in exception handling. No documentation of course. The guy who made the API will have a job for life, after he is fired he will be rehired as a consultant for 4x more. Since nobody can sit down and use his code without years of reverse engineering. A very smart programmer indeed.

      Don't invest time in elaborate APIs and abstraction unless you have already have a plan for future improvements which are only limited by funding or minor business model demands at the moment. If you can't whiteboard the plans on why you need abstraction, you dont need it. If you are metriced by the line, go with all the OOP fluff and keep adding classes. If you are paid by the project, go functional with the least amount of typing to get the job done. Nothing I said says to copy code instead of proceduring it.
Re: Perl Elitist Code vs Functional Code
by Your Mother (Archbishop) on Aug 11, 2012 at 03:21 UTC

    In my view the “Perl Elitist code” is often going to be more terse because it uses modules and idioms. Further, because it was that kind of day at work where I have to maintain 12 year-old “functional code,” I’ll add: the “elitist” code is also not going to bite you in the ass viciously, repeatedly, and in dozens of minorly differing iterations because it was actually written to be general purpose, testable, and reusable. Hell, I hear tell the elitists are even known to use revision control. From time to time.

Re: Perl Elitist Code vs Functional Code (attitude)
by tye (Sage) on Aug 11, 2012 at 03:54 UTC

    Sounds like you just have a bad elitist.

    You might also have a bad attitude (or that might just be a response to the bad attitude of your bad elitist -- I can't tell from here).

    If the two of you can't effectively communicate to the point that you understand much of the benefit of the 150-lines-worth of extra code he wrote (if there is any), then that is the most important problem.

    Since he is acting like the senior developer, then he probably is at least partially to blame for being ineffective as a mentor. If you don't have a manager (or higher) with whom you could effectively discuss that problem, then my next step would be to start looking for a new job. I've worked a lot of places but I've never had to put up with that kind of poor communication for very long.

    There are certainly programmers who overly complicate tasks to little benefit. Even worse are those who overly complicate designs to much detriment.

    But there can also be a lot of benefits to applying good "best practices", especially in the long run. And my experience is that best practices don't make code take up even close to 4x as many lines. That is, unless the "best practices" are very poorly applied or the no-best-practices code is actually an overly-compact mess. Nor do they make code significantly slower to develop (and they tend to make code much faster to maintain, in the long run -- which is really the point).

    - tye        

Re: Perl Elitist Code vs Functional Code
by eyepopslikeamosquito (Bishop) on Aug 11, 2012 at 05:04 UTC

    You wrote it in 10 minutes ... but took you an hour to write
    I think you are over-selling the importance of quick coding. For example, Schach (1999) estimates that programming represents only 12% of total software development cost while maintenance dominates at 67%. So even reducing programming time down to zero saves you only 12% while halving maintenance costs saves you 33%.

    Of course, hacking out a quick throw-away script in ten minutes, rather than an hour, is a big win. But for production code that must be maintained by many different programmers over a period of many years, it is more important to focus on maintainability.

Re: Perl Elitist Code vs Functional Code
by chromatic (Archbishop) on Aug 11, 2012 at 03:29 UTC
    So I am going to pose a simple question please do not start a super flame war.

    Flame wars are the inevitable results of posting false dichotomies.

Re: Perl Elitist Code vs Functional Code
by davido (Cardinal) on Aug 11, 2012 at 05:49 UTC

    Bloating something that could be done robustly, maintainably, and with clarity from fifty lines to two hundred isn't a practice I would consider "best."

    On the other hand, taking something that could be done robustly, maintainably, and with clarity in 200 lines, and instead writing it without those qualities in fifty lines could be a bad practice.

    If you haven't yet seen the benefits of modularity, generalized solutions, maintainability, separation of concerns, thorough testing, and tools such as version control, I recommend going with the flow for now, and opening yourself to trying to understand why so many others consider such practices meritorious.


Re: Perl Elitist Code vs Functional Code
by tinita (Parson) on Aug 11, 2012 at 10:46 UTC
    strange. seems whatever perl programmers do, it's wrong. the usual accusation is, "elitist" code is short and difficult to read. now you accuse "elitists" to write modern code with best practices that might take a bit more space. so what can the elitists actually do to be not accused? *sigh*
Re: Perl Elitist Code vs Functional Code
by CountZero (Bishop) on Aug 11, 2012 at 07:20 UTC
    Sometimes all you have is 10 minutes and then the choice is easy to make.


    A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

    My blog: Imperial Deltronics
Re: Perl Elitist Code vs Functional Code
by BrowserUk (Pope) on Aug 11, 2012 at 11:04 UTC

    You came here; you asked your question. They've already got to you.

    You are giving a damn about what they think of your code. It's all slippery slope from here on in.

    I now ask for a moment of silence ...

    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.

    The start of some sanity?

Re: Perl Elitist Code vs Functional Code
by sundialsvc4 (Abbot) on Aug 11, 2012 at 14:21 UTC

    Let me draw a comparison with the building trades.   “Home Depot® did not become a gigantic company by selling good-quality stuff to people who know what they are doing.”   You can take your own home and by-and-large do whatever you want to with it.   If you need to hold something up, you can saw a couple of two-by-fours and whack together a little improvised saw-horse and no one other than yourself will see it.   But a professional home-builder, who has done this hundreds if not thousands of times by now, will take a completely different approach.   This person will build not only for the present but for the future, knowing not only (and much better than you do or even could) that the structure (s)he is building will last, but also anticipating what experience has taught might happen.   Right down to building the thing upon a rock and not the shifting sand.   There are building codes, inspection programs, and minimum materials standards which a professional will scrupulously follow, and not merely because the law requires it.   The professional knows that (s)he is paid to know what the homeowner does not, and to build quality structures with the professional’s name on it.   Professionals eat very well.

    Over the past thirty years, I have myself spent a lot of my time ... in fact, the preponderance of it ... cleaning up after the work of the amateur, the “agile,” the arrogant, and most especially the unprepared.   It is difficult work which I compare to that of the Red Adair well-fire fighting teams, and it should never have been that way.   I suppose I should be grateful, though, that there probably will always be an endless supply of hacks who run a project straight into the ground and then jump ship.   Those people have been good to me, although not to the then-desperate people who’ve engaged us.

Re: Perl Elitist Code vs Functional Code
by xyzzy (Pilgrim) on Aug 11, 2012 at 15:51 UTC

    Most of our esteemed Monastery Elite are taking the expected position that this so-called "Elitist" code, with it's mandatory OO design and dependence on modules to perform even simple tasks is better because it makes your code "clearer" and "easier to maintain".

    The more attuned monks are adding that, while a 10-minute hack will always be better than an hour-long struggle when solving a single, specific problem, most of these small hacks will eventually grow into full-fledged packages and distributions, even if they were originally never designed to do more than that one small function.

    I am curious as to the turning point at which one should abandon the hack in favor of a package. For example, to tie in the reference to the Unix shell vs. Perl post, I have a collection of tiny hardware monitoring shell scripts that run every second and output to the notification area of my window manager. Right now there are three "module" scripts, one "daemon" that is required by a "module", and one that runs each "module" and compiles/formats the output onto a single line. Most are 3-5 lines long, one is about 15 or so because it has to do a switch on the different battery states. I wrote the first version of these over a year ago when I first started using dwm, and recently rewrote them for my new netbook almost from scratch and with considerable improvements as I have learned more about bash scripting. Over the last year, I have thought many times, "Hmm... If I combine everything into a super-duper Perl script I can put everything into separate packages and use better logic and tie in CPAN modules and event handling and all sorts of other fun stuff. But-- if I try to make the move from thinking about to writing it, I end up worrying too much about scary OO concepts and being unsure about how to actually prototype everything I want to add without limiting my options. Also I'm a little worried about a tradeoff in resource use, although that shouldn't really be that much of a concern. I kinda lost my train of thought, but I guess the point is, even when you have an idea to expand a quick and simple hack, and when know exactly what kind of features you could get out of it, the sheer complexity of converting everything into OO is too much to overcome the inertia of having a perfectly working thing right now. Unless, of course, you're an OOP elitist who spends the first 30 minutes of every script writing 50 lines of package infrastructure. (Sadly?) I am not experienced enough to do this comfortably.

    There is another important aspect to best practices--formatting and naming conventions, comments/documentation, stylistic things--and these I tend to disregard with such inconsistency that it's downright dangerous for anyone to look at my code if they are (not?) on mind-altering drugs. I never remember what I chose to name some random variable, I constantly mix awkwardly short control structures with my clear, fully-typed-out ones because I feel that it would save time and space on the screen, I don't think I have a single file longer than 50 lines that uses the same indentation or delimiter placement scheme throughout the whole file, and I usually only bother to comment when I know from the start I'm not going to finish something right away, or if I've already spent 20 minutes starting at something and don't want to figure it out a third time. This is probably much much worse than not using modules and such, and the Elitists will argue that writing code this way is not even "functional". I say it's functional if it works, and if I wrote it and it worked, then it's functional enough, until I have to go back and fuck with it some more. But I think the root of the problem is that Perl is positioned as this practical language with its quick-and-dirty one-liners and such, which makes it very attractive when you want to sit down and pump out a feature for something in 10 minutes. But then at the same time, it goes "No no no no, this is BAD PRACTICE, you really should treat it like one of those other languages, where everything should be verbose for the sake of clarity." And yeah, I suppose the latter is what all programming should be, regardless of language, and that's just something any code will have to deal with. Then this is really just a rant about how annoying it is to have to type the same thing all the time, because even if you claim that you don't rewrite your code, you do have to rewrite all those long method names, all those long object references, all that nice white space and other assorted "fluff", etc. Like, I've been working with Catalyst for way too long, and it's such a pain in the ass to constantly have to type out the same one or two-line snippets to handle routine things like reloading model data that was saved to the stash, or setting status/error messages (the "best practice" way is: $c->res->redirect($c->uri_for("/some/url/goes/here",{mid=>$c->set_error_msg('Oh noes, ANOTHER FUCKING ERROR!!!'}));$c->detach(); and that is with minimal whitespace). But it works. And it has big advantages over other "simpler" methods. So I grunt and I deal with it, but it certainly makes me laugh at the notion that Perl is, by its very nature, a terse language.

    ok. rant over. OBLIGATORY IMAGE MACRO

    $,=qq.\n.;print q.\/\/____\/.,q./\ \ / / \\.,q.    /_/__.,q..
    Happy, sober, smart: pick two.

      Frankly, it just sounds like you're doing it wrong.

      mandatory OO design and dependence on modules to perform even simple tasks

      I don't consider either of those to be best practices.

      you're an OOP elitist who spends the first 30 minutes of every script writing 50 lines of package infrastructure

      If it takes you 30 minutes or 50 lines to create boilerplate for a new class, then I think you are certainly doing it wrong.

      where everything should be verbose for the sake of clarity

      Verbosity doesn't lead to clarity. An obsessive devotion to terseness certainly is unlikely to lead to clarity, usually the opposite. But clarity doesn't require verbosity. And verbosity can certainly go far enough that it interferes with clarity.

      constantly have to type out the same one or two-line snippets to handle routine things

      That's the opposite of a best practice.

      I am not experienced enough to do this comfortably.

      Based on what you wrote above, I'd personally encourage you to ease off on worrying about OO, verbosity, and consistency and instead concentrate on trying to write unit tests. Not primarily for the sake of testing (though that will likely prove useful), but to help you see how to do practical abstraction.

      Code that can be unit tested well usually ends up being broken into logical subroutines, each with a unified and rather isolated purpose.

      I think you need to first concentrate on breaking code up into logical units and get more experience and skill at figuring out how to split code effectively, producing routines with small and clear interfaces and purposes that match their names.

      Once you start breaking code into subroutines with simple interfaces (which is called "modularity"), then you'll be able to wrap your head around moving some of those routines into a module.

      And if your code is well tested, then you'll build confidence in your ability to refactor things without breaking them.

      - tye        

      Don't constantly retype boilerplate code. Wrap it in reusable functions. Here's an example for your status/error messages...

      package MyProject::Sugar::Catalyst; use Sub::Exporter -setup => { exports => [ error_msg => \&_build_error_message, ], groups => { default => [qw/ error_msg /], }, }; sub _build_error_message { my ($class, $name, $def) = @_; return sub { my ($c, %arg) = @_; my $uri = $arg{uri} || $def->{uri} or die "No URI supplied"; my $msg = $arg{msg} || $def->{msg} || 'Oh noes, ANOTHER FUCKING ERROR!!!'; $c->res->redirect( $c->uri_for($uri, { mid => $c->set_error_msg($msg) }) ); $c->detach(); } }

      An example of usage:

      package MyProject::Controller::Foobar; use MyProject::Sugar::Catalyst db_error_msg => { msg => "Database Error!" }, http_error_msg => { msg => "HTTP Error!" }, error_msg => { }; ...; sub foo_bar { ...; db_error_msg($c, uri => $uri); } sub foo_baz { ...; db_error_msg($c, uri => $uri, msg => "specific error message"); }

      It makes things easier in the long run.

      perl -E'sub Monkey::do{say$_,for@_,do{($monkey=[caller(0)]->[3])=~s{::}{ }and$monkey}}"Monkey say"->Monkey::do'

      You got a ++ from me for your honesty. With such (bad) styling practice, I bet it will be hard for you to fit in a team.

      Weather you need OO and/or modularization or not is not important when no-one can read your code. Consistency is WAY more important then the way you write code (imperative, OO, recursive, whatever).

      Enjoy, Have FUN! H.Merijn
Re: Perl Elitist Code vs Functional Code
by blue_cowdawg (Monsignor) on Aug 13, 2012 at 17:33 UTC
        So is the functional coder worse then the elitist?

    The answer is 42... problem is you're not asking the right question.

    Let's set aside language for a moment. I've been programming in one language or another since 1972. Over that time period I've seen some really nifty code and I've seen butt ugly code. The difference in the two very little to do with the techniques used. I've seen functional coding that was elegant and I've seen OO code that was butt ugly. I've seen elegant OO code and I've seen code that looked like an obfu competition entry. Worst part of that is I've inherited my share of the butt ugly code to maintain.

    To me the difference between good code and bad code is readability and maintainability. I should be able to look at a piece of code and understand to some extent what is going on right away. I haven't much hair left and I get upset when I end up pulling more our trying to figure out what a piece of code does.

    As to your example of the "Elitist Code" let me say this. If some authoritative body for the environment in question or local culture dictates that your code should only work on 5.12 then I'd be asking the question of why? Usually there's a good reason and on some rare occasions I've been exposed the answer has been "because it's always been that way." If there's go good solid technical reason for the standards than suck it up and work within those parameters. If not then you may have an opportunity to change things for the better if you can keep your temper in check and provide good solid technical and/or business reasons for your proposals. Been there done that and it was a rewarding experience for me to influence change for the better.

    I am the right kind of lazy. (At least I'd like to think so) I use a lot of OO programming in both Perl and C++ when I write code. My reasoning has always been that I hate writing the same code over and over again. I'll give a for instance.

    I was once presented with a requirement to write some code to glean records from network equipment logs and look for patterns in the entries to detect malicious behavior. There were several flavors of that malicious behavior out there so I broke the job into several modules that made up the work.

    • Log reading and parsign
    • Pattern detection
    • Report Writing
    • Report archiving
    • Report delivery
    and that's an over simplified list. Each of the bullet items above became a module and while they took a long time to write the first time when I got a new requirement after the first were written adding a new pattern to took a lot less time than rewriting from scratch the whole script or modifying one already in place. My code almost literally looked like:
    use strict; use ABC::NE::Logparser; use ABC::Traffic::Patterns; use ABC::Report; my @recipts=( 'user1@abc.corp','user2@abc.corp','user3@abc.corp'); my $lp = new ABC::NE::Logparser; my $records = $lp->get_all('2011-01-01','2011-01-15'); my $matcher = new ABC::Traffic::Patterns('pattern1'); my $matches = $matcher -> find_candidates($records); my $rpt = new ABC::Report(); $rpt->generate($matches); $rpt->save(); $rpt->send (@recipts);

    If I had pursued the functional approach my code wouldn't look that clean for one thing, adding new functionality is a bit tougher (maybe not a lot) and someone who needs to look at my code has less to look at in one chunk than having to look at an entire script with lots of subs.

    Summing up my thoughts on this:

    • Code standards are a necessary evil for code that more than one person is going to be looking at.
    • Code standards are should be driven by business need, best practices and technical merit.
    • Code standards should not be developed in a vaccum
    • Write code with the thought in mind that someone else is going to read that code some day.

    There's a postscript to this posting: It is timely that the post I'm commenting on showed up on PM. The above mentioned "framework" for a lack of better term was inherited by some folks I've never even met. Since my personal email address was listed in the comments for the modules and scripts that I wrote they sent me an email to tell me that they were still using my code and had added several more types of pattern matching logic to what I had written. That code was written in 2001.

    Peter L. Berghold -- Unix Professional
    Peter -at- Berghold -dot- Net; AOL IM redcowdawg Yahoo IM: blue_cowdawg
Re: Perl Elitist Code vs Functional Code
by Anonymous Monk on Aug 11, 2012 at 06:17 UTC

    So I am going to pose a simple question please do not start a super flame war.

    Gee, a question about code quality, that includes no code to examine , and a warning not to flame -- how juvenile

      There is no code examples for a reason. I was just curious the entire post relates to quick hacks nothing that would ever become a full fledged script.
        the entire post relates to quick hacks nothing that would ever become a full fledged script.

        That's kind of the point, though: some people say such a thing doesn't really exist. In their experience, "quick hacks" have a way of growing into larger, more complex programs and being maintained by larger groups of programmers. So it makes sense for them to design all their programs as if that will be the case, even if the need doesn't seem to be there at the start.

        On the other hand, some of us have written plenty of quick hacks that have never needed to be expanded, or used and maintained by anyone else -- many were even used once and discarded. That being the case, any amount of time spent making them more than simply "functional" would have been a waste.

        Where you fall on a range between those two extremes depends on your own programming style and your work situation -- how often is your code reused or shared with others? Based on those things, you have to make your own judgments about your own coding needs.

        Aaron B.
        Available for small or large Perl jobs; see my home node.

        Most of us have maintained plenty of “quick hacks” that the (long gone ...) original designers never imagined would become a full-fledged script.   Or, likewise, dozens of quick-hacks that became in the aggregate a completely-unmaintainable full fledged system.

        And that is why, if you were hoping for a flame-war, you are not too likely to be rewarded with one.   People around here understand implicitly what the consequences of hack-code are, because they have had to deal with it for a very long time.   This is why they work as they do.   Even if you intentionally put in words like “functional vs. elitist,” you simply are not going to see this group dividing itself into two camps and bickering.

        Early in my career, I tried to fix the plumbing in my house.   The corroded, galvanized fitting that my predecessor had attached to a copper piping system broke off in my hands.   “OMG!!” I thought to myself, “I’m screwed!!”   But the home improvement gods were smiling that day.   The first guy who I called showed up immediately, fixed the problem in less than ten minutes, gratuitously checked the piping in the rest of the house, charged me $50 and left a stack of business cards.   (I vividly remember his assistant innocently asking, “shall I turn the water on now to check for leaks?”   With a calm but withering stare, he replied, “My work does not leak.”   The assistant hurriedly found something else to do.)   I told that story and passed out business cards.   In fact, I am still telling that story right now.   What I desperately wanted, and could not do for myself, is what he very-professionally did.   What I feared most was to him unthinkable.   He could have charged me any price he named, and I would have paid it and never forgotten it.   Well, I did pay the price he named, and I have never forgotten it.

        Ever since, and with every client we’ve ever had or will have, I have simply tried to copy the ways of that wise plumber.

        the entire post relates to quick hacks nothing that would ever become a full fledged script
        You probably should have mentioned this in the original post.
Re: Perl Elitist Code vs Functional Code
by sundialsvc4 (Abbot) on Aug 13, 2012 at 14:20 UTC

    There is, of course, the practical necessity for making a business-case for change of any sort.   Change itself is always de-stabilizing.   Depending on the importance and the visibility of the system, you must design and plan the change process very carefully.

      Change itself is always de-stabilizing.

      RFC:MUST it be always?

      Here you are then: Bug fixes are always destabilizing. They change the code and all change is destabilizing and, as the Great White Shadow teaches, change is to be feared. Therefore the practical necessity, lest one tread on the serpents of chaos, for making a valid business case in this market of synergistic tendencies toward the supreme bounds of workaday entropy hemmed by the ubiquitous market demands for profit realization within paradigm changing certainties of all battle-tested stripes. Waterfall! Sea change!!! {Cough} {Cough} Beware… You didn't know to be careful with important and visible systems before this moment—change management is a completely alien concept to absolutely all naïve elitists—but now you do!!!!11!!!11

Log In?

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

How do I use this? | Other CB clients
Other Users?
Others taking refuge in the Monastery: (5)
As of 2021-12-07 22:37 GMT
Find Nodes?
    Voting Booth?
    R or B?

    Results (34 votes). Check out past polls.