Monday, March 16, 2009

Is Dynamic is too dynamic?

I was just watching the start of a screencast by Kirill Osenkov.

In it he describes some of the new features for C# 4.0 starting with the dynamic keyword.

Take for example the following…
-------------------------------------------------------------

static void main()
{
    dynamic SomeVar = 1;
    SomeVar.Foo();
}
-------------------------------------------------------------

Now while I appreciate the ability to call into dynamic methods in this way… I feel it’s too easy to get things wrong.

I can call into this dynamic method several times and any mistakes made are simply not detectable until runtime.

So I can call a method correctly several times and then call it incorrectly once also and not notice the mistake until my programming logic is enacted at runtime.

-------------------------------------------------------------

static void main()
{
    dynamic SomeVar = SomeOfficeToolbarFactory.GetMeAToolbar();
    SomeVar.Show();
    SomeVar.Hide();
    SomeVar.Show();
    SomeVar.Hide();
    SomeVar.Show();
    SomeVar.Hide();
    SomeVar.Show();
    SomeVar.Hide();
    if (SomeSpecialConditionHere)
    {
        SomeVar.Showww(); // <- this does not exist at runtime.
    }
}
-------------------------------------------------------------

What about if I could define the dynamic methods that I expected to exist on a given type at runtime?

What if you could define a “dynamic partial interface” for any type which would list said methods?

So in VB.Net terms I could say…

-------------------------------------------------------------
Dynamic Partial Interface SomeOfficeToolBar
    Sub Show()
End Interface
-------------------------------------------------------------

If this definition existed then the compiler could detect that “Showwww()” was incorrect before runtime.

“Show()” and “Hide()” would still be detected and used dynamically but you would giving yourself design time aid in finding bugs in dynamic calls.

I guess it’s a bit like defining your external functions using a .h file in C++

Now technically this would no longer be a dynamic type. It would still be a static type. However you would have added the ability to statically check the code that made calls to methods which would be located dynamically at runtime.

 

Just a thought.


2 comments:

Kirill Osenkov said...

That's a good idea (making a dynamic object implement a certain interface). I think we were asked about this several times. It won't be in C# 4.0 for sure, but probably in some later version. Thanks!

Kirill Osenkov said...

Hi again Rory,

I've talked to our C# language PM Mads Torgersen and here's his response:

================

Hi Kirill,

We know about it but I don’t think we’ll support it directly. It is something people can do with various tricks on the side, but we feel like we shouldn’t endorse it, because the “dynamic” type is the thing that tells people (and tools) that dynamic dispatch is going on.

Mads