defining methods on the fly
flogic
created: 2006-08-02 15:59:48
I sure this breaks some rules of good programming practice, but it's still cool. And yes I'm planing on using it.
#!/usr/local/bin/perl

use warnings;
use strict;
use Want;

sub lvalueMethod($) {
  my ($name)    = @_;
  my ($package) = caller;
  my ($fn)      = $package . "::" . $name;

  no strict 'refs';
  *{$fn} = sub  : lvalue {
    my $self = shift;
    local *call = sub { $self->{$name}->(@_); };
    if ( !want('LVALUE') && ref( $self->{$name} ) eq 'CODE' ) {
      goto &call;
    }
    $self->{$name};
  };
}

{
  package Foo;

  sub new { bless {}, shift; }
  main::lvalueMethod("bar");
}

my ($x) = Foo->new();
print "$x\n";
$x->bar = 5;
print $x->bar, "\n";
$x->bar = sub { print( @_, "\n" ); };
$x->bar("Hello World");
Re: defining methods on the fly
created: 2006-08-02 17:46:32
See Class::Accessor::Lvalue
    (reference: Re: Class::Accessor and Damian's PBP)

Another previous post: RFC: Autogenerating lvalue methods

More Discussion:
  Re: Perl OO and accessors
  Experimenting with Lvalue Subs
Re^2: defining methods on the fly
created: 2006-08-03 10:14:42
Hmmm beaten to the punch again... Well at least it was an interesting learning experience.
Re: defining methods on the fly
created: 2006-08-02 18:15:37
I sure this breaks some rules of good programming practice, but it's still cool. And yes I'm planing on using it.

I hate this attitude. :-(

In all those threads that asked why people were abandoning Perl: well, I think it's mostly this point of view: the belief that "cool" trumps "good practice", "flexible" trumps "well defined", and "clever" trumps "simple".

I hate "cool" code. I like simple code that works. :-(

Re^2: defining methods on the fly
created: 2006-08-02 18:48:37
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.
Re^3: defining methods on the fly
created: 2006-08-03 09:42:33

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
Re^4: defining methods on the fly
created: 2006-08-03 10:36:06

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.
Re^5: defining methods on the fly
created: 2006-08-03 11:55:06

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).

Re^6: defining methods on the fly
created: 2006-08-03 14:02:37
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.

In what sense do they prevent you from doing your work?

If you have another developer on your team who persists in using idioms you don't understand, either ask for help learning the idiom and decide if it's worth using, or, as a team, decide not to use that idiom. (If you can't do either, your code maintenance problems have very little to do with technology.)

Re^7: defining methods on the fly
created: 2006-08-03 15:10:57

Hmmm. I think you caught me. What I really want is for you (in the generic sense) to dumb down your code so I can easily understand and adopt it and so that it doesn't take much time for me to use it to do my work. When you don't cooperate with my selfish goal but instead have fun with your own elegant approach, then I get peevish. After all, it isn't all about your ego, it is about my paycheck. :)

Either that, or I just got up too early and am cranky.

Update: Strange as it may seem, I'm not being sarcastic, here. I realized that my frustration was founded in the fact that, as BrowserUK pointed out earlier, I stopped learning Perl when I had enough knowledge to get my immediate work done, and I resent the (sometimes perceived as oh-so-clever elitist) folks who were more thorough in learning the language and can thus fully use its capabilities without having to puzzle over it.

Why Idioms
created: 2006-08-03 17:29:39
When you don't cooperate with my selfish goal but instead have fun with your own elegant approach...

Please don't put words in my mouth.

I've used a lot of obscure and esoteric features of Perl. Some were for good reasons and some were for very bad reasons.

I've also spent five years writing tests, writing test modules, giving talks on how to test Perl, and writing books and articles on how to make Perl code more maintainable. It would be nice if people would take that into account before jerking their knees so hard they mistakenly hit enter before thinking about what I said.

The presence of idioms in Perl the language or in code written in Perl is not the problem.

The problem is in people using idioms badly, ineffectively, and antisocially.

Take CPAN://P5NCI for example. There aren't a lot of people who can look at that code immediately and tell what's going on, or how it works. Yet also look at CPAN://P5NCI::Declare and tell me that doesn't make a lot of maintenance problems related to XS and language bindings just go away. If the people who just wanted idioms and weird features and stuff they don't understand to go away had their way, I couldn't have written either module.

Remember, there are people on this site who don't understand hashes, let alone map or anonymous functions or closures. I don't expect them to maintain my code, not because I revel in complexity or have some ego complex about being the smartest programmer in the room. (Trust me; I know way too many other programmers to believe that.)

I don't expect them to maintain my code because they don't have any business maintaining my code without more experience and at least some guidance from another experienced programmer.

Now if, some day in the future, I find myself on a programming team where the team's guidelines are to avoid anonymous functions or closures, I won't necessarily like it, but I'll program that way (and I'll probably try to explain how they work to the rest of the team and get them back on the approved list).

I'm not giving up all of the great features of Perl that make me more productive and make my code more powerful, more concise, more expressive, and more maintainable just because someone, somewhere might not understand them. I'll write tests. I'll write documentation. I'll explain it over and over. Yet expecting people not to have to learn anything to maintain code is silly and wrong and a grave technical risk and I'll keep saying it until people listen.

Update: corrected module name

Re^5: defining methods on the fly
created: 2006-08-03 20:20:32
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".

Re^4: defining methods on the fly
created: 2006-08-03 11:07:06
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
created: 2006-08-03 10:44:44
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...

Re^4: defining methods on the fly
created: 2006-08-03 12:09:56

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
Re^5: defining methods on the fly
created: 2006-08-03 18:58:52
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.

Re^6: defining methods on the fly
created: 2006-08-04 04:25:57
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.
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.

So any use of runtime redefinition is bad? Even when it lets you abstract duplicate code, do like better testing, etc.?

Throwing away a useful programming tool because some people misuse it is like throwing away electric drills because some idiot uses it to mix their smoothie and manages to put a hole in their hand.

Re^7: defining methods on the fly
created: 2006-08-08 15:30:28
Throwing away a useful programming tool because some people misuse it is like throwing away electric drills because some idiot uses it to mix their smoothie and manages to put a hole in their hand.

If someone says "I know this is bad carpentry practice, but I'm using my electric drill to mix smoothies", I cringe inwardly, and I don't hold out much hope for the state of their hands. ;-)

Re^4: defining methods on the fly
created: 2006-08-03 12:24:41

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.
Re^5: defining methods on the fly
created: 2006-08-03 16:14:02
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.

Ahhh... I get it. You bought into the myth that because you're a programmer, you should be pampered and spoiled, and treated better than everyone else, because you're special. You're not like those non-tech scum, right?

It's crap; and the .com bust proved it. Pampering a bunch of spoiled brats leads to... no increase in productivity, and a bunch of pampered, but still spoiled brats. Silicon Valley leaks money like a sieve... most programmers aren't paid that much; I flat out refused to cash in on that nightmare, becaue I saw all the snake oil that was being peddled down there, and refused to be a party to bilking clueless investors out of their money.

It's because if you deskill a job; take away a workers pride in the job they do;

A worker should take pride in every job they do; the pride comes from doing the job well, not from being pampered. A real man learns to take pride in a floor well swept, garbage well cleaned, or anything done right. In coding, that includes code written to conform to the standards of his fellow man; not "rockstar" coders writing clever, unmaintainable code to tickle their own ego.

eliminate personal innovation, flair--and yes--ego from the workplace;

Whine, whine, whine! Your personal ego is not what motivates a normal person; the real motivation is to do the job right, so that everyone can understand it. Ego and selfishness lead to poor products; people do better when they co-operate, not fight to screw each other over.

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

Blah, blah, blah... doom and gloom, lack of creativity -- oh, my! Programming should be a rote job; it's just the act of documenting a known solution to a known problem. The hardware guys build the machines. The mathematicians prove the algorithms work. The 0.1% in R&D design something new. Everyone else plugs in busines rules into business needs, adding the customizations to known wheels in known ways. It's NOT high art, no matter the typical programmer conceit.

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.

"Innovations" are overrated; the world is full of innovative ideas that just aren't practical to implement. Everyone and their dog has some great new, "world chaning idea". The tiny little corner that is R&D is the place to test those out; not the 99.999% reality that is the real business world. Skills are what matter; especially the skill of discerning what is compatible with existing standards, and how to conform to them. Egos should be left at the door in every line of work.

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.

Bah. A man works because the work is worthwhile, and the pay is worth it. If the rival has a better job, and/or better pay, then anyone will leave. That's just the nature of the market; programming is not special in this regard.

Re^6: defining methods on the fly
created: 2006-08-03 16:46:08
Programming should be a rote job; it's just the act of documenting a known solution to a known problem.

A good programmer only solve the problem once. A good programmer eliminates as much of the rote as possible.

It comes back to that flexibility your so afraid of. I suppose if you don't understand flexible code, its much more comforting to just pound out the same solution over and over again...

Re^7: defining methods on the fly
created: 2006-08-03 19:25:23
A good programmer only solve the problem once. A good programmer eliminates as much of the rote as possible.

Where does the "good" programmer formally prove that his solution is correct, or even workable?

Oh, right... he doesn't. He just slings "flexible" ad-hoc, undocumented code, and ensures that it's so obfuscated that that no one else can ever read it.

And then his semi-documented work of "genius" keeps him in job security until his flawed system can be analysed sufficiently well to be replaced with a simple system that actually does the job that was wanted in the first place.

Re^8: defining methods on the fly
created: 2006-08-03 21:00:59
Well, if your argument is that good programmers are bad programmers, then all of your points make sense...
Re^8: defining methods on the fly
created: 2006-08-04 04:16:36
Where does the "good" programmer formally prove that his solution is correct, or even workable?

The same way everybody else does - tests and documentation.

Re^6: defining methods on the fly
created: 2006-08-03 17:09:49
Programming should be a rote job; it's just the act of documenting a known solution to a known problem

Your post is very long, and I hate to sum it all up with such a tiny quote, but I think the portion I quoted is close to the crux of the disagreement here. Your programming experience is evidently all business all the time. Not every programmer lives in that world. Some people really are solving interesting problems, with the computer being just one tool in the problem solving chain. And as a word of notice, your apparent (and almost hyperbolic) failure to recognize that will put you at odds with a large portion of the Perl Monks population. I wish you the best of luck, but be prepared to write a lot of very long posts with excessive use of bold.

Re^7: defining methods on the fly
created: 2006-08-03 19:07:54
Some people really are solving interesting problems, with the computer being just one tool in the problem solving chain.

They're the 0.0001% case. They should learn to recognize it.

Re^6: defining methods on the fly
created: 2006-08-03 17:18:42

I spent the last 6 years NOT working, and living off the ample proceeds of my skill, dedication and innovations of the previous twenty-five as a programmer and analyst.

In that time I encountered several lower and middle managers who expressed similar views to those you've just expressed. I even had the misfortune to work under one for a short time, though I mostly managed to avoid that situation by weeding them out at the interview stage. S'funny how they all thought that they were interviewing me.

In every case they were failed programmers who had had been moved sideways into management to get them out of the way. A common, but ultimately destructive practice in corporations with old-style, job-for-life terms of employement dating from circa 1975. Sidelined, and on the long slide into a career cul-de-sac, their embittered "professionalism" slowly takes it's tole upon all who work under them, and the teams and departments they run.

Enjoy your trip. It'll be a short one.


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.
Re^7: defining methods on the fly
created: 2006-08-03 19:14:44
Ah.

So I'm a failed programmer, and you're rich, and smarter than I'll ever be?

Thanks for not making this personal. I give up; you're smarter, you're richer, I guess you're just better than I am, so I should shut up, and listen to you, right?

Clearly, writing self-modifying code is the right way to go. Obfuscation based job-security all the way!

It's what all the Perl contractors are doing these days! Why shouldn't I join the bandwagon, and get rich like you! Stupid ethics I've got; trying to do a good job instead of screwing the client and running away to the next job before I get caught!

You're right. I'm really dumb. :-(

Re^8: defining methods on the fly
created: 2006-08-03 20:11:30

Lose the chip on your shoulder, your burden will be lighter.


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.
Re^9: defining methods on the fly
created: 2006-08-04 12:42:17
First you brag: I spent the last 6 years NOT working, and living off the ample proceeds of my skill, dedication and innovations of the previous twenty-five as a programmer and analyst.

Then you sneer: In every case they were failed programmers who had had been moved sideways into management to get them out of the way... Enjoy your trip. It'll be a short one.

Then you blame someone else for your bad attitude:Lose the chip on your shoulder, your burden will be lighter.

You really are a contractor, aren't you? ;-)

Re^10: defining methods on the fly
created: 2006-08-04 12:54:56

If you think that not working for the last 6 years is bragging, then it's no wonder that you misinterpret the rest.

You really are a contractor, aren't you?

Yes I was. I was someone who's employment and performance was subject to review every 6 months for nearly 20 years, and yet the shortest duration of any my jobs was 2 1/2 years, and the longest over 8 years.

Think about that. Every 6 months, my employers had the opportunity to dispense with my services without even having to explain why. No warnings. No justifications. No tribunals or appeals. Just times up, goodbye. To be extended 15 times by the same employer meant I must have been doing something right don't you think?


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.
Re^4: defining methods on the fly
created: 2006-08-03 13:51:53

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
Re^4: defining methods on the fly
created: 2006-08-03 13:55:22
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.

Re^5: defining methods on the fly
created: 2006-08-03 17:00:41
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?

Re^6: defining methods on the fly
created: 2006-08-03 17:21:39
It is a straw man argument because you chose a single easy example where something was flexible but ill defined to refute the claim that flexible is not an antonym of well defined.

All you did was show that flexible is not a synonym of well defined, but that was never assertion.


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.

So he was doing exactly what you are arguing for: Removing the cleverness. In his mind, instead of using the fancy-dancy clever recursive function calls, he used a simple-straight forward state machine. Anyone can understand a state machine! You can always break it down into a series of boolean logic statements, what's simpler than that?

Its exactly what BrowserUK is pointing out. What is "clever" and what is "simple" depends entirely on your level of understanding, and your training.

Re^4: defining methods on the fly
created: 2006-08-03 13:58:44
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.

Re^5: defining methods on the fly
created: 2006-08-03 16:52:03
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...

Re^6: defining methods on the fly
created: 2006-08-03 18:05:27
And your mother is obviously going to be writing well written and easily maintainable code using good programming practices with no training whatsoever, because is just that easy.

After all, it takes a degree in computer science before you can screw up programming.

Re^7: defining methods on the fly
created: 2006-08-03 18:36:11
No. It didn't say it was easy. I never said it didn't require training. I said it was important, and was a skill that could be learned by normal people; just as technical writing can be learned by normal people.

Good technical writing is hard, and the better it is, the simpler it seems, because that's the point of good technical exposition. Good code is like that, too.

Re^8: defining methods on the fly
created: 2006-08-03 21:25:06
It didn't say it was easy. I never said it didn't require training. I said it was important, and was a skill that could be learned by normal people

Thats certainly not my interpretation of what you wrote, but since you wrote it, I guess you'd know better than me.

Of coarse anyone can learn it, but until everyone has learned it not everyone can fix it.

Re^8: defining methods on the fly
created: 2006-08-04 00:24:52

Actually no. Most normal people can't write good technical documents and can't write good code and can't be taught to do either. I know a lot of people I consider fairly normal and I know that there are domains of ability that they just are not suited to venture into, just as I know that there are things that I can't do well.

The concept that all people are created equal is a complete fallacy. Damn good thing too! Life would be a whole lot less interesting if everyone had the same abilities and perceived the world in the same way.

Even in the very narrow domain of programming there are a huge range of abilities and knowledge domains. No programmer encompases the range of skills, or even potential skills, to be productive with all techniques and in all problem domains.

It's not just training, it's a question of aptitude and interest. Few people have an interest in programming, and even fewer have an aptitude for it - the same is true for technical writing.


DWIM is Perl's answer to Gödel
Re^6: defining methods on the fly
created: 2006-08-03 19:09:56
The real mistake seems to be the notion that experts aren't needed, domain knowledge is irrelevant...

That was precisely and simply and exactly my point. I don't care if a novice can't maintain my vector space categorizer because it uses some advanced programming techniques. If you hire a novice without domain knowledge to maintain that code, your problem is completely exactly not that he might, gasp horror, encounter a closure in my code.

Re^3: defining methods on the fly
created: 2006-08-03 13:45:57

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. :)

Re^4: defining methods on the fly
created: 2006-08-03 16:55:16
Thanks. I'm glad *someone* gets it.
Re^3: defining methods on the fly
created: 2006-08-03 17:21:26
Applauses++


Re: defining methods on the fly
created: 2006-08-02 21:51:50

Just keep in mind that you invalidate your method-lookup cache everytime you invoke that code. Normally once perl knows what function belongs to a method call on an object from a particular class it's able to cache that and not do the work of looking all around ISA. Whenever you change something that could cause the cached value to be incorrect, perl discards all it's cached information. Those somethings are changing @ISA anywhere or altering the symbol table. Glob assignments like you did are one of those explicit reasons. Your code won't even work unless perl does this.

So just be aware you're making perl's OO slow for you. It has to do work that most people's perl won't have to.

⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re^2: defining methods on the fly
created: 2006-08-03 10:37:53
hmm... Does the cache get rebuilt? And does the second glob assignment cause the same problem? Class::Accessor::Lvalue (mentioned above) uses an eval. Is the eval faster?
Re^3: defining methods on the fly
created: 2006-08-03 12:18:38

Yes, the cache is rebuilt. You're just resetting it. All new method lookups after it's been reset are cached until it's reset again. Here's some code I ran in bleadperl which includes a function to look at the version number of the method lookup cache. Things that you do once during setup aren't usually of any account. It's worth blowing your cache then because you get all the utility of whatever it is that you stopped to do and you don't usually incur lots of extra runtime work. When you blow your cache during your run you impact your overall performance because now you're penalizing all the time consuming regular stuff too.

use B 'sub_generation';
sub show_cache_version { print sub_generation, "\n" }

show_cache_version;    # 554
{
    show_cache_version;    # 554
    local *call = sub { };
    show_cache_version;    # 555 <- @ISA cache reset
}
show_cache_version;        # 555

⠤⠤ ⠙⠊⠕⠞⠁⠇⠑⠧⠊

Re^4: defining methods on the fly
created: 2006-08-03 15:14:08
The following modification does not assign to a glob. Do this avoid the cache reset issue?
#!/usr/local/bin/perl

use warnings;
use strict;
use Want;

sub lvalueMethod($) {
    my ($name)    = @_;
    my ($package) = caller;

    no strict 'refs';
    *{$package . "::" . $name} = sub :lvalue {
        my $self = shift;
        if (!want('LVALUE') && ref($self->{$name}) eq 'CODE') {
            goto &{$self->{$name}};
        }
        $self->{$name};
    };
}

{
    package Foo;

    sub new { bless {}, shift; }
    main::lvalueMethod("bar");
}

my ($x) = Foo->new();
print "$x\n";
$x->bar = 5;
print $x->bar, "\n";
$x->bar = sub { print( @_, "\n" ); };
$x->bar("Hello World");

Remember: There's always one more bug.
Re^5: defining methods on the fly
created: 2006-08-03 16:24:34
From my understanding of his response that avoids the issue.
Re^5: defining methods on the fly
created: 2006-08-04 13:37:53
The following modification does not assign to a glob.

Apologies if I'm misunderstanding something here, but isn't the following code assigning to a glob?

    *{$package . "::" . $name} = sub :lvalue {

Update: Thanks for the reply -- I was indeed "misunderstanding something here."

Re^6: defining methods on the fly
created: 2006-08-04 21:57:07
Apologies if I'm misunderstanding something here, but isn't the following code assigning to a glob?
*{$package . "::" . $name} = sub :lvalue {
True, but that wasn't what I was referring to. The above is only executed once. The concern was with the following line in the original code that was executed every time the method was called:
local *call = sub { $self->{$name}->(@_); };
By removing that line, my suggested code should not suffer from the method cache reset performance penalty that occurs each time the method in the original code is called.

Remember: There's always one more bug.
</