By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
431,900 Members | 1,078 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 431,900 IT Pros & Developers. It's quick & easy.

How can I have one function call another function dynamically?

P: n/a

Folks,

I'm sure this can be done legally, and not thru tricks of the trade - I
hope someone can help.

I'm writing a 'tool' (a function) which can be used generically in any
of my projects. When it completes, it can call a success, or a failure
function. The names of these success, or failure functions will differ,
and I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...

Roughly speaking I want to have something like

function my_engine(success_function_name, failure_function_name)
{
// Processing code here chews data

// Then...
if(myResult==true)
{ success_function_name(); }
else
{ failure_function_name(); }
}

Anybody got any ideas/suggestions? I'm sure there was a js method that
I could use but I can't find reference to it in my O'Reilly JavaScript
pocket reference...

All help, via the newsgroup (so all can learn) will be greatly appreciated,

Thanks,
Randell D.
Jul 23 '05 #1
Share this Question
Share on Google+
39 Replies


P: n/a
Randell D. wrote:

and I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...


function callFunction(name)
{
var f = new Function(name+"()");
f();
}

But maybe it would be more convenient to just pass the function itself
as a parameter...

Robert.
Jul 23 '05 #2

P: n/a
ASM
Randell D. wrote:

Folks,

I'm sure this can be done legally, and not thru tricks of the trade - I
hope someone can help.

I'm writing a 'tool' (a function) which can be used generically in any
of my projects. When it completes, it can call a success, or a failure
function. The names of these success, or failure functions will differ,
and I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...

Roughly speaking I want to have something like

function my_engine(success_function_name, failure_function_name)
{
// Processing code here chews data

// Then...
if(myResult==true)
{ success_function_name(); }
try :
Function(success_function_name);
with calling
my_engine('success', 'failure');

or
{ success_function_name }
or ?
{ eval(success_function_name) }
and calling :
my_engine('success()', 'failure()');
else
{ failure_function_name(); }
}


--
Stephane Moriaux et son [moins] vieux Mac
Jul 23 '05 #3

P: n/a
VK
> I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...


It is very simple. Just pass *function references*, not function names.

<script type="text/javascript">
function f1(fun1,fun2) {
fun1();
fun2()
}

function f2() {
alert('f2')
}

function f3() {
alert('f3');
}

function init(){
f1(f2,f3);
}

window.onload = init;
</script>

Jul 23 '05 #4

P: n/a
VK


Robert wrote:
function callFunction(name)
{
var f = new Function(name+"()");
f();
}


What a hey is that? We're talking JavaScript here, not RobertScript :-)

Do you mind at the very least:
<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsobjfunction.asp>

Jul 23 '05 #5

P: n/a
Randell D. wrote:
I'm writing a 'tool' (a function) which can be used generically in any
of my projects. When it completes, it can call a success, or a failure
function. The names of these success, or failure functions will differ,
and I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...
Passing the name of a function is the wrong thing to do here. Instead you
should just pass the function itself.

Roughly speaking I want to have something like

function my_engine(success_function_name, failure_function_name)
{
// Processing code here chews data

// Then...
if(myResult==true)
{ success_function_name(); }
else
{ failure_function_name(); }
}


Just do it this way:

function my_engine(success_function, failure_function)
{
// Processing code here chews data

// Then...
if(myResult==true)
{ success_function(); }
else
{ failure_function(); }
}

This way the functions don't actually have to be accessible through global
names, you can also use anonymous functions, or functions defined inside
other functions.

Jul 23 '05 #6

P: n/a
VK wrote:

Robert wrote:
function callFunction(name)
{
var f = new Function(name+"()");
f();
}

What a hey is that? We're talking JavaScript here, not RobertScript :-)

Do you mind at the very least:
<http://msdn.microsoft.com/library/default.asp?url=/library/en-us/script56/html/js56jsobjfunction.asp>


Sorry? I did suggest that passing the function reference is probably a
better idea.
But what do you find wrong with my example? Are you saying it is not
valid JavaScript?
Jul 23 '05 #7

P: n/a
VK
> Are you saying it is not valid JavaScript?

*Roughly* that.

var functionRef = new Function(arg1, arg2, arg3, ..., argN);

where all args except the last one treated as function arguments, and
the last one as function body.
so:

var helloWorld = new Function("alert('Hello world!);");

equals to

function helloWorld() {
alert('Hello world!);
}
var alertType = new Function("obj","alert(typeof(obj));");

equals to

function alertType(obj) {
alert(typeof(obj));
}

As such Function will be evaluated on each call, it's performance is
lower than with standard function(). So it's suggested to use it only
if you really need to create run-time functions from the scratch.

Jul 23 '05 #8

P: n/a
VK wrote:
Are you saying it is not valid JavaScript?

*Roughly* that.

As such Function will be evaluated on each call, it's performance is
lower than with standard function(). So it's suggested to use it only
if you really need to create run-time functions from the scratch.


Yes, that is exactly what he asked for.
name -> function call
It could not have been done using a literal function to my knowledge.

Anyway,
eval(name+"()")
is a better solution.
Jul 23 '05 #9

P: n/a
On 15/07/2005 11:54, Robert wrote:

[snip]
It could not have been done using a literal function to my knowledge.
No, it couldn't.
Anyway,
eval(name+"()")
is a better solution.


No, it isn't. Passing a function object reference is much better, as
David describes, and it's what the OP should use.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #10

P: n/a
Robert wrote:

Hi,
eval(name+"()")
is a better solution.


Using "eval" as property accessing technique isn't really a good
practice, in the posted case the function is called from within a
function iself called directly, so something like
this[name]();
would be a better solution:-)

Anyway passing the reference, as yourself and others have suggested, is
the best - the OP just wasn't probably aware that functions are
first-class objects in javascript...
Cheers,
Yep.
Jul 23 '05 #11

P: n/a
Yann-Erwan Perio wrote:
Using "eval" as property accessing technique isn't really a good
practice, in the posted case the function is called from within a
function iself called directly, so something like
this[name]();
would be a better solution:-)


Ahh interesting. So many ways to achieve something in Javascript :)
Jul 23 '05 #12

P: n/a
Michael Winter wrote:
Anyway,
eval(name+"()")
is a better solution.

No, it isn't. Passing a function object reference is much better, as
David describes, and it's what the OP should use.


Yes, but that was not what he asked for.
Jul 23 '05 #13

P: n/a
On 15/07/2005 12:37, Robert wrote:
Michael Winter wrote:
[...] Passing a function object reference is much better [...]


Yes, but that was not what he asked for.


He asked how to have one function call another. His current approach is
to pass the name of that function, but I don't see why that should be
set in stone, particularly if there's a better way.

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #14

P: n/a
Robert wrote:
VK wrote:
Are you saying it is not valid JavaScript?


*Roughly* that.

As such Function will be evaluated on each call, it's performance is
lower than with standard function(). So it's suggested to use it only
if you really need to create run-time functions from the scratch.

Yes, that is exactly what he asked for.
name -> function call
It could not have been done using a literal function to my knowledge.

Anyway,
eval(name+"()")
is a better solution.


NO.

window[name+'()']

is a better solution.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #15

P: n/a
Randell D. wrote:
I'd like to know how I can pass the name of a
function to my tool, and how my tool can call the function, using that
name...


Wow, all these posts and no one answered your question :)

Passing a reference to a function is best, but not always possible or
practical.

Since functions are just properties of the window object, you can do:

function callfunc(name) {
if (typeof(window[name])=="function") {
window[name]();
}
}

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jul 23 '05 #16

P: n/a
Matt Kruse wrote:
Randell D. wrote:
I'd like to know how I can pass the name of a
function to my tool, and how my tool can call the function, using that
name...

Wow, all these posts and no one answered your question :)


That's not fair! I answered... just wasn't a very efficient way to do it :p
Jul 23 '05 #17

P: n/a
Randy Webb wrote:
window[name+'()']

is a better solution.


I'm now reluctant to submit window[]-based solutions, for at least two
reasons:
- window[] implies that the host is a browser; using "this" would work
on all browsers, provided the function is called as a member of the
global object,
- window[] implies that the conception relies on global functions, which
generally indicates a namespace pollution, therefore often a lazy
conception.

Anyway, in your example you have to put the parentheses outside of the
identifier, otherwise this won't work.

The following should help the OP into misunderstanding everything:-)

---
window["foo()"]=foo;
function foo(){alert("Hello, World!")};
function test(name){
this[name+"()"]();
}

test("foo");
---
Cheers,
Yep.
Jul 23 '05 #18

P: n/a
Yann-Erwan Perio wrote:
- window[] implies that the host is a browser; using "this" would work
on all browsers, provided the function is called as a member of the
global object,
Using 'this' is highly sensitive to the calling environment also. For most
situations, referencing window[name]() will work while this[name]() might
not.
- window[] implies that the conception relies on global functions,
which generally indicates a namespace pollution, therefore often a
lazy conception.


I disagree.

Most people developing javascript are not experts at the language by any
means. Most code does not make use of closures or inner functions, but
instead has a bunch of global functions.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jul 23 '05 #19

P: n/a
Matt Kruse wrote:

Hi,
- window[] implies that the host is a browser; using "this" would work
on all browsers, provided the function is called as a member of the
global object,
Using 'this' is highly sensitive to the calling environment also. For most
situations, referencing window[name]() will work while this[name]() might
not.
As you say, the "this" value depends on the way the function is called:
if called as a method, then the "this" value will be the reference of
the object of which it is the method, if called as a function then the
"this" value will be a reference to the global object.

So if you want a function generic enough to be called as a member of
different objects (global object, custom object), and only operate with
the global object for the "this" value, then indeed referencing "window"
directly would be a good option (while I'd prefer, personally, use a
construct with an inner function returning the global object).

However I feel that, when calling a function, the "this" value inside
should be already known and should not depend on how the function is
called (an external parameter of the function, lack of encapsulation).
- window[] implies that the conception relies on global functions,
which generally indicates a namespace pollution, therefore often a
lazy conception.

I disagree.

Most people developing javascript are not experts at the language by any
means. Most code does not make use of closures or inner functions, but
instead has a bunch of global functions.


Your argument, AIUI, is strange you know; you say you disagree that
global functions indicate a lazy conception, and then you justify the
point by precising that the guys using the "global functions" approaches
are not javascript experts.

What should I conclude from this? Should I trust so-called professionals
who can only use global functions, and don't even understand the
paradigm of the language they're using, to be skilled enough to provide
me with quality code?

Or would you rather defend that conceptions based on global functions
can be as good as conceptions using the javascript paradigm to its full?
Regards,
Yep.
Jul 23 '05 #20

P: n/a
JRS: In article <0DIBe.150880$on1.84486@clgrps13>, dated Fri, 15 Jul
2005 06:22:52, seen in news:comp.lang.javascript, Randell D.
<su*****@fiprojects.moc> posted :

Roughly speaking I want to have something like

function my_engine(success_function_name, failure_function_name)
{
// Processing code here chews data

// Then...
if(myResult==true)
{ success_function_name(); }
else
{ failure_function_name(); }
}


You can do that; you're passing the function as a parameter.

But the test line should be if (myResult) as comparing with true is
unnecessary.

You could also do

function Mine(X, Y, AF) {
// calculate with X Y getting answer R and result code Z
AF[Z] // call the Zth function in array AF
return R }

and call it as RR = Mine(XX, YY, [F0,F1,F2,F3,F4,F5]) which has
three parameters the last being an array of functions. You probably
won't want to, but it is illustrative to see that you can.
Sometimes I use
function FuncName(Fn) { // Fn is a function; return its name
return Fn.toString().match(/( \w+)/)[0] }
though it's just occurred to me that the matching may be sub-optimal -
though speed is not important as I use it.

--
John Stockton, Surrey, UK. ?@merlyn.demon.co.uk Turnpike v4.00 IE 4
<URL:http://www.jibbering.com/faq/> JL/RC: FAQ of news:comp.lang.javascript
<URL:http://www.merlyn.demon.co.uk/js-index.htm> jscr maths, dates, sources.
<URL:http://www.merlyn.demon.co.uk/> TP/BP/Delphi/jscr/&c, FAQ items, links.
Jul 23 '05 #21

P: n/a
Yann-Erwan Perio wrote:
Your argument, AIUI, is strange you know; you say you disagree that
global functions indicate a lazy conception, and then you justify the
point by precising that the guys using the "global functions"
approaches are not javascript experts.
To me, "lazy" means you know how to do something the right way, but choose
not to because it takes more effort. Someone who is ignorant of a more
advanced way of doing a task certainly isn't "lazy" if they do it in the
best way that they know how.
What should I conclude from this? Should I trust so-called
professionals who can only use global functions, and don't even
understand the paradigm of the language they're using, to be skilled
enough to provide me with quality code?
Sure, why not?

Do you think most of the code written in the world is written by experts in
the languages used? Far from it. There are few experts. Most code that I've
seen is written by moderately skilled programmers. Increasingly, much code
is written by junior programmers in India or similar places. Skilled
programmers who are experts in the language they are using are very rare,
IMO.
Or would you rather defend that conceptions based on global functions
can be as good as conceptions using the javascript paradigm to its
full?


It can be a complicated issue... I understand (now even more than
previously) how to use closures and other techniques which are more advanced
than most people ever face when touching javascript. [Note that I do not
consider myself an expert in the js language, but I do consider myself much
more experienced than the average person writing javascript] But in
developing code that will be maintained, implemented, and possibly enhanced
and customized by novice javascript programmers, it seems to me like a good
choice to program in a way that they will comprehend.

If I write code that is highly compact and obfuscated by advanced language
techniques, it becomes meaningless to the average javascript programmer.
Then they'll seek out a less-complex solution which they understand, but may
be written by someone at their own skill level and have problems. Which is
better? It's not as obvious of a decision as some would like to believe,
IMO.

I guess a fundamental question is: Given two sets of code - one written in a
manner that uses the language and its features to its fullest and one which
uses global functions and procedural style - that perform the same task
effectively, is one necessarily better than the other? And is that a
subjective or objective decision? Based ono what?

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jul 23 '05 #22

P: n/a
Robert wrote:
Randell D. wrote:

and I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...

function callFunction(name)
{
var f = new Function(name+"()");
f();
}

But maybe it would be more convenient to just pass the function itself
as a parameter...

Robert.

I'm reading through everyone's posts at the moment - my internet acces
is restricted hence I'm taken a bit by surprise on the feedback I've got
so far. I like your solution above because I can support it - however I
also agree with some of the arguements put forward by the others... I'll
read in to things further and then decide which solution to use.

Thanks for the help

randelld
Jul 23 '05 #23

P: n/a
Randy Webb wrote:
Robert wrote:
VK wrote:
Are you saying it is not valid JavaScript?


*Roughly* that.

As such Function will be evaluated on each call, it's performance is
lower than with standard function(). So it's suggested to use it only
if you really need to create run-time functions from the scratch.


Yes, that is exactly what he asked for.
name -> function call
It could not have been done using a literal function to my knowledge.

Anyway,
eval(name+"()")
is a better solution.

NO.

window[name+'()']

is a better solution.


This use of the window object (method?) I like... I'm going to play
around with it...

And with regards to eval - My experience thus far has been to avoid
using eval where possible because of its overheads... but excusing the
performance weight, its simple, and functional...

Thanks,
randelld
Jul 23 '05 #24

P: n/a
VK wrote:
I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...

It is very simple. Just pass *function references*, not function names.

<script type="text/javascript">
function f1(fun1,fun2) {
fun1();
fun2()
}

function f2() {
alert('f2')
}

function f3() {
alert('f3');
}

function init(){
f1(f2,f3);
}

window.onload = init;
</script>

I did originally try something like this but it failed - however from
what I have learned in previous posts, it is likely to have to have
failed because of the window object... I can't recall exactly (it was
one of my earlier attempts) but I think I had a child window call a
function which then called success/failure functions that existed in the
parent window environment...

I'm still learning... however I am grateful to your response.

randelld
Jul 23 '05 #25

P: n/a
Duncan Booth wrote:
Randell D. wrote:

I'm writing a 'tool' (a function) which can be used generically in any
of my projects. When it completes, it can call a success, or a failure
function. The names of these success, or failure functions will differ,
and I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...

Passing the name of a function is the wrong thing to do here. Instead you
should just pass the function itself.

Roughly speaking I want to have something like

function my_engine(success_function_name, failure_function_name)
{
// Processing code here chews data

// Then...
if(myResult==true)
{ success_function_name(); }
else
{ failure_function_name(); }
}

Just do it this way:

function my_engine(success_function, failure_function)
{
// Processing code here chews data

// Then...
if(myResult==true)
{ success_function(); }
else
{ failure_function(); }
}

This way the functions don't actually have to be accessible through global
names, you can also use anonymous functions, or functions defined inside
other functions.


The problem with the above solution is that I'm createing a generic tool
which won't know the names of functions to call when the results of
processing are true or false... This was my main problem - do make my
tool/function dynamic for other projects...

Thanks though for the help,
Randell D.
Jul 23 '05 #26

P: n/a
Matt Kruse wrote:
Randell D. wrote:
I'd like to know how I can pass the name of a
function to my tool, and how my tool can call the function, using that
name...

Wow, all these posts and no one answered your question :)

Passing a reference to a function is best, but not always possible or
practical.

Since functions are just properties of the window object, you can do:

function callfunc(name) {
if (typeof(window[name])=="function") {
window[name]();
}
}


Hmmmmm... at first I balked at your reply - but after a minute or so of
thinking, I can see what you're suggesting and again, it looks clean,
and something I feel happy that I can support. I had half an idea that
functions were objects from within a window, however I was calling them
wrongly... Using a variable name called success_function I had tried
doing something like

window.success_function();

but of course this failed with an error that success_function didn't
exist (thus telling me that success_function, a variable, was not
translated).

I'm still learning - and you've just thought me something nice above,
thanks

randelld
Jul 23 '05 #27

P: n/a
Randell D. wrote:

Folks,

I'm sure this can be done legally, and not thru tricks of the trade - I
hope someone can help.

I'm writing a 'tool' (a function) which can be used generically in any
of my projects. When it completes, it can call a success, or a failure
function. The names of these success, or failure functions will differ,
and I'd like to know how I can pass the name of a function to my tool,
and how my tool can call the function, using that name...

Roughly speaking I want to have something like

function my_engine(success_function_name, failure_function_name)
{
// Processing code here chews data

// Then...
if(myResult==true)
{ success_function_name(); }
else
{ failure_function_name(); }
}

Anybody got any ideas/suggestions? I'm sure there was a js method that
I could use but I can't find reference to it in my O'Reilly JavaScript
pocket reference...

All help, via the newsgroup (so all can learn) will be greatly
appreciated,

Thanks,
Randell D.

Many Many MANY thanks to all - you've given me some food for thoughts -
My internet access is restricted at the mo' so I'll go away and work on
some of the solutions everyone has proposed, and read into them. My
main concern is writing code I can support first followed closely by
something that is environmentally friendly on the systems resources...

Thanks again, I didn't think my question would prove such a large response,

Cheers
Randell D.
Jul 23 '05 #28

P: n/a
Yann-Erwan Perio wrote:
Robert wrote:

Hi,
eval(name+"()")
is a better solution.

Using "eval" as property accessing technique isn't really a good
practice, in the posted case the function is called from within a
function iself called directly, so something like
this[name]();
would be a better solution:-)

Anyway passing the reference, as yourself and others have suggested, is
the best - the OP just wasn't probably aware that functions are
first-class objects in javascript...
Cheers,
Yep.

My internet access is restricted (which is a shame) however you're
right, I didn't know that functions are first-class objects in
javascript. I have about a years worth of javascript behind me and this
will help push my skillset further... thanks

randelld
Jul 23 '05 #29

P: n/a
Matt Kruse wrote:

Hi,
To me, "lazy" means you know how to do something the right way, but choose
not to because it takes more effort. Someone who is ignorant of a more
advanced way of doing a task certainly isn't "lazy" if they do it in the
best way that they know how.
Ah now I understand your point, and realise I have expressed myself
inaccurately; what I meant by "lazy" was that the underlying conception
was simplistic, poor (a truly lazy conception being the shame of the
programmer).
What should I conclude from this? Should I trust so-called
professionals who can only use global functions, and don't even
understand the paradigm of the language they're using, to be skilled
enough to provide me with quality code?

Sure, why not?
An interesting answer, but ISTM that it is centered on what programmer I
should employ, not the quality I'm expecting.

At first I'd say that because they don't fully master the language, they
can only produce a limited solution to the problem, while an experienced
programmer would be able to produce a solution using the language at its
maximum. From a quality point of view the solution provided by the
skilled programmer is likely to be superior than the one provided by the
non-qualified programmer (whose quality would depend on the task to be
coded).

However, the real problem here is indeed a matter of expectations, i.e.
compare/estimate the difference of value and cost of the 2 solutions -
and then make the choice between the two programmers.
Do you think most of the code written in the world is written by experts in
the languages used? Far from it. There are few experts. Most code that I've
seen is written by moderately skilled programmers. Increasingly, much code
is written by junior programmers in India or similar places. Skilled
programmers who are experts in the language they are using are very rare,
IMO.
My experience so far yields the same impression.

This practice comes here for business reasons, though. The less skilled
a programmer, the lower his cost, the higher the margin you can have by
selling him to your customer (be it internal or external), the higher
the risk you're taking for your project (and therefore with your customer).

This is the art of the manager to be able to employ non-qualified guys
with qualified ones, so that he can reach the level of margins expected
by the company at a price sold by the salesman, using the experience of
his skilled employees to minimise the risk for his project.

<snip>
[Note that I do not
consider myself an expert in the js language, but I do consider myself much
more experienced than the average person writing javascript]
Given the code/advice you've been offering for years you're perfectly
entitled to:-)
But in
developing code that will be maintained, implemented, and possibly enhanced
and customized by novice javascript programmers, it seems to me like a good
choice to program in a way that they will comprehend.
This is certainly an important consideration a programmer must have when
writing code - but that's not the only one. If there's no added value in
using advanced conceptions then it'd be foolish to do so (for the
reasons you've explained, among others), however if there is a real
added value in using the language to its fullest then it'd be foolish
*not* to do so.

I understand that the average programmer may not be aware of these
techniques; it is however his responsibility/interest (and the
responsibility/interest of his management) to learn and understand them
when he comes across them, and gain the ability to re-use them.
Otherwise he's just accumulating a kind of experience that permits him
to sell himself at a better price without adding more value than the
average coder - in the end he's unlikely to be taken for the job.

<snip>
I guess a fundamental question is: Given two sets of code - one written in a
manner that uses the language and its features to its fullest and one which
uses global functions and procedural style - that perform the same task
effectively, is one necessarily better than the other? And is that a
subjective or objective decision? Based ono what?


Is that really a difficult thing to assess for someone familiar with the
two approaches? It should be easy to determine whether the conception
would benefit from data encapsulation, modularisation techniques, or
whether these techniques would simply burden the script in regards of
the task that is to be performed.

The problem, with closures, is that they aren't well-known, and are hard
to learn - which make people abandon their learning even before it's
seriously started. That's too bad, because the reward is worth the
effort, i.e. the value for the programmer, the manager and the customer
could only increase.
Regards,
Yep.
Jul 23 '05 #30

P: n/a
On 16/07/2005 01:12, Randell D. wrote:
Duncan Booth wrote:
[snip]
function my_engine(success_function, failure_function)
{
// Processing code here chews data

// Then...
if(myResult==true)
{ success_function(); }
else
{ failure_function(); }
}


[snip]
The problem with the above solution is that I'm createing a generic tool
which won't know the names of functions to call when the results of
processing are true or false...


The above will accommodate this. The difference between this and, for
argument's sake, Matt's is that you'd pass the name of the function at
run-time with his, whereas with the above you'd just pass that function. So,

function funcA {}
function funcB {}

my_engine('funcA', 'funcB');

becomes

my_engine(funcA, funcB);

This latter version is more flexible because to resolve the names in a
string version, the functions must be accessible at global scope (unless
you alter the interface or revert to eval), whereas with a function
object version, the functions can exist anywhere.

[snip]

Mike

--
Michael Winter
Prefix subject with [News] before replying by e-mail.
Jul 23 '05 #31

P: n/a
Matt Kruse wrote:
Yann-Erwan Perio wrote: <snip>
What should I conclude from this? Should I trust so-called
professionals who can only use global functions, and don't
even understand the paradigm of the language they're using,
to be skilled enough to provide me with quality code?


Sure, why not?


Maintenance costs are probably the best reason for preferring to employ
someone with good understanding of what they are doing. Not necessarily
because they will write code that is easy for all others to understand
but because, in acquiring their knowledge and experience, they are
likely to be in a position to be writing code that addresses the likely
issues from the outset and so creating code that does not need nearly as
much maintenance.

Consider the way in which amateurs and the inexperienced often approach
multi-browser coding. They discover an approach that works with one
browser, and then add branching and variations to accommodate other
browsers they encounter. An example might be this original code from an
externally soured script that I am responsible for maintaining:-

| if(ISIE){
| document.body.onload=load_functionality;
| }else{
| document.body.setAttribute("onload","load_function ality(event);");
| }
(and yes the ISIE test was - var ISIE = document.all ? true : false;)

The author had discovered that attaching an onload handler to the body
element in IE worked, and then discovered that Mozilla/Netscape/Gecko
was not interested and so trawled about for an alternative that would
work. As this in Intranet code and the spec is to support IE and
Mozilla/Gecko the code above satisfies that, but we all know that it is
twice as complex as it needs to be and extremely vulnerable to minor
revisions and new bugs in newer versions of even those two browser. It
is also code that is not very friendly to its environment, hogging the
onload event, and doing so differently in different browsers. These
things represent potential maintenance costs that would not exist in
code written by a more experienced author.

You will recall that Opera 6 was not a particularly dynamic browser. At
the time of the release of the significantly better, and genuinely
dynamic, Opera 7 much code had been written to exclude Opera 6 just
because it was an Opera browser, and so Opera 7 was also excluded. The
authors/owners of that code, assuming they perceived a desire to take
advantage of the new features of Opera 7, were faced with a cost for
code updating that could only be considered a maintenance cost.

Those of us who had been using feature detection, and particularly an
interest in dynamic DOM standard features, welcomed the arrival of Opera
7 as another dynamic visual browser with which our code would happily
act. I did not have to change a single line of my code at the time to
accommodate the arrival of Opera 7, it all just noticed the availability
of the features it needed and so used them. The total maintenance cost
of accommodating a new, and very different, version of a browser was
zero.
Do you think most of the code written in the world is
written by experts in the languages used? Far from it.
There are few experts. Most code that I've seen is written
by moderately skilled programmers. Increasingly, much code
is written by junior programmers in India or similar places.
Skilled programmers who are experts in the language they are
using are very rare, IMO.
It is in the nature of any skill that is more than trivial than any
population exhibiting that skill will vary in their mastery of that
skill. There will be relative novices alongside experts, and a spectrum
of knowledge and experience in-between. Things have to be that way else
the skills in question would die out as the individuals who posses them
age and die.

This is a reality that lends itself to hierarchical organisation. In a
big OO project there may be a couple of individuals with the skills to
handle the architectural aspects of the software design, a larger group
capable of designing, implementing and testing the main objects in the
design, and a majority who are best employed in writing the code that
uses those objects.

An important aspect of getting such a hierarchy to work for the benefit
of the project is drawing the important distinction between the internal
details of an object implementation and its public interface. The
programmes that use the objects in a system don't need to concern
themselves with the internal details of those objects, they just need to
understand the public interface. Internal complexity is not their
concern, and they are not going to be the people who maintain that code
(though they may acquire the experience to become the people who
maintain that code, but in doing so they would also become capable of
coping with its internal complexities).

Such a hierarchical organisation of skills gives everyone a place, and
reason to improve their skills; to move up the hierarchy (if they want
to). An organisation that says that everything should be written so that
the next trainee through the door can understand and maintain everything
would be throwing away the advantages of having more experienced
programmers, and removing the motivation of the programmers it does have
to improve their skills.
Or would you rather defend that conceptions based on global
functions can be as good as conceptions using the javascript
paradigm to its full?


It can be a complicated issue... I understand (now even more
than previously) how to use closures and other techniques which
are more advanced than most people ever face when touching
javascript. [Note that I do not consider myself an expert in the
js language, but I do consider myself much more experienced than
the average person writing javascript] But in developing code that
will be maintained, implemented, and possibly enhanced and
customized by novice javascript programmers, it seems to me like
a good choice to program in a way that they will comprehend.


The code that I cited above was inexpensively sourced form India. It is
simple in that it does not use any 'advanced' javascript techniques and
is relentlessly procedural, but it is also 4000 lines long, uses 200-odd
global variables to maintain its state and features, for example, a 500
line mouse move event handler.

In principal there is no single aspect of that code that could not be
understood by a relative novice at javascript. In reality the totality
is such a spaghetti mass of indirect interactions that I don't find it
easy to understand, and a novice would be utterly lost.

You cannot blame the Indian programmers for creating this code. They had
a specification and they got code out of the door that satisfied that
specification. The problem was that the authors of the specification
left the code design up to the implementers, and the implementers didn't
have the experience to do anything other than a massively elaborated
procedural implementation.

The result satisfied the specification but is nearly useless to us, as
even minor changes require a massive effort back tracking the spaghetti
to find all the points where they need to be enacted, and the nature of
the existing implementation makes more extreme changes completely
impossible. i.e. it is a maintenance nightmare, squandering all the
saving derived from its external sourcing because the time I spend
working on it is relatively expensive. But it would not help to have a,
theoretically cheaper, relative novice work on it either, as they would
spend significantly longer making the same changes and so cost as much
overall.

Eventually I will get the time to re-write it from scratch, and do the
OO implementation that it should have been from the outset. The result
will be unintelligible to its original author and many other novices,
but it will be objectively simpler, easier to maintain and (most
importantly) possible to extend in the direction that current thinking
looks like it wants to take it.
If I write code that is highly compact and obfuscated by advanced
language techniques, it becomes meaningless to the average javascript
programmer. Then they'll seek out a less-complex solution which they
understand, but may be written by someone at their own skill level
and have problems. Which is better? It's not as obvious of a decision
as some would like to believe, IMO.
This is where the distinction between the internal details of an
implementation and its public interface becomes significant. The
(non-public) web application that I am currently working on is a
windowing GUI inside a browser (in-window pop-ups) with 2000-odd
server-side forms potentially displayed in the windows within the
browser. So the client-side code mostly represents an environment that
is, more or less, used by the server-side forms. And the server-side
forms are written by server-side programmers who have very little (and
in most cases no) understanding of javascript, but that doesn't matter
as they are not using javascript directly they are using templates and
tag libraries. Other, more experienced server-side programmers have
written the templates and tab libraries and they have been using
javascript to interact with the client-side environment, but they also
have minimal understanding of javascript.

My responsibility is to provide the server-side programmers who work on
the templates with interfaces to the client-side environment that are
simple enough for them to understand and use, while hiding the
implementation details from them. Their responsibility is then to
conceal those details (and much else) form the bulk of the individuals
programming the server-side code.

The intention is very deliberately to have a series of black boxes that
do no more than precisely what they are advertised as doing. The
back-end programmers don't care in the slightest how the front-end is
implemented. And those working on the intermediate layer between the
back-end and the front-end don't care that much either, so long as the
front-end can do what they need it to do.

The approach taken to having code executed onload listed above can be
contrasted with the way the rest of the application code achieves the
same. Every page loaded into the application includes a single JS file
that includes the following:-

/**
* A global function named - initializeMe - is created that can be used
* to arrange the execution of an arbitrary number (but probably
* implementation limited to the order of about 1500) of functions from
* the - onload - handler of a web page. The intention being to allow an
* indefinite number of other scripts to use a common interface for
* triggering their onload initialisation functions without having to
* worry about conflicts in the use of the onload handler.
*
* NOTE: This function must be included before any code that attempts
* to use it.
*
* The - initializeMe - function is called with a reference to a
* function object as its first argument, and up to 4 optional
* additional arguments:-
*
* initializeMe(functRef, "idOfElement", "nameOfForm");
*
* - The function reference and any additional arguments are stored in a
* function stack, the base of which is assigned as to window.onload
* handler (or using W3C DOM addEventListener or IE attachEven, if
* available) and when the onload event is triggered the execution of
* the base of the function stack results in the execution of the
* function passed as the first argument, followed by the next function
* in the stack (which executes its function argument, And so on until
* the stack is excused. The execution of functions passed to the -
* initializeMe - function is in the order in which they are passed to
* the - initializeMe - function (first in, first executed).
*
* The function object passed as - funcRef - is called with its first
* argument being the (onload) - event - object and the values
* originally passed to the call to - initializeMe - as the optional 2nd
* to 5th arguments as its 2nd to 5th arguments (in the same order). So,
* in the example call to - initializeMe - above, the function object
* passed by reference as the first argument would have the pattern:-
*
* function(event, idString, nameString){
* ...
* }
*
* - and the two string arguments passed to - initializeMe - would be
* passed on when it was called during the onload event.
*
* @param Function Reference <code>funcRef</code>
* @param Any (Reference or Value) <code>arg1</code> - Optional.
* @param Any (Reference or Value) <code>arg2</code> - Optional.
* @param Any (Reference or Value) <code>arg3</code> - Optional.
* @param Any (Reference or Value) <code>arg4</code> - Optional.
*/
var initializeMe = (function(){
var global = this, base = null, safe = false;
var listenerType = (global.addEventListener && 2)||
(global.attachEvent && 3)|| 0;
function getStackFunc(funcRef, arg1,arg2,arg3,arg4){
var next = null;
function l(ev){
funcRef((ev?ev:global.event), arg1,arg2,arg3,arg4);
if(next){next = next(ev);}
return (arg1 = arg2 = arg3 = arg4 = funcRef = null);
};
l.addItem = function(d){
if(next){
next.addItem(d);
}else{
next = d;
}
};
return l;
};
return (function(funcRef, arg1,arg2,arg3,arg4){
if(base){
base.addItem(getStackFunc(funcRef, arg1,arg2,arg3,arg4));
}else{
base = getStackFunc(funcRef, arg1,arg2,arg3,arg4);
}
if(!safe){
switch(listenerType){
case 2:
global.addEventListener("load", base, false);
safe = true;
break;
case 3:
global.attachEvent("onload", base);
safe = true;
break;
default:
if(global.onload != base){
if(global.onload){
base.addItem(getStackFunc(global.onload));
}
global.onload = base;
}
break;
}
}
});
})();

- except in a more concise form. The effect is to provide a single
interface to having code called onload. Internally it is apparently
complex, using closures and building private structures, but externally
it is simplicity itself. One function call is the entire public
interface. It doesn't care how many items of initialisation code employ
it or whether it is never used at all. It does its job reliably and
cleans up after itself; a perfect black box.

When I introduced that function to replace all of the ad-hock
initialisation code I was certainly the only individual who understood
how it worked. Even the javascript programmer who wrote the original
in-window pop-up code had never seen anything like it, but he did not
even consider rejecting its use as he recognised the value of a single
simple interface to the problem. And the template authors, who are not
even interested in how it works, instantly recognised it as ideal for
use in their code.

Generally, if the public interface is sufficiently simple and concise
and the internal details authored by someone who knows what they are
doing (and so are robust, reliable, complete and well tested) there
should be no problems with the result being used as a black box by the
most unskilled authors. Even when they have no hope of understanding the
internal details.

Indeed it might be that the internal details only gain an unjustified
significance in javascript because it is difficult to actually hide them
from others. In, for example, Java you don't concern yourself with
asking whether you understand the implementation of the HashMap class,
do you? You cannot easily see it, and so long as it works as advertised
you don't have to care. So why should being presented with a
closure-based javascript HashMap implementation become more alarming?
Just because you can see that you don't understand its source code?
I guess a fundamental question is: Given two sets of code
- one written in a manner that uses the language and its
features to its fullest and one which uses global functions
and procedural style - that perform the same task effectively,
is one necessarily better than the other? And is that a
subjective or objective decision? Based ono what?


Working at the end of 50-odd years of thought and research into software
design and development we are in a position to apply more criteria to
decision making than "perform the same task effectively". Why has
machine code authoring been replaced with higher level languages? Why
have complex systems moved towards OO? Why have a choice of languages at
all?

When, for example, under the heading "Measuring the Quality of an
Abstraction", Grady Booch discusses the concepts of: Coupling, Cohesion,
Sufficiency, Completeness and Primitiveness, isn't the implication that
there are many criteria for assessing all sorts of aspects of software
design?

The notion that experienced programmers use "advanced" techniques for no
other reason than just because they can is ridiculous. While it may be
true that novice programmers do not use "advanced" techniques just
because they cannot, the more experienced have good reasons for the
implementation decisions that they make. Reasons informed by experience,
and reasons informed by the study of the subject. And if the novice
cannot comprehend the results then that is a manifestation of being a
novice not a justification for adopting a lowest common denominator
approach to software authoring.

Richard.
Jul 23 '05 #32

P: n/a
Robert wrote:
<snip>
Anyway,
eval(name+"()")
is a better solution.


Disregarding the discussion of how working with function references
would be preferable to working with function names in the form of
strings, and that the eval use is not necessarily the best approach to
executing the functions named by those strings, this proposed use is
itself sub-optimal. The function name is concatenated with the string
representation of an empty arguments list and then executed as an
ECMAScript Program by the eval function. It must resolve the identifier
that (hopefully) is held in the string value of 'name' and then call
that function, returning the result of the function call.

The concatenation is not necessary as:-

eval(name)();

- would have the eval function resolve the identifier and return a
reference to the function object, which is then called outside of the
eval by following the CallExpression: eval(name) with an arguments list.
No string concatenation is necessary. This also allows a safer
implementation (though not nearly as safe as never using eval at all):-

var f;
if((f = eval(name)){
f();
}

- where failure to resolve the identifier does not result in an error.

Richard.
Jul 23 '05 #33

P: n/a
Richard Cornford wrote:
[over 2,000 words]
Richard, you are nothing if not verbose :)

I don't think we disagree. I just think we're used to working in different
environments. Therefore, I will just make some bullet points that kind of
sum up my obersvations:

* In a situation like yours, where you can deliver a "black box" solution,
and it is unlikely that it will be maintained by someone who doesn't
understand your use of the language, then I agree - use the full power of
every feature which makes the code most maintainable and future-proof.

* Very VERY few people working with javascript work in such an environment.
You're lucky.

* In an environment where javascript is written into "mockups" or sample
screens by person A, implemented into JSP code by person B, then tweaked and
maintained by person C, it's a whole different story. Not every development
environment is as structured as yours. I've _often_ seen inexperienced
javascript programmers take something that was written by a skilled person,
not understand how to adapt it to their needs, and rather than ask the
original author to add some capability, they re-write parts of it or throw
it out in favor of a solution that they think works better but in fact is of
lower quality.

* I've often promoted the idea of "libraries" or "black box scripts" which I
make available on my sites, and you've often criticized the idea as
fundamentally flawed. Yet here, you're arguing in favor of "expert-written"
code that is a black box with a published interface, and anyone wanting to
use the object to just use the interface. You compare it to a HashMap in
Java or other similar utils. The problem is, there isn't a collection of
reusable black-box javascript objects written by expert developers which
inexperienced programmers can reliably use in their work. In fact, expert
programmers such as yourself frown on the very IDEA of supplying such a
toolkit. I stand by my belief that these things provide huge value to junior
developers who don't know a lot about javascript, but have a requirement to
fill. And they _will_ find a solution. If not one published by an expert
javascript developer, then one published by someone using eval. And since so
many expert developers find little value in publishing reusable black-box
javascript solutions, you shouldn't complain when people find and continue
to use solutions that you think are inferior.

* When possible, I think everyone would prefer to hire a javascript expert
to write high-quality code in a black-box manner with a published interface
that other developers on the project could just hook into. In the real
world, that rarely happens. Code gets written as fast and cheaply as
possible, and if it works it's good enough. This is what most people are
used to, IMO. And in that environment, it's important to have code that can
be used, understood, and maintained by a wide range of people. Because if
it's not, it will often be bastardized or replaced and the end result is
even _worse_.
The notion that experienced programmers use "advanced" techniques for
no other reason than just because they can is ridiculous.


I don't think so. I've seen people try to "tighten" code that is very easy
to understand, only to have it execute .001% faster and contain fewer
characters. At the cost of readability. Face it, many programmers love
optimization and tweaking and writing dense code because it's a challenge
and because it shows off how much they know.

--
Matt Kruse
http://www.JavascriptToolbox.com
http://www.AjaxToolbox.com
Jul 23 '05 #34

P: n/a
Matt Kruse wrote:

Hi,

<snip>
I've _often_ seen inexperienced
javascript programmers take something that was written by a skilled person,
not understand how to adapt it to their needs, and rather than ask the
original author to add some capability, they re-write parts of it or throw
it out in favor of a solution that they think works better but in fact is of
lower quality.


I don't know the specifics of the business case, but there seem to be
lessons to be drawn from your description:
- the newbie had an assignment, and struggled to achieve it. That's
great, but he lacks common sense since he had the opportunity to ask the
author some advice and never considered it,
- that the management of the newbie permitted such actions, which
resulted in a loss of time, a low value solution, a not formed newbie,
clearly demonstrates the lack of ability of the management of the newbie.

I don't know how the projects you participate in are managed, but in the
projects I work for this would never be allowed - and we have tight
delays and high quality expectations. But as you told Richard, I may be
lucky as well.

<snip>
The notion that experienced programmers use "advanced" techniques for
no other reason than just because they can is ridiculous.

I don't think so. I've seen people try to "tighten" code that is very easy
to understand, only to have it execute .001% faster and contain fewer
characters. At the cost of readability. Face it, many programmers love
optimization and tweaking and writing dense code because it's a challenge
and because it shows off how much they know.


You certainly have seen some guys doing these things, but were these
guys truly experienced? A good programmer has in mind that quality is
determined by more factors than optimisation, and that unmaintenable
code is a waste.
Regards,
Yep.
Jul 23 '05 #35

P: n/a


Randell D. wrote:
Randy Webb wrote:
Robert wrote:
VK wrote:

> Are you saying it is not valid JavaScript?


*Roughly* that.

As such Function will be evaluated on each call, it's performance is
lower than with standard function(). So it's suggested to use it only
if you really need to create run-time functions from the scratch.

Yes, that is exactly what he asked for.
name -> function call
It could not have been done using a literal function to my knowledge.

Anyway,
eval(name+"()")
is a better solution.

NO.

window[name+'()']

is a better solution.


This use of the window object (method?) I like... I'm going to play
around with it...

And with regards to eval - My experience thus far has been to avoid
using eval where possible because of its overheads... but excusing the
performance weight, its simple, and functional...


Eval keeps it simple! (K.I.S.S.)

http://www.askblax.com
Thanks,
randelld


Jul 23 '05 #36

P: n/a


Yann-Erwan Perio wrote:
Matt Kruse wrote:

Hi,
- window[] implies that the host is a browser; using "this" would work
on all browsers, provided the function is called as a member of the
global object,
Using 'this' is highly sensitive to the calling environment also. For most
situations, referencing window[name]() will work while this[name]() might
not.


I agree. Starting with the window name gives more control over an
object because it forces the programmer to ensure that the 'this'
exists. Least that is what I have always thought.
As you say, the "this" value depends on the way the function is called:
if called as a method, then the "this" value will be the reference of
the object of which it is the method, if called as a function then the
"this" value will be a reference to the global object.

So if you want a function generic enough to be called as a member of
different objects (global object, custom object), and only operate with
the global object for the "this" value, then indeed referencing "window"
directly would be a good option (while I'd prefer, personally, use a
construct with an inner function returning the global object).

However I feel that, when calling a function, the "this" value inside
should be already known and should not depend on how the function is
called (an external parameter of the function, lack of encapsulation).


I agree. But, supposedly, not knowing how the function is called is
better in some situations...

http://www.askblax.com

Jul 23 '05 #37

P: n/a
askMe wrote:

Randell D. wrote:


<snip>
And with regards to eval - My experience thus far has been to avoid
using eval where possible because of its overheads... but excusing the
performance weight, its simple, and functional...

Eval keeps it simple! (K.I.S.S.)


That is, without a doubt, some of the dumbest advice that can be given
in a js newsgroup. But, who does it "keep it simple" for? The answer is:
No one.

To be able to *properly* use the eval, you *must* understand what it's
going to do, and how it's going to do it. That requires more knowledge
than learning how to do it otherwise.

--
Randy
comp.lang.javascript FAQ - http://jibbering.com/faq & newsgroup weekly
Jul 23 '05 #38

P: n/a
Matt Kruse wrote:
Richard Cornford wrote:
[over 2,000 words]
Richard, you are nothing if not verbose :)

I don't think we disagree. I just think we're used to working in
different environments. Therefore, I will just make some bullet
points that kind of sum up my obersvations:

* In a situation like yours, where you can deliver a "black box"
solution, and it is unlikely that it will be maintained by someone
who doesn't understand your use of the language, then I agree -
use the full power of every feature which makes the code most
maintainable and future-proof.

* Very VERY few people working with javascript work in such an
environment. You're lucky.

* In an environment where javascript is written into "mockups"
or sample screens by person A, implemented into JSP code by
person B, then tweaked and maintained by person C, it's a whole
different story. Not every development environment is as structured
as yours. I've _often_ seen inexperienced javascript programmers
take something that was written by a skilled person, not understand
how to adapt it to their needs, and rather than ask the original
author to add some capability, they re-write parts of it or throw
it out in favor of a solution that they think works better but in
fact is of lower quality.


In general, the abysmal standard of average web authoring is not a
justification for adopting low standards. Though it does seem to be a
common justification used by those that have low standards and are too
idle to attempt to do better.
* I've often promoted the idea of "libraries" or "black box
scripts" which I make available on my sites, and you've often
criticized the idea as fundamentally flawed.
The objection to libraries is very specific to the problem of browser
scripting. Because the browser is provided with the code that it
executes in the form of source code text all of the code that is
executed first needs to be download. In other contexts having a large
general library providing a wide range of facilities and having
application code cherry pick that library for the facilities it needs.
Attempting the same in a browser script mean downloading a huge bulk of
code most of which may never be executed.

Rather than having a browser import a large file of general facilities
and then execute only the ones that are needed it makes more sense to
only include the facilities that will actually be used.

Which is not to say that the author shooed not have a collection of
re-useable code that could be considered a library itself, or originated
into collections of related functionality that might be considered a
group of libraries. But those collections should not take the form of JS
files to be downloaded but instead a source of to be gathered together
into js files for use in a single specific context.
Yet here, you're arguing in favor of "expert-written"
code that is a black box with a published interface,
and anyone wanting to use the object to just use the interface.
And you will recall that I have often discussed the level at which to
target re-usable code. Obviously the lower the level of a component the
higher the chances that it will find applications in a wider range of
contexts. Once you are working in the context of a specific application
the higher level objects stand little chance of being of any use in
other contexts.

You want to write high level general objects, with a high level of
configurability for use in specific applications. Using such objects
necessitates including much code that is of no real use in any given
application. But given a sufficiently lager collection of re-usable low
level components it becomes easy to create application specific high
level objects without having to write the whole thing (or even much of
it) from scratch and without imposing the overheads of importing code
that will never be used.
You compare it to a HashMap in Java or other
similar utils.
And it is as good a specific example as any. For simple storage of
name/value pairs with names form a restricted and known set we don't
need any special object at all. For safe storage of name/value pairs
with truly arbitrary names we need something that may resemble the Java
HashMap class. Many implementations of such objects have been proposed
to address the naming issues, and they have varied in the facilities
they provide. From simple implementations that provide only get and put
methods to more elaborate versions that reproduce almost the entire
interface of the Java class. And all versions that may or may not
provide enumerators/iterators. In Java it makes no difference to be
using an object that has the full facilities of the HashMap class, in
javascript if you are not going to be using an enumerator there is
little point in downloading the code that facilitates them, and likewise
for the rest of the interface beyond put and get.
The problem is, there isn't a collection of reusable
black-box javascript objects written by expert developers
which inexperienced programmers can reliably use in their
work. In fact, expert programmers such as yourself frown
on the very IDEA of supplying such a toolkit.
Yet if you look into the archives of comp.lang.javascirpt you will find
thousands of examples, often created in response to a discussion of the
pertinent issues and the results subject to critical peer review. So all
you are saying is people who have done some work to acquire their
understanding don't feel much sympathy for individuals who cannot be
bothered to do something as simple as compose an effective google
search.
I stand by my belief that these things provide
huge value to junior developers who don't know a lot
about javascript,
And I stand by my belief that people who want to develop javascript will
provide most 'value' by learning the language they are attempting to
use.
but have a requirement to fill. And they _will_ find
a solution. If not one published by an expert javascript
developer, then one published by someone using eval.
What you find when you look for something is influenced in part by where
you look and how you look.
And since so many expert developers find little
value in publishing reusable black-box javascript
solutions, you shouldn't complain when people find and
continue to use solutions that you think are inferior.


Somehow I manage to live in a world where people who I have good reason
to accept as javascript experts publish a constant stream of code
examples, some of which are, or include, recognisable black boxes. You
have never really participated in the business of this newsgroup,
restricting yourself to a bit of shameless self-promotion and general
sniping from the sidelines. You have missed much in the process.

<snip>
The notion that experienced programmers use "advanced"
techniques for no other reason than just because they can
is ridiculous.


I don't think so. I've seen people try to "tighten" code that
is very easy to understand, only to have it execute .001%
faster and contain fewer characters. At the cost of readability.
Face it, many programmers love optimization and tweaking and
writing dense code because it's a challenge and because it shows
off how much they know.


It is as bad to be perceiving the discussion of "advanced" techniques as
directed towards reducing code by a few characters and running
fractionally faster as it is to attribute it to no more than the
demonstration of the ability to use those techniques. In reality the
application of the "advanced" techniques, and the related discussion of
the subject, is mostly concerned with software design issues.

As I have said, we have a wealth of research into software design to
draw upon. And many aspects of the design process have been identified
as significant in producing code that is (for various reasons) good. So,
for example, you might look at the importance of the distinction between
the internal details of an object and its external interface. You might
then wonder how that distinction could best be enforced/re-enforced in a
language that superficially appears to only have public object members.

Initial thoughts might be directed towards the use of naming conventions
to mark aspects of an object that are not intended for public use as
private. And along the way invite the derision of the authors of
'proper' OO languages for achieving the distinction (literally) in name
only.

Then you discover that closures can give you a truly private place to
put your internal details, and from which you can expose precisely the
aspects of an object that you want exposed. It seems perfectly
reasonable, as a result, to have an interest in the significance of
enforcing a distinction between the internal and the external in
particular application contexts, and an interest in which techniques
could best provide that distinction when it is seen as important.

That is but one aspect of software design that can be more effectively
addressed with a more complete understanding of the implementation
language. And much of research into software design is primarily geared
towards easing software maintenance, having identified that as a
significant expense in the process, but achieving that as much by
designing out the need for as much maintenance as making the work of
maintenance easier.

Richard.
Jul 23 '05 #39

P: n/a

Richard Cornford wrote:
In general, the abysmal standard of average web authoring is not a
justification for adopting low standards. Though it does seem to be a
common justification used by those that have low standards and are too
idle to attempt to do better.
I agree with you re adoption of standards. But practicality dictates
that the lowest level of standards begins at the environment in which
your application is to be run. Always takes me back to html and
javascript and the markup's and programming language's capabilities...
makes all else irrelevant, IMO.
Yet if you look into the archives of comp.lang.javascirpt you will find
thousands of examples, often created in response to a discussion of the
pertinent issues and the results subject to critical peer review. So all
you are saying is people who have done some work to acquire their
understanding don't feel much sympathy for individuals who cannot be
bothered to do something as simple as compose an effective google
search.
Google is predicated on the user's knowledge. I cannot enter search
words that I am ignorant of. Google's guesses at what I meant to
search for are predicated on how ignorant the last 8,000 or so people
were also ignorant of. That said, google is a good tool for
researching programming errors. Before one gets to that error, though,
what would one search for?
And I stand by my belief that people who want to develop javascript will
provide most 'value' by learning the language they are attempting to
use.
And this includes learning what is wasted energy vs what is time well
spent like learning how to use eval to achieve the desired results...
but have a requirement to fill. And they _will_ find
a solution. If not one published by an expert javascript
developer, then one published by someone using eval.


I use eval because I am working on fulfilling a functionality
requirement.
It is as bad to be perceiving the discussion of "advanced" techniques as
directed towards reducing code by a few characters and running
fractionally faster as it is to attribute it to no more than the
demonstration of the ability to use those techniques. In reality the
application of the "advanced" techniques, and the related discussion of
the subject, is mostly concerned with software design issues.
The thing that kills me in software design/development is that people
start trying to reuse code for the sake of saying that they have
resused code. If the code is bad, why bother building on it? I have
seen people become experts because they make some bad code work. If
they were truly experts, they would have scrapped the notion of
building on bad code because it wastes so much more time to train a
staff of developers to do something the wrong way.
That is but one aspect of software design that can be more effectively
addressed with a more complete understanding of the implementation
language. And much of research into software design is primarily geared
towards easing software maintenance, having identified that as a
significant expense in the process, but achieving that as much by
designing out the need for as much maintenance as making the work of
maintenance easier.

Richard.


Jul 23 '05 #40

This discussion thread is closed

Replies have been disabled for this discussion.