Multi-cast delegates the evil way

A lot of people have asked me over the years how various kinds of event binding work.  Basically, event binding works like this:

1)     Someone clicks on a button,
2)     then a miracle happens, and…
3)     the button’s event handlers execute.

It’s that second step that people struggle with.

First, some terminology.  I studied applied mathematics, and somethings we talked about quite a bit were sources and sinks. Sources produce something — a faucet produces water at a certain rate, for example.  A sink takes that water away.  We’ll borrow this terminology for our discussion of events.  An event source is something that produces events, like a button or a timer.  An event sink is something that consumes events, like an event handler function.  (Event sinks are also sometimes called “listeners”, which mixes metaphors somewhat, but that’s hardly unusual in this profession.)

This terminology leads to a rather unfortunate homonymy — when I first heard “this method sinks the click event”, I heard “this method syncs the click event”.  When we talk about event sinks, we’re talking about the consumer of something, not about synchronizing two things in time.  (Sinks, of course, can be asynchronous…)

The miracle actually isn’t that miraculous.  Implementing event sources and sinks requires two things: first, a way to wrap up a function as an object, such that when the source wants to “fire” the event, all it does is invokes the sink’s wrapper.  Second, a way for the thread to detect that the button, or whatever, has been pressed and thereby know to trigger the sink wrappers.

An explanation of the magic behind the latter would take us fairly far afield.  Suffice to say that in IE, the details of how that mouse press gets translated into windows messages and how those messages are dispatched by the COM message loops behind the scenes are miracles that I don’t want to talk about in this article.  I’m more interested in those wrappers.

In the .NET world, an object that can be invoked to call a function is called a delegate.  In JScript Classic, all functions are first-class objects, so in a sense, all functions are delegates.  How does the source know that the developer wishes a particular delegate (ie, event sink) to be invoked when the event is sourced?

Well, in IE, it’s quite straightforward:

function doSomething() {  }
button1.onclick = doSomething;  // passes the function object, does not call the function

But here’s an interesting question — what if you want TWO things to happen when an event fires?  You can’t say

function doSomething() {  }
function doOtherThing() {  }
button1.onclick = doSomething;
button1.onclick = doOtherThing;

because that will just replace the old sink with the new one.  The DOM only supports “single-cast” delegates, not “multi-cast” delegates.  A given event can have no more than one handler in this model.

What to do then?  The obvious solution is to simply combine the two.

function doSomething() {  }
function doOtherThing() {  }
function doEverything() { doSomething(); doOtherThing(); }
button1.onclick = doEverything;

But what if you want to dynamically add new handlers at runtime?  I recently saw an inventive, clever, and incredibly horribly awful solution to this problem.  Some code has been changed to protect the guilty.

function addDelegate( delegate, statement) {
var source = delegate.toString() ;
var body = source.substring(source.indexOf(‘{‘)+1, source.lastIndexOf(‘}’)) ;
return new Function(body + statement);

Now you can do something like this:

function dosomething() { /* whatever */ }
button1.onclick = dosomething;
// … later …
button1.onclick = addDelegate(button1.onclick, “doOtherThing();”) ;

That will then decompile the current delegate, extract the source code, append the new source code, recompile a new delegate using “eval”, and assign the new delegate back.

OK, people, pop quiz.  You’ve been reading this blog for a while.  What’s wrong with this picture?  Put your ideas in comments and I’ll discuss them in my next entry.

This is a gross abuse of the language, particularly considering that this is so easy to solve in a much more elegant way.  The way to build multi-cast delegates out of single-cast delegates is to — surprise — build multi-cast delegates out of single cast delegates.  Not decompile the single-cast delegate, modify the source code in memory, and then recompile it!  There are lots of ways to do this.  Here’s one:

function blur1(){whatever}
function blur2(){whatever}

var onBlurMethods = new Array();

function onBlurMultiCast() {
for(var i in onBlurMethods)
blah.onBlur = onBlurMultiCast;

I’ll talk about VBScript and JScript .NET issues with event binding another time.

I’m on vacation for the next three weeks, so I might have lots of time for blogging, or lots of other things to do.  So if you don’t hear from me, I’ll be back in the new year.  Have a festive holiday season!

Tags JScript Scripting

Comments (11)

You must be logged in to post a comment.

  1. theCoachThere is a great comic illustrating your intro in Daniel Dennett’s book “Consciousness Explained” [or possibly “Darwin’s Dangerous Idea”. FYI.
  2. Log in to Reply
  3. December 12, 2003 at 2:29 pm
  4. Eric LippertI was making a deliberate reference to this famous cartoon:Is that the one you’re thinking of?
  5. Log in to Reply
  7. December 12, 2003 at 2:38 pm
  8. Andy Smithjust thought I’d blog my take instead of leaving comments:
  9. Log in to Reply
  10. December 12, 2003 at 3:37 pm
  11. Tom TrenkaFunny you should mention this topic…I’ve just released the beginnings of an ECMAScript BCL called f(m)…and the centerpiece of this kit is….drumroll…a common Event system that handles this exact problem. Except I basically copied the .NET guys 🙂Log in to Reply
  12. You can find it at, and to be honest, I’d love some feedback. Why did I do it that way? Because I’ve seen a number of examples like the ones you showed above, and it looks SO ugly…
  13. December 12, 2003 at 4:20 pm
  14. JayHere’s my solution. It allows the delegating object to behave just like both a method AND an array of delegate methods. I used the “” syntax to allow contained methods of MulticastDelegate to access its “this” property (i.e., they become methods of the parent object as well).function MulticastDelegate()
    var $d = function()
    for( var ix in arguments.callee.delegates )
    arguments.callee.delegates[ix].call(this, arguments )
    $d.delegates = new Array();
    $d.push = function(f) { this.delegates.push(f) }
    // add other Array methods to taste
    return $d;
    }Or, if talking about a web page:Log in to Reply
  15. button1.onclick = new MulticastDelegate();
    button1.onclick.push( function() {whatever} );
    button1.onclick.push( function()
    a more complex whatever
    } );
  16. example = new MulticastDelegate();
    example.push( function() { println( “One” ) } )
    example.push( function() { println( “Two” ) } )
  17. function println(v) { WScript.StdOut.WriteLine(v) }
  18. December 12, 2003 at 6:47 pm
  19. JayIf I were really putting this into production, I would also have MulticastDelegate examine it’s “arguments” and push all such elements onto the constructed array. This would allow multiple delegate functions to be added at construction time. Jay.
  20. Log in to Reply
  21. December 12, 2003 at 6:50 pm
  22. Andy SmithAssuming a script running in a browser, there is a MUCH easier way to do all of this. But first i’ll highlight why these kinds of ideas are not always useful. Not everybody writing script that attaches to events, controls all the code on the page. assigning a custom multicast delegate doodad to SomeElement.onclick will be destroyed if some other chunk of code that doesn’t have any clue about your code just comes along and assigns it’s own function to SomeElement.onclick. Note that the code examples here do exactly that. You may be interfering with somebody else’s event handling system.This is why I think it’s better to leverage the browser here, and use addEventListener (for W3C DOM compliant browsers) and/or attachEvent ( for IE). I’ve blogged about this, with my current methodology, here:
  23. Log in to Reply
  24. If you are wondering about a real-world scenario… think about server controls development. If I package some behavior in a control with script, I want to make sure that my event handling system will not be affected by the page developer or some 3rd party.
  25. December 12, 2003 at 7:33 pm
  26. Dan ShappirFirst a nitpick, the code should be:andAnd not as written.blah.onBlur = blur1.andThen(blur2);Another way to approach this problem using BeyondJS is event streams. Streams are objects that behave like containers, only in “time” instead of in “space”. This allows you to use list comprehensions on events:Unsurprisingly this looks a lot like your onBlurMultiCast example, only streams support lots of other list comprehensions such as filer.buttons1.onclick = alert;
    button1.onclick = addDelegate(button1.onclick, “doOtherThing();”);A third problem is that the original delegate function looses its scope (closure).Log in to Reply
  27. And yes, for the browser you should simply use addEventListener or attachEvent.
  28. would break because window.alert.toString() just won’t work. You could try “” + window.alert which would run, but the result still won’t work.
  29. I can think of various reasons why you would dislike the addDelegate code, primarily the fact that it’s eval. Another problem is that it won’t always work. For example:
  30. var st = eventStream(blah, “onBlur”);
  31. andThen is implemented in such a way that you can modify the function chain dynamically. An added advantage, though not in this case, is that the value returned by blur1 is passed as an input arg to blur2.
  32. Of course, had you been using the BeyondJS library you would have functional composition available, in which case you could simply write:
  33. > blah.onBlur = onBlurMultiCast;
  34. > button1.onclick = addDelegate(button1.onclick, “doOtherThing();” );
  35. December 13, 2003 at 5:52 pm
  36. David SchontzlerattachEvent has always left something to be desired, but I stopped using it awhile ago so I don’t recall what bugged me about it.
  37. Log in to Reply
  38. December 17, 2003 at 4:49 am
  39. David SchontzlerAndy-Log in to Reply
  40. Your method still requires people to conform to your function call, which is no different than the other methods. This doesn’t really fix the problem of 3rd party integration you speak of.
  41. December 17, 2003 at 4:52 am
  42. Brian R. JamesDo people still attach events that way? attachEvent has been around for years. Why reinvent the wheel?
  43. Log in to Reply
  44. December 17, 2003 at 5:10 pm

Skip to main content

Follow Us

Popular Tags

C# Scripting JScript VBScript Language Design COM Programming Rarefied Heights Puzzles Rants Performance Security C# 4.0 Non-computer SimpleScript JScript .NET Immutability Code Quality Pages Recursion Books


The JScript Type System Part Eight: The Last Blog Entry About Arrays, I Promise

that I defined a type as consisting of two things: a set of
values, and a rule for associating values outside of that set with
values inside the set.  In JScript .NET,
assigning a value outside of a type to a variable annotated with that type restriction
does that coercion if possible


var s
: String = 123; // Converts 123 to a String


I already discussed what happens when you assign a JScript array to a hard-typed CLR
array variable


var sysarr
: int[] = [10, 20, 30]; // Create new int[3] and copy


what happens when you assign a one-dimensional CLR array to a JScript array variable:


var jsarr
: Array = sysarr; // Wrap sysarr


what happens when you assign a hard-typed
CLR array
 to a variable annotated with a different CLR
array type?


var intarr
: int[] = [10, 20, 30];

var strarr
: String[] = intarr;


might think that this does the string coercion on every element, but in fact this
is simply not legal. Rather than creating a copy with every element coerced to the
proper type, the compiler simply gives up and says that these are not type compatible.
If you find yourself in this situation then you will simply have to write the code
to do the copy for you.  Something like
this would work:


copyarr(source : System.Array) : String[]


dest : String[] = new String[source.Length];

index : int in source)

= source.GetValue(index);




are a few notable things about this example. First, notice that this copies a rank-one
array of any element type to an array of strings. This is one of the times when it
comes in handy to have the System.Array “any
hard-typed array” type!


notice that you can use the for-in loop
with hard-typed CLR arrays. The for-in loop enumerates
all the indices of an array rather than the contents of the array.
 Since CLR arrays
are always indexed by integers the index can be annotated as an int. The loop above
is effectively the same as


for (var
index : int = 0 ; index < source.Length ; ++index)


the for-in syntax
is less verbose and possibly more clear.


you might recall that GetValue (and SetValue)
take an array of indices because the array
might be multidimensional. But we’re not passing in an array here.  Fortunately,
you can also pass only the index if it is a single-dimensional array.


speaking, hard-typed array types are incompatible with each other. There
is an exception to this rule, which I’ll discuss later when I talk about what exactly
“subclassing” means in JScript .NET.

Tags JScript .NET Scripting

Comments (0)

You must be logged in to post a comment.

Skip to main content

Follow Us

Popular Tags

C# Scripting JScript VBScript Language Design COM Programming Rarefied Heights Puzzles Rants Performance Security C# 4.0 Non-computer SimpleScript JScript .NET Immutability Code Quality Pages Recursion Books


A grammatical aside


just wrote in a comment to my previous entry, “The ability to rate one’s knowledge
of a subject accurately is strongly correlated with one’s knowledge.”


a minute.  “One’s”???  Word’s
grammar checker didn’t blink at that.  But
nor does it blink at “ones”.  Well, according
to the OED, “one’s” is the genitive declension
of “one”.  Let’s sum up:


Pronoun   Genitive


Me        My

You       Your

Us        Our

Him       His

Her       Hers

Them      Their

Thou      Thine

It        Its

One       One’s


always thought that the reason that “its” doesn’t take an apostrophe-s was because
the rule “add an apostrophe-s to form a possessive” applied
only to noun phrases
, not to pronouns (And of course, we all know that apostrophe-s
does not itself form a genitive noun —
otherwise, in the sentence “The First Lady is the President of America’s wife,” Laura
Bush would be associated with America, not President Bush.)


the heck is going on here?  Surely there
is some grammar pedant out there who can justify this.  My
faith in English grammar has been sorely tried.

Tags English Usage Non-computer Rants

Comments (28)

You must be logged in to post a comment.

  1. mikeWell, let’s work backward. In the phrase “The First Lady is the President of America’s wife”, the possessive is applied to the entire phrase: “(the President of America)’s wife.” This is common; here’s a nice example: “The woman I went to school with’s daughter”. ( FWIW, the ability to add a possessive to a noun phrase and not just to a noun is a comparatively recent development in English: “Until well into Middle English times what Jespersen calls the ‘group genitive’, i.e. ‘[the king of England]’s’ nose did not exist, but the usual type was ‘[the king]’s nose of England’. In Old English the usual structure, before the use of the of-possessive would have been ‘the king’s nose England’s’ (’s actually interesting to contemplate is why the hell we have an apostrophe for the possessive at all. Possessive is just the genitive case; as such, it’s a normal noun declension, and has no more need for an apostrophe than the plural does. Nothing is elided with the possessive/genitive. And as noted, pronouns manage without it. German likewise has an -s for the genitive and manages without a possessive marvelously well. So whither the flingin-flangin possessive apostrophe, which does little more these days than confuse and annoy people?
  2. Log in to Reply
  3. I have no explanation for the anomaly of “one’s” except to note that “one” is a “special” kind of pronoun since it has no direct antecedent. Unfortunately, my two most reliable sources for sussing out this kind of things are unavailable for the nonce.
  4. December 2, 2003 at 8:54 pm
  5. MattWell, according to Strunk & White, “The prenominal possessives hers, its, theirs, yours, and ours have no apostrophe. Indefinite pronouns, however, use the apostrophe to show possession.” The example they use is “one’s rights”. Shertzer (Elements of Grammar) notes that “there is no apostrophe before the s in the possessive of personal pronouns”, which suggests that maybe you mis-remembered the rule.
  6. Log in to Reply
  7. December 3, 2003 at 1:36 am
  8. MattGah – that should be misremembered, not mis-remembered. So much for pedantry.
  9. Log in to Reply
  10. December 3, 2003 at 1:37 am
  11. MikeUm, that would be “*whence* the flingin-flangin possessive apostrophe.” Sheesh. This comment feature needs an edit feature. 🙂
  12. Log in to Reply
  13. December 3, 2003 at 2:29 am
  14. Eric LippertRe: whence the apostrophe?Log in to Reply
  15. I was under the impression that in archaic Germanic languages like Old English, the genitive case was indicated by adding “es”, and that we elide the “e” with an apostrophe. But what I know about Old English grammar you could fit into a matchbox without removing the matches first, so I wouldn’t be at all surprised if I were completely misinformed…
  16. December 3, 2003 at 2:54 am
  17. Anonymousits doesn’t have an apostrophe because you wouldn’t be able to tell whether it was the possessive or a contraction (of ‘it is’). At least that’s what I was taught in school 🙂
  18. Log in to Reply
  19. December 3, 2003 at 3:21 am
  20. Ian GriffithsYou’re on the right track with the “e” being elided with an apostrophe – that is indeed the origin of the use of an apostrophe as the indication of the genitive.What seems to have happened is that “ites” got ellided, as frequently-used words tend to, but this happened much earlier in the history of English than the elision that happened to all other genitive forms. (Presumably because it was a widely-used word – the workhorses of a language are the ones that tend to get streamlined first, which is why the verb ‘to be’ is highly irregular in most languages.)So the progression looks like this: originally the word was “ites”, then it became “its” at a time when apostrophes were apparently not required on such elisions, and then quite a lot later, we started to elide *all* the genetive forms, but by then it was considered correct to indicate such elisions with an apostrophe.Log in to Reply
  21. So “its” is an anomaly because we started eliding that long before we elided all of the other genitive forms.
  22. At the time “ites” got elided to “its”, apostrophes were apparently not used to indicate elision. (As far as I can tell… I’ve not done extensive research on this by the way. But what seems clear is that apostrophes weren’t used for this particular elision.)
  23. But this still doesn’t explain “its”. But that just turns out to be historical accident. The genitive form used to be “ites” – you can find a few examples of this in Old English documents of a certain age around on the web. (I forget which, but I did a search about 2 years ago the last time I had this discussion. I’m sure Google can still find them if you want to see them.)
  24. December 3, 2003 at 4:22 am
  25. Dan ShappirSo “its” is a case of maintaining backward compatibility 🙂
  26. Log in to Reply
  27. December 3, 2003 at 5:35 am
  28. MikeThe issue of ellision of the vowel in genitive -es only partly explains the possessive apostrophe; the -as ending was also used for plural of masculine strong nouns in OE (nice declension and conjugation chart here:, which suggests that many noun plurals once had, as they did genitive singular, an unstressed vowel to go with their -s. Granted, it has less to do with how things really were than how they were perceived to be when our not-quite-rational system of orthography was being codified. As I sort of opined earlier, IMO the apostrophe is more trouble than it’s worth for possessives; even educated people are confused about its use, if my email Inbox is any evidence. In historical linguistics, mass confusion about forms is often a prelude to an evolutionary change. 🙂
  29. Log in to Reply
  30. December 3, 2003 at 8:50 pm
  31. MikeIncidentally and on a slightly different note, you say “My faith in English grammar has been sorely tried.” I do hope that you’re careful to make a distinction between the real grammar of English, which is splendid and about which one never need feel sorely tried, and the highly artificial rules of English orthography, which are in fact so arbitrary that you and I don’t even spell common words (e.g. “color”) the same way.
  32. Log in to Reply
  33. December 3, 2003 at 10:54 pm
  34. Eric LippertI was being sarcastic.My bad; it is often difficult to deduce sarcasm from mere text and I was insufficiently clear. English has so many bizarre rules and bizarre exceptions to those rules that a quibble over an apostrophe in a seldom-used pronoun is hardly shocking.Log in to Reply
  35. I mean, good heavens, any language in which “I would have had to have driven if I had wished to have arrived on time” — five haves! — is a perfectly sensible sentence is clearly not a sensible language! 🙂
  36. December 4, 2003 at 1:04 pm
  37. DanaI don’t see the need for delving into the history of elision (or “ellision,” as somebody spelled it, probably for some very good reason). It is intuitively obvious why we need an apostrophe in “one’s.” The apostrophe, for better or for worse, does indicate possession–at least, we’re accustomed to associating the two. And, oddly, we do need a non-possessive form of “one.” For example, “I want a dozen doughnuts. Give me two of those chocolate-frosted ones, and….” The apostrophe helps us distinguish between a plural and a possessive.As for grammar and/or orthography being a general pain in the neck, I have always considered that the very existence of heteronyms proves that English spelling, at least, is cruel.
  38. Log in to Reply
  39. As for “its” versus “it’s,” this ultimately makes sense, too. The source of the confusion is that the apostrophe in English isn’t just used to show possession, but also gets used when words are shortened (e.g., in “that’s the spirit!” the apostrophe stands in for the “i” in “is”). Since you can form a possessive of “it” and we can also contract “it is,” we need to differentiate between the possessive and the contraction by using or eschewing the apostrophe. It’s perfectly arbitrary which form gets the apostrophe–there’s a case for either–so who knows, somebody had to flip a coin at some point. Since it IS arbitrary, we just have to memorize the rule without relying on any logical reasoning to help us remember. So the more pedantic among us suck it up and remember the rule.
  40. December 4, 2003 at 1:50 pm
  41. Peter TorrSince the language geeks are out in force 🙂 and using lots of big words, here’s a question for you. I know that “onomatopoeia” means essentially a word that sounds like the thing it is describing, but I seem to remember there being another word that meant “words that describe themselves.” For example, “short” describes itself, but “big” does not.Log in to Reply
  42. What is that word?!?
  43. December 4, 2003 at 7:22 pm
  44. Eric LippertThe words you’re looking for are “heterological” and “homological”, and you’ve heard of them because at some point in your philosophy minor, someone mentioned Grelling’s Paradox to you. Grelling’s paradox is a version of Russell’s Paradox. “Heterological” means “not describing itself”, ie, “long” is heterological, “polysyllabic” is homological. Is “heterological” heterological or homological?
  45. Log in to Reply
  46. December 4, 2003 at 7:58 pm
  47. Eric Lippert> its doesn’t have an apostrophe because you wouldn’t be able to tell whether it was the possessive or a contraction (of ‘it is’). At least that’s what I was taught in school 🙂That’s not how languages evolve! There are lots of hard-to-parse constructions in English — while we’re on the subject of possessives, how about “Mitzi is the owner of Fido’s sister”? Is Mitzi the sister of the guy who owns Fido, or does Mitzi own a dog, and the dog’s brother is Fido? Why hasn’t English evolved to eliminate this ambiguity?Log in to Reply
  48. Rationality is occasionally a force that drives linguistic change, but the fact that we do not all speak Esperanto is a testament to the fact that it is a pretty weak force!
  49. In other words, you’re asserting that the language is the way it is because otherwise it would be hard to parse?
  50. December 4, 2003 at 8:56 pm
  51. MikeDon’t confuse language (and language evolution) with mere reading. When you say “parse,” do you mean “read off the page” or do you mean “parse, er, tokens out of an oral stream”? Apostrophes have nothing to do with the latter, since you can’t hear ’em. cant hear em. Whatever.
  52. Log in to Reply
  53. December 5, 2003 at 12:31 am
  54. Ian GriffithsI just want to reply to Dana’s point – I almost agree but not quite.But I don’t see how you can claim that “its” also makes sense without delving into the history of elision. It clearly flies in the face of the first rule – it’s a genitive form that sounds like it was formed in the normal way, but for which we are required by convention to omit the apostrophe. (And worse, when you look into it a bit, you discover that it also flies in the face of the second rule!)Log in to Reply
  55. How can you describe “its” as intuitively obvious? Without the historical background, it’s arbitrarily and non-intuitively different from everything else.
  56. Yes, “one’s” makes sense, and “it’s” also makes sense, albeit for different reasons. The former because we almost always use apostrophes to indicate the genitive, and we also use apostrophes to indicate contractions.
  57. December 5, 2003 at 10:21 am
  58. Peter TorrActually, according to The New Shorter Oxford English Dictionary, the opposite of “Heterological” is “Autological,” a word for which they do not have an entry (although it is listed under “auto” as a “combining entry”)Log in to Reply
  59. One day I’m going to buy the full Oxford English Dictionary in print( There’s just something inexplicable cool about the idea of having all those words at your disposal.
  60. December 8, 2003 at 9:39 pm
  61. Eric LippertYou know that Microsoft has a subscription to the online OED, right? All those words ARE at your disposal.
  62. Log in to Reply
  63. December 10, 2003 at 12:54 am
  64. Peter TorrInteresting; I did not know that. I just like thumbing through the pages though… there’s something about it that seems special. On-line dictionaries don’t have the same allure.Log in to Reply
  65. Yeah, I’m a crackpot.
  66. December 10, 2003 at 4:29 am
  67. MarcusConfusing “its” with “it’s” is a very common mistake, but it shouldn’t be so, since once the difference is understood it’s easy to ensure that you use each once correctly.In contrast, “it’s” is always a contraction of “it is” just as “won’t” = “will not” and “can’t” = “cannot”.Just to further confuse the issue, when using names like my own (Marcus), the genitive is formed by adding an apostrophe at the end, but NOT adding the expected “s”! Thus, if you were to refer to my post, you should say “Marcus’ post” rather than “Marcus’s post”.
  68. Log in to Reply
  69. I suspect that the source of the confusion for most people is probably that (AFAIK) no other two words in English share exactly the same letters and are pronounced the same, and yet differ in punctuation and meaning.
  70. Just in case it’s not already abundantly clear, the examples stated in the original blog post without an apostrophe are in the genitive case, i.e. “its” = “of it” in the same way that “his” = “of him” and “hers” = “of her”. Naturally, English being English, these are the exceptions to the norm, since other articles (such as “one” as given earlier) DO use an apostrophe… “one’s”, “dog’s”, etc.
  71. December 10, 2003 at 10:40 am
  72. MarcusI posted that before I meant to…. oops!Log in to Reply
  73. I failed to make clear that the rule mentioned in the last paragraph only applies to names already ending in an “s” (my own name being merely one example close to home, another being the name of my old school – Skinners’ School)… and of course the “once” in the first sentence should have read “one” instead. :p
  74. December 10, 2003 at 11:05 am
  75. Norman DiamondIt seems to be rather random whether English will disambiguate any particular homonyms or not.The comparison of “theirs” with “its” was incorrect. The plural of “its” is “their” with no “s”. You can say “Don’t judge English by its speakers” or “Don’t judge languages by their speakers”.Last and least, though not speaking for my employer, I will speak about my employer 🙂 🙂 :
    its’s its’s trademark.
  76. Log in to Reply
  77. Or am I wrong. The singular of “This book is theirs” might be “This book is hers” or “This book is his”, but suppose the book is owned by a company? “This book is its’s” or what?
  78. “One’s” is possessive. “Ones” is plural.
    “Whose” is possessive. “Who’s” is a contraction of “who is”.
  79. December 16, 2003 at 9:55 pm
  80. Eric LippertMy cat has a bowl; its bowl is empty; the empty bowl is its. My company has a building; its building is tall; the tall building is its. No problems there.
  81. Log in to Reply
  82. December 19, 2003 at 3:52 am
  83. ElbieFar be it from this one to be an expert on grammer, but this one’s opinion is that everything is as it should be.
  84. Log in to Reply
  85. March 19, 2004 at 7:52 am
  86. Mrs. NicklebeeAnd my grammar teacher dared to wonder why I struggled in her class!I’ve never heard of presidents being referred to as the President of America, fwiw.  The Canadians and Mexicans might object as they are North Americans.  We are just plain Americans but he is called the President of the United States.Log in to Reply
  87. The newest comment is only more than three years old but what the hay!
  88. I am no grammar queen, but  I would like to suggest that the Laura Bush sentence, “The First Lady is the President of America’s wife,” would be better stated another way:  The wife of the President of the United States is called the First Lady.  The First Lady is the wife of the President of the United States would also work.  When there is that much of an issue involving what is modifying which, isn’t it better to simply rewrite the sentence and try to eliminate the ambiguity?
  89. July 12, 2007 at 11:44 am
  90. Johannes LeushuisOne does not belong in the list of I, you , he etc. because one is an indefinite pronoun like somebody, anybody, everybody, nobody, while I, you , he are personal pronouns. Possessives of indefinite pronouns get “’s”: somebody’s, anybody’s, everybody’s, nobody’s, one’s, while possessives of personal pronouns do not: my, your, his, her, its, etc. Perhaps this is because the “’s” is an abbreviation of “his”: the man’s book, the man his book. Then you use that for indefinite pronouns: somebody his book becomes somebody’s book, while you do not use that for personal pronouns: my book, his book, her book etc. Perhaps the same is valid for “The book is somebody’s”, “The book is ours”?
  91. Log in to Reply
  92. October 6, 2007 at 6:35 pm
  93. Eric LippertSee for a discussion of the “his genitive”.
  94. Log in to Reply
  95. October 7, 2007 at 10:55 am

Six out of ten ain’t bad

Occasionally I interview C++ developers. I’m always interested in how people rate themselves, so I’ll occasionally ask a candidate, “On a scale from one to ten, how do you rate your C++ skills?”

The point of the question is actually not so much to see how good a programmer the candidate is — I’m going to ask a bunch of coding questions to determine that. Rather, it’s sort of a trick question. What I’m actually looking for — what I’m looking for in almost every question I ask — is “how does the candidate handle a situation where there is insufficient information available to successfully solve a problem?” Because lemme tell ya, that’s what every single day is like here on the Visual Studio team: hard technical problems, insufficient data, deal with it!

The question has insufficient data to answer it because we have not established what “ten” is and what “one” is, or for that matter, whether the scale is linear or logarithmic. Does “ten” mean “in the 90th percentile” or “five standard deviations from the mean” or what? Is a “one” someone who knows NOTHING about C++? Who’s a ten?

Good candidates will clarify the question before they attempt to answer it. Bad candidates will say “oh, I’m a nine, for sure!” without saying whether they are comparing themselves against their “CS360: Algorithmic Design” classmates or Stanley Lippman.

I mention this for two reasons — first of all, my favourite question to ask the “I’m a nine out of ten” people actually came up in a real-life conversation today: OK, smartypants: what happens when a virtual base class destructor calls a virtual method overridden in the derived class? And how would you implement those semantics if you were designing the compiler? (Funny how that almost never comes up in conversation, and yet, as today proved, it actually is useful knowledge in real-world situations.)

The second reason is that ten-out-of-ten C++ guru Stanley Lippmann has started blogging. Getting C++ to work in the CLR environment was a major piece of design work, of a difficulty that makes porting JScript to JScript.NET look like a walk in the park on a summer day.

Compared to Stanley Lippmann, I give myself a six.

Comments (16)

  1. After the “I’m a nine”, I always ask them “what question would you ask someone who was an 8.9 that they would have difficulty answering – just general subject is fine, but a specific question is great”. The real nines have a question like (I normally tech .net) “what should you look out for when casting a structure to an interface and calling methods that modify the data”. The non-nines say “Something about how inheritance works”. If nothing else, it really gives you an idea of what they find hard about what you’re teching them in.

    The great part about this is, I can then use the good questions on people later! And, if they have good questions I can learn something, too (after watching PDC speakers and going to ask the experts, I had to re-rate myself. I used to say I liked feeling stupid, but ouch — ego blow. And if you’re a six, I’m not saying what I am) .

  2. Dan Shappir

    With regard the 1-to-10 scale and insufficient data: I think that in this case cultural norms fill in most of the blanks. For example, it’s quit clear the scale isn’t linear, most human scales aren’t. The differences between 2 to 3 to 4 are generally insignificant while the differences between 8 to 9 to 10 are huge.

    I think the answer to the question provides more information with regards to that person’s ability to accurately judge his or her own capabilities, the personal honesty to accept this judgment, and the guts to give you the correct answer. Without additional questions, it’s you who doesn’t have sufficient data to evaluate the answer.

    I personally have never used this question, but I’ll certainly consider it. A good question I’ve recently learned about is: “which good CS book have you recently read?” Obviously this question is better suited for someone who is not straight out of the University.

    A question I might ask somebody answering 9 is: “why is it a bad idea to overload the && operator?”

  3. Indeed, ability to rate one’s knowledge of a subject accurately is strongly correlated with one’s knowledge! Dilletants tend to compare themselves against their peers, and hence produce inaccurate ratings; experts tend to compare themselves against gurus.

    As for the && operator — I don’t think I’ve ever actually overloaded an operator other than “new”. It’s not very often that one needs to add two parsers together. I’ve always disliked the entire idea of operator overloading — making << mean “stream to a file” struck me as incredibly disgusting when I first heard of it, and my opinion hasn’t improved since then.

    I can think of lots of reasons to avoid overloading in general. Something that strikes me about the && operator is that it is a short-circuiting operator — one might imagine that this would lead to bizareness when overloaded.

  4. Dan Shappir

    > Something that strikes me about the && operator is that it is a short-circuiting operator

    Exactly. Say a and b are expressions of type bool. If you write:

    c = a && b;

    if a is false b isn’t evaluated at all – short circuit.

    If a and b are expressions of UDT X with an overloaded && operator then the previous expression translates to a function call:

    c = X::operator&&(a, b)

    In this case both expressions are evaluated regardless of their values. This discrepancy in behavior is why overloading binary logical operators is a bad idea.

    I agree that in most cases operator overloading can detract rather than enhance readability (BTW you can pass this sentiment on to whomever elected to use += with delegates). OTOH where would a string class be without an overloaded + operator?

    And on a related issue, another 9 question: what is Koenig lookup?

  5. Dan Shappir

    For more discussions of “weird” C++ stuff check out the thread:$6697

  6. That question is a little too jargony. Case in point: I once wrote an internal spec describing the insanely complex rules that JScript .NET uses to resolve overloads at compile time and run time. I could certainly describe algorithms for argument-dependent name resolution, why you’d want to use them, and what the practical pitfalls are when using the Reflection layer to do so, but until two minutes ago I didn’t know that this was called “Koenig lookup”! (I’m sure that Herman, who actually implemented that algorithm in JScript .NET, knows that it’s called Koenig lookup, but he’s got a PhD in language design…)

  7. I actually kind of like += for delegates, though it struck me as odd at first. It gets across the idea that you are adding something and at the same time modifying the LHS. However, when designing a new language, one can add new keywords and operators pretty easily. I personally would have created a new operator or syntax rather than overloading += in this weird way.

    Next time I see Anders I’ll ask him what motivated that decision. Don’t hold your breath waiting — I haven’t had a meeting with Anders in over six months.

  8. I know Herman was against += as well. JScript’s method of directly calling add_EventName() and remove_EventName() seems kind of klunky, but at least you know exactly what is going on.

  9. Or hey, AddHandler from VB.NET. 🙂

  10. Centaur

    [quote]what happens when a virtual base class destructor calls a virtual method overridden in the derived class?[/quote]

    Is a 9-out-of-10 supposed to say, without looking up, something along the lines, “Chapter 12.7 ‘Special member functions – Construction and destruction’, verse 3 of The Holy Standard says, ‘When a virtual function is called directly or indirectly from a constructor or a destructor, and the object to which the call applies is the object under construction or destruction, the function called is the one defined in the constructor or destructor’s own class or in one of its bases, but not a function overriding it in a class derived from the constructor or destructor’s class, or overriding it in one of the other base classes of the most derived object (1.8)’. Thus, the virtual base class V destructor V::~V shall invoke the virtual method V::f, not the overridden D::f”?

  11. Dan Shappir

    I personally would not expect the 9-out-of-10 to quote chapter and verse out of the C++ standard (I would probably be somewhat scared if he did). I would expect him to understand the implications. For example, the “indirectly” bit is very important. Misunderstood it can result in application misbehavior that this person would simply not understand, and thus be unable to correct.

  12. Centaur

    By the way, my first reaction was, “Is it even legal, to call a virtual method from a base destructor, when the derived object has already been partially destroyed?” Then, after digging into the standard, it turned out it is. Oops. Anyway, this is a questionable practice.

  13. It’s a terrible practice. But to answer the question, no, I don’t expect 9/10’s to have memorized the specification. I do expect that 9/10’s should be able to say something like:

    “I don’t know offhand,but let me see if I can reason it out. The base class destructor runs after the derived class destructor. That means that when the virtual function is called, all the state that makes the derived class different from the base class has been destroyed. In a sense, after the destructor runs, the “this” pointer really isn’t pointing to a valid instance of the derived class anymore! Therefore, I’d expect that a virtual function call would call the base class version, because the derived class version might depend upon now-destructed state. This would be pretty easy to implement — the derived class destructor could, as its final act, change the virtual function pointer to point to the base class vtable instead of the derived class vtable.”

    That’s a 9/10 answer. It demonstrates that the candidate understands destructors, virtual functions, how virtual functions are implemented, and most important, that the candidate can think like a language designer. Deciding what the “for” loop syntax looks like is easy. The hard part of language design is figuring out the right thing to do in these weird corner cases.

    Sometime I’ll tell you guys about the new data type that I tried to get them to add to VB.NET — a variation of the Variant that I called the “Deviant”. Now _that_ was a host of corner case bugs waiting to happen.

  14. Couple interesting links on related topics (Disclaimer: Not Necessarily Directly Applicable to Your Situation!):

Speeding can slow you down

I hope all you readers living in the United States had a restful and enjoyable Thanksgiving holiday. I sure did.

I’ve been meaning to talk a bit about some of the performance issues you run into when tuning massively multi-threaded applications, like the ASP engine.  I’d like to start off by saying that I am by no means an expert in this field, but I have picked up a thing or two from the real experts on the ASP perf team over the years.

One of the most intriguing things about tuning multi-threaded applications is that making the code faster can slow it down. How is that possible? It certainly seems counter-intuitive, doesn’t it?

Let me give you an analogy.

Suppose you have an unusual road system in your town.  You have a square grid of roads with stoplights at the intersections. But unlike the real world, these are perfect traffic lights — they are only red if there actually is another car in the intersection. Unlike a normal road, each road goes only one way, and has at most one car on it at a time.  Once a car reaches the end of the road, it disappears and a new car may appear at the start. Furthermore, there is a small number of drivers — typically one or two, but maybe eight or sixteen, but probably not one for every car. The drivers drive a car for a while, then stop it and run to the next car!  The drivers are pretty smart — if their car is stopped at a red stoplight then they’ll run to a stopped car that is not at a red stoplight (if one exists) and drive it for a while.

In our analogy each road represents a thread and each stoplight represents a mutex.  A mutex is a “mutually exclusive” section of code, also known as a “critical section”.  Only one thread can be executing in that code at one time. The car represents the position of the instruction counter in this thread.  When the car reaches the end of the road, the task is finished — the page is served. The drivers represent the processors, which give attention to one thread at a time and then context switch to another thread.  The time spent running from car to car is the time required to perform a thread context switch.

Now imagine that you want to maximize the throughput of this system — the total number of cars that reach the end of their road per hour.  How do you do it?  There are some “obvious” ways to do so:

  • hire more drivers (use more processors)
  • eliminate some stoplights by building overpasses at intersections (eliminate critical sections)
  • buy faster cars (use faster processors)
  • make the roads shorter (write pages that require less code)

You’ll note that each of these is either expensive or difficult.  Perf isn’t easy!

Now, I said that these are “obvious” ways to solve this problem, and those scare quotes were intentional.  Imagine a complex grid of roads with lots of stoplights, a moderate number of cars on the road, and two drivers.  It is quite unlikely that cars will spend a lot of time stopped at stoplights — mostly they’ll just breeze right on through.  But what happens when you throw another six drivers into the mix? Sure, more cars are being driven at any one time, but that means that the likelihood of congestion at stoplights just went up. Even though there are four times as many drivers, the additional time spent at stoplights means that the perf improvement is less than a factor of four. We say that such systems are not scalable.

Or consider a moderately congested freeway system with a whole lot of cars, drivers and intersections.  Now suppose that you keep the cars, drivers and intersections the same, but you shrink the whole system down to half its previous size. You make all the roads shorter, so that instead of having eight stoplights to the mile, now you’ve got twenty. Does total throughput get better or worse?  In a real traffic system, that would probably make things worse, and it can in web servers as well.  The cars spend all their time at intersections waiting for a driver to run over to them. Making code faster sometimes makes performance worse because thread congestion and context switches could be the problem, not total path length.

Similarly, making the cars faster often doesn’t help. In the real world of Seattle traffic, upgrading from my 140-or-so horsepower Miata to a 300 HP BMW isn’t going to get me home any faster.  Getting a faster processor and shorter program only helps if the “freeway” is clear of traffic. Otherwise, you sit there in your souped-up ultimate driving machine going zero at stoplights like everyone else.  Raw power does not scale in a world with lots of critical sections.

When perf tuning servers, use the performance monitor to keep a careful eye on not just pages served per second, but on thread switches per second, processor utilization and so on.  If you cannot saturate the processor and the number of thread switches is extremely high, then what is likely happening is that the drivers are spending way too much time running from car to car and not enough time actually driving. Clearly that’s not good for perf.  Tracking down and eliminating critical sections is often the key to improving perf in these scenarios.

Comments (1)

  1. A JOS reader interested in developing server software asked recently Is it possible to determine the