in reply to Re: defining methods on the fly
in thread defining methods on the fly

I hate "cool" code. I like simple code that works.

I hate this attitude. "Cool", or idiomatic Perl is simply code that uses the full expressive power of Perl.

If you do not appreciate just how much your every day Perl programmer relies on Perl's coolness, go learn Cobol'74 (or even '85), or Fortran IV. Once you've spent a few days dealing with the "simplicity" of those languages, you'll soon realise that almost every line of every Perl program is packed with "cool" idioms--including your own code.

The difference between the judgement of "acceptable cool", and unacceptable cool Perl idioms generally amounts to whatever point the person judging reached before they decided that they had learnt enough Perl. At that point, anything they did not bother to familiarise themselves with--so that they could read and understand "advanced Perl idioms", rather than throwing their arms up in disgust at anything that requires them to think twice about--is distained.

Cool it not an antonym of good practice.

Flexible is not an antonym of well defined.

Clever is not an antonym of simple.

That does not mean that you cannot write bad code using cool idioms, but it is equally possible, just as easy, and arguably more prevelent, to write bad code using "simple" Perl.


Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^3: defining methods on the fly
by ptum (Priest) on Aug 03, 2006 at 13:42 UTC

    Don't lose sight of the fact that the OP was unabashedly admitting that 'good programming practices' were being ignored in favor of the 'coolness' of the idiom. That's where I draw the line -- use all the expressive power of Perl you like, but do it consistently and carefully and, for crying out loud, thoroughly comment anything that is especially clever, elegant or obscure. I've had several occasions to bewail the unnecessary complexity of some code I had to maintain, only to discover that it was something I wrote (in one case, only a few months before).


    No good deed goes unpunished. -- (attributed to) Oscar Wilde

      What the OP actually said is

      I['m] sure this breaks some rules of good programming practice,

      Which reads to me a little like someone saying "I'm sure that it will offend someone somewhere for me to say this, but I really enjoyed the dog stew I was served in Cambodia"*.

      Given that site:cpan.org autogenerate methods a very quick query of CPAN shows up a large number of modules that either autogenerate methods for their own use, or provide the facility of autogenerating accessors and mutators for use by other class modules. And that many of these are written by some of Perl's biggest and most respected names. The basic idea is far from a uniquely obscure, dangerous or obviously "bad practice".

      Indeed, there is a strong argument that one of the major benefits of using a dynamic language is the ability to write code that generates code. This is epitomised by the Once And Only Once practice design principle of XP fame and was (I think) originally advocated in the book, The Pragmatic Programmer: From Journeyman to Master, which is generally very highly regarded.

      Without critiquing the OP's implementation, the basic idea is far from a "bad programming practice", and it is anonymonk's somewhat kneejerk reaction to the OP's use of the word "cool" that I was addressing.

      *I've never been to Cambodia!


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.

        I don't think I'm qualified to judge this specific implementation, or to weigh in on a particular 'good programming practice'. I was reacting to what I perceived as your er, kneejerk reaction, in seeming to generally defend 'cool' Perl idiom.

        I think you expressed your point of view well, when you indicated that resistance to a particular Perl idiom can be rooted in individual unwillingness to learn more Perl. But I think it is common for Perl developers to indulge their taste for the elegant at the expense of code clarity or maintainability, a natural pitfall of TIMTOWTDI. It may have been unfair for anonymonk to pick on the OP in this particular instance, but I don't think I am alone in wishing that some of the 'cute' idioms could be restrained so that those of us (I admit it freely) who haven't yet learned all of Perl could get on with our work.

        I know I'm out of my depth in arguing with you, and I hope I'm not just trying to have the last word, but I feel a little like George Bailey in It's a Wonderful Life, when he says to Mr. Potter, "They may be 'rabble' to you, but this 'rabble' you sneer at does a lot of the living and working and dying in this town. Is it too much to ask that they do that living in two rooms and a bath?" (original quote badly paraphrased).

        I'm sure this breaks some rules of good programming practice,

        reads to me like "I'm sure this breaks some rules of good programming practice".

      Well the question is more which practices does it ignore and in this case does it pay off? Personally I think it may well pay off so I'm using it.
Re^3: defining methods on the fly
by Anonymous Monk on Aug 03, 2006 at 17:45 UTC

    I'm curious, did you read and understand the entire code you are commenting on? Your response is like someone saying "I'm sure it won't be good for me but I love the taste of mad cow brains in my dog stew" and then responding with a list of many fine Cambodian restaurants that serve dog stew*.

    The primary feature of the code is not auto generation of methods, but of allowing methods to be replaced at will by assigning a code ref to an invocation of the method to be replaced.

    I am not too surprised that there may be rare situations where replacing method implementations willy nilly might be somewhat appropriate. I also suspect that I would manage to avoid such situations by virtue of a more restrained design sense and likely would eventually regret it if I didn't.

    But I agree with even the original poster that using the same one mechanism to change attribute values and to replace the methods used to implement an attribute is a violation of good coding practices. Such radically different operations should look different. Further, assigning a value to an attribute should look fairly innocuous while replacing a method implementation long after the object(s) have been created should provide visual cues as to how unusual of an operation it is.

    * Yes, that is a horrible analogy, which is appropriate as also being an analogy of the other horrible analogy. :)

      Thanks. I'm glad *someone* gets it.
Re^3: defining methods on the fly
by sh1tn (Priest) on Aug 03, 2006 at 21:21 UTC
    Applauses++


Re^3: defining methods on the fly
by Anonymous Monk on Aug 03, 2006 at 14:44 UTC
    Cool it not an antonym of good practice.

    Yes, it is. "Cool" means the ego of the programmer has somehow gotten involved, emotion has gotten involved, and the programmmer has run off the rails of professionalism.

    Good code is not "cool", because ego is not involved. The code is correct, and works. How the programmer *feels* about the code is irrelevant. Good code and good practice stands on it's own merits; "cool", and other subjective, emotional metrics do not.

    Flexible is not an antonym of well defined.

    "This function is ultimately flexible, just like a Turing machine!!! In fact, it emulates a Turing machine!" Which means, means, by definitiion, that it's impact on the problem to be solved is vaguely defined; absolutely nothing has been specified about the behaviour of how the final result will be generated. Running one turing machine inside another is the ultimate in power, flexiblity... and pointlessness.

    Clever is not an antonym of simple.

    Clever code requires thought to understand, because it's clever and tricky, and showcases the ego of the programmer. Simple code instead seeks to document the program requires, even as it fulfills them.

    idiomatic Perl is simply code that uses the full expressive power of Perl

    And using the full expressive power of any language is a mistake. I'm writing this in comprehensible English, not using the full expressive power of the language. If I tried to do so, neither one of us could understand it.

    The goal of programming is to write simple, correct, understandable code, not to stroke programmer ego, to be cool, to appeal to mathematical sensibilities, or any of a thousand mental pitfalls that modern programmers fall prey to.

    The difference between the judgement of "acceptable cool", and unacceptable cool Perl idioms generally amounts to whatever point the person judging reached before they decided that they had learnt enough Perl.

    Ad hominem, and unfair. I refuse to use many of the ugly idioms perl provides, because they grow increasingly complicated to understand, and I know, from experience, that my fellow programmers will fail to understand them even if I myself feel ever-so-clever for using them.

    I once wrote a "clever" one-line regexp, as an intellectual diversion. It never went near production. I showed it to my co-workers, wrote the requisite 20 lines of documentation to explain it, then re-wrote it as ten simple lines of obvious code, and put those into production, because that was the obvious thing, so that was the correct thing to write.

    That does not mean that you cannot write bad code using cool idioms, but it is equally possible, just as easy, and arguably more prevelent, to write bad code using "simple" Perl.

    Anyone can fix simple code, good or bad. You may not agree with what it does, but what it does is obvious. No one can fix bad, clever code without serious effort; it masks both the intent and effect of the code *simultaneously*, whereas simple code is bad at hiding both.

    I'm tired of tracing through 3,000 line mazes only to find out that partway through, some idiot quietly re-defined the function I was tracking...

      Wow. All that from 'cool','clever', and 'flexible'. Man I think you have some other issues at play here which is explained in the last line of your code. I can dig that, I had a bad experience with fish one time, I don't eat it now, but I don't go yelling at everyone who does calling them idiots. Bad analogy? Perhaps, but you stretched quite a bit in your little rant too so I think it is fair. "I've been down this road and got burned so no one should ever go down that road" is pretty weak as an argument. If you had someone redefine a function on you in the middle of debuging then be mad at that person, not at anyone who rights 'cool','clever', 'flexible' code.

      As a side note I would call code 'cool' if it did something in a quick clever fashion that i immediatly understood. Code I can't understand wouldn't be called cool, and code I could do simpler another way wouldn't be called cool.

      Clever would be code that uses an approach that isn't obviously found, but is easily understood. Ever learned the different sorting techniques and gone...wow thats clever!

      Flexible to me would mean that while the code has one specific goal in mind, it was written with the ability to extend its functionality and use it in as yet unforseen ways. The sort function in perl is pretty darn flexible and will let you do cool and clever things with it ;)

      Thats my two cents, take it, leave it, whatever.


      ___________
      Eric Hodges
        If you had someone redefine a function on you in the middle of debuging then be mad at that person, not at anyone who rights 'cool','clever', 'flexible' code.

        You did notice that this is exactly what the Original Poster's self-proclaimed "cool" code does, right?

        The point of his code is to let you add, define, and redefine attributes and methods at run time; this lets him completely alter the entire meaning of a entire class at any point in the program you he so desires.

        In short, he's destroyed the regular expectation about how classes and objects will behave. He's said doing this just because it's "cool" to do so. He outright admitted that he felt that he was using bad programming practices, but somehow felt that being "cool" justified bad programming.

        Do you wonder that I complained about this attitude? I think I am getting mad at the right person; the person who is about to redefine the codebase under me again, and the person who is teaching others to go do the same, without tempering "cool tricks" with the need to ensure that they're used carefully and correctly, and only when necessary.

      I'm tempted just to say "what BrowserUk said". But, I have something of my own to add:

      Good code is not "cool", because ego is not involved. The code is correct, and works. How the programmer *feels* about the code is irrelevant. Good code and good practice stands on it's own merits; "cool", and other subjective, emotional metrics do not.

      I simply wish to call BS. I have my reasons:

      1. Good code can be cool code too. "Cool" can mean a lot of things: innovative and interesting among them. Innovative approches to solving problems can fall well within best practices -- and even when they don't, sometimes they are such an improvement that they become best practices. Object-oriented methodology was novel "cool" code at one time -- and it broke the rules of procedural programming that were generally accepted. Yet it's become so useful that it's become a best practice in many organizations.
      2. Ego -- that is, pride in one's work -- is incredibly important to writing good software. Developing software certainly has disciplined aspects to it, but it's also a creative endeavor. So is designing a suspension bridge. Any master of any discipline will tell you that experience develops intuition. Intuition is nothing more than seeing something and knowing it's got potential (or not) because it "feels right" (or wrong). Granted, you should always back up such feelings with evidence before you go production, but that emotional process is essential to creative problem solving and efficient work.

      Yes, there are times when "creative" or "cool" solutions are inappropriate, but it is not (as you suggest) always inappropriate. It only becomes a problem when the niftiness of the solution begins to outweigh practical considerations -- when "cool" becomes more imporatant than "good".

      See, "cool" and "good" are not mutually exclusive.

      <radiant.matrix>
      A collection of thoughts and links from the minds of geeks
      The Code that can be seen is not the true Code
      I haven't found a problem yet that can't be solved by a well-placed trebuchet

      Have you ever seen footage of the 1950s office space? Row after row of identical desks, identical chairs, and identical typewriters; all rigidly aligned to the ordinals of the office walls and a regulation distance apart. No plants. No personal photos. Nothing to make one desk stand out from another apart from a discrete "g4" or similar. And of course the physical differences in the statutorily, near-uniformed apparelled occupants.

      Those practices evolved on the basis of the notion that each cog in the industrial office space was interchangable, and that any and all demarkation between cogs was a distraction from the process of work and the overall efficiency of the machine. Deskill the tasks, train lots of cheap competents and use them as components. Remove all ego, personality and variability from the equation and, the theory went, you arrive at a cost efficient industrial machine.

      Do you know why you don't see this type of office much beyond the early '60s? Why the Silcon Valley giants have jakuzies and sleeping rooms and one or two man offices? And why this is how the big name/success story in software development over the last 10 years r so goes about attracting new staff:

      Students, imagine if you will...

      A cafeteria where the food is plentiful, delicious and, yes, free.

      A workplace where dogs are welcome and there's no dress code.

      A workspace where the technology sitting on top of it is powerful enough to work through any computational challenge you can devise.

      A lunch table where you sit down and learn your tablemate is the world's leading authority on a problem you were only vaguely aware existed – and the guy next to her wrote the textbook you used last semester.

      A campus that offers not just free meals but also a gym, an endless pool, a volleyball court, razor scooters, massage therapy, laundry rooms and dry cleaning, and (of course) valet parking.

      With us so far? Now's when the fun starts. Working at Google means making a positive difference in tens of millions of lives every day. Do you love to critique the design of everyday things? Do you dream of working for an innovative, world-class organization? Are you looking to work with engineers to create products that improve the lives of millions? If so, Google may have a place for you. We hire exceptional people, at all degree levels, BS, MS, and PhD. We have offices all over the world including Mountain View, California; Santa Monica, California; Kirkland, Washington; New York, New York; Switzerland; India; and Japan, all working on the same cutting edge solutions. The people at Google love to work on innovative products and believe passionately in our mission: to organize the world's information and make it universally accessible and useful.

      It's because if you deskill a job; take away a workers pride in the job they do; eliminate personal innovation, flair--and yes--ego from the workplace; you get the cheapest per-hour labour bills, because you end up with the dregs of the profession. Those with low skills, no motivation to improve, that "occupy" theirs desk for the statutory minimum hours to fulfill their job descriptions, whilst turning out the bare minimum of lowest quality work they can get away with. Combine the low productivity with the high turnover and subsequent initiation and training costs and those low pay rates suddenly become a completely false economy.

      Until you can replace your humans with robots as the car industry did on their production lines, you'd better invest in training your programmers to a high standard, and valuing their innovations, skills and yes--egos. Show me a programmer who does it only for the money, and I'll show you someone who will be working for your rival next week or the week after.


      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      Lingua non convalesco, consenesco et abolesco. -- Rule 1 has a caveat! -- Who broke the cabal?
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
      A reply falls below the community's threshold of quality. You may see it by logging in.
      Anyone can fix simple code, good or bad.

      Oh good, the second great fallacy of maintainable software. I eagerly await your mother's patches to my vector-space text correlation engine.

        I eagerly await your mother's patches to my vector-space text correlation engine.

        Step 1: Read the specification of the algorithm from which you coded said engine. Step 2: Fix your coding flaws (the difference between what the algorithm says to do, and what your code does instead). Step 3: Profit. ;-)

        Note carefully: coding is NOT the same thing as developing new domain knowledge. Coders write down existing domain knowledge written in English, and translate it into steps simple enough for a computer to understand, in a way that is clear, obvious, and correct.

        Sometimes, in their hubris, coders make the fatal error of inventing their own domain knowledge instead of consulting the experts; this is a primary source of both coding errors, and badly re-invented wheels.

        To further confuse the issue, in some rare cases, such as the realm of mathematics, the coder may in fact BE the local domain expert, but make no mistake, the roles are distinct.

        A good expert still double checks his expertise; mathematicians peer review their algorithms among as many experts in the field as possible. Physicists don't trust an experiment until it's been duplicated multiple times. Engineers wait several years for a new concept to "stand the test of time" before they adopt it. Outside an R&D lab, people do what's been done before, and is known to be correct, and they rely on the knowledge of trained experts to accomplish it. For coders, that task is one of a highly specialized form of technical writing called "computer programming".

        If my mother was a PhD in Mathematics with a specialization in vector spaces, I doubt she'ld have much trouble debugging your flawed implementation; but only if that implementation was laid out in a way she could read and understand.

        Also, if my mother has access to a domain expert, and can understand what the expert is saying, she can fix the code, if it's well written. To do this, she needs good communications skills, and a minimal ability to read and write code in a uniform, obvious way. A basic understanding of the problem domain may also be of benefit.

        To me, it isn't a fallacy that anyone with a basic grounding in coding can fix code flaws, given sufficient documentation and clear code. The real mistake seems to be the notion that experts aren't needed, domain knowledge is irrelevant, or the insidious notion that arises in certain circles which suggests that coders are more important than the thing coded...

          A reply falls below the community's threshold of quality. You may see it by logging in.
      Cool it not an antonym of good practice.

      ..How the programmer *feels* about the code is irrelevant...

      Exactly. The "coolness" is irrelevant when determining the quality of the code. Which means "Cool is not an antonym of good practice".


      Flexible is not an antonym of well defined.

      "This function is ultimately flexible, just like a Turing machine!!! In fact, it emulates a Turing machine!" Which means, means, by definitiion, that it's impact on the problem to be solved is vaguely defined; absolutely nothing has been specified about the behaviour of how the final result will be generated. Running one turing machine inside another is the ultimate in power, flexiblity... and pointlessness.

      Besides the fact this is a blatant straw man argument, Turing machines are also well defined. Which means "Flexible is not an antonym of well defined".


      Clever is not an antonym of simple.

      Clever code requires thought to understand, because it's clever and tricky, and showcases the ego of the programmer. Simple code instead seeks to document the program requires, even as it fulfills them.

      I totally agree. "Tricky is an antonym of simple". Don't know why you brought it up as part of "Clever is not an antonym of simple" though.

        Besides the fact this is a blatant straw man argument, Turing machines are also well defined. Which means "Flexible is not an antonym of well defined".

        1) That's not just some straw man. Unfortunately, that's an example from real life. I've maintained code that had a finite state machine to emulate function calls embedded in... Perl, which does function calls: that is, a general state machine calling another general state machine. The author maintained that adding the list of functions to be called (with different names) as a list instead of "recursive function calls" was somehow easier to understand. He was proud of how flexible and dynamic it was. He's one of many bad Perl coders I wish I'd never met. :-(

        2) The machine is well defined. It's operation is not; it varies depending on the input, which is not specified. Is that specific enough for you?