Will C#4.0 dynamic objects have some facility for duck typing? - dynamic

In C#4.0 we're going to get dynamic types, or objects whose "static type is dynamic", according to Anders. This will allow any method invocation resolution to happen at runtime rather than compile time. But will there be facility to bind the dynamic object to some sort of contract (and thereby also get full intellisense for it back), rather than allowing any call on it even if you know that is not likely to be valid.
I.e. instead of just
dynamic foo = GetSomeDynamicObject();
have the ability to cast or transform it to constrain it to a known contract, such as
IFoo foo2 = foo.To<IFoo>;
or even just
IFoo foo2 = foo as IFoo;
Can't find anything like that in the existing materials for C#4.0, but it seems like a logical extension of the dynamic paradigm. Anyone with more info?

I'm not aware of anything really resembling duck typing, I'm afraid. I've blogged about the idea, but I don't expect any support. It probably wouldn't be too hard to use Reflection.Emit to make a class which will generate an implementation of any given interface, taking a dynamic object in the constructor and just proxying each call through to it. Not ideal, but it might be a stopgap.

That's a cool idea.
If I understand you, you're describing/proposing a capability of the CLR, whereby, when you try and cast a dynamic object to an interface, it should look at what methods/properties the dynamic object supports and see if it has ones that effectively implement that interface. Then the CLR would take care of 'implementing IFoo' on the object, so you can then cast the dynamic object to an IFoo.
Almost certain that that will not be supported, but it's a interesting idea.

Tobias Hertkorn answered my question here with a link to his blogpost showing an example of how to use the Convert() method on MetaObject to return a dynamic proxy. It looks very promising.

Related

Where is changing the class of an object at runtime allowed

Do you know programming languages where changing the class of an object at runtime is allowed (supported)?
Please give a short example regarding the syntax. Give a use case, if you know any. Examples involving duck typing are welcome as well, so do not shy away from mentioning these languages.
Update: I figured out that Smalltalk has changeClassTo and become. CLOS can do change-class. I found a paper suggesting to use these mechanisms to implement 'husk objects' that are referenced at runtime, but only constructed from some persistence when actually accessed, providing some nifty lazy loading of related objects.
I assume, you mean the following:
You have an object of class A. But you would like to treat it as an object of class B.
There are some constructions possible:
If B is a subclass of A you can cast the object to B (but it should be created as B else you have unexpected (and hopefully unwanted) results).
In some languages you can cast anything to anything. If you know what you are doing, this is great, else prepare for several holes in your foot.
You mention ducktyping. I have no practical experience with it. But As far as I know, duck typing is something like this: "I need an object that support methods X, Y and Z." In that case you don't care about the class. You just want it to quack, swim and walk at your command.
Give a usecase
??? I'd expect you to ask for a solution on a specific use case.
Changing type of an object? I think "No."
But if you like to change part of an objects capabilities or behaviours have a look at loosely coupling!
For example your class holds a member of type File_Saver. There's a public setter accepting any instance of File_Saver and you can inject File_Saver_XML, File_Saver_PDF, ...
It's no common way, but any processing inside a class can be done by 1-n loosely coupled handlers, which you can exchange from outside.
Melt down to your question: You need a wrapper + a setter. :-)
Coming back to the case after some time, I've come to the conclusion that you want duck typing if you feel the need of changing an objects class.

Is it good convention for a class to perform functions on itself?

I've always been taught that if you are doing something to an object, that should be an external thing, so one would Save(Class) rather than having the object save itself: Class.Save().
I've noticed that in the .Net libraries, it is common to have a class modify itself as with String.Format() or sort itself as with List.Sort().
My question is, in strict OOP is it appropriate to have a class which performs functions on itself when called to do so, or should such functions be external and called on an object of the class' type?
Great question. I have just recently reflected on a very similar issue and was eventually going to ask much the same thing here on SO.
In OOP textbooks, you sometimes see examples such as Dog.Bark(), or Person.SayHello(). I have come to the conclusion that those are bad examples. When you call those methods, you make a dog bark, or a person say hello. However, in the real world, you couldn't do this; a dog decides himself when it's going to bark. A person decides itself when it will say hello to someone. Therefore, these methods would more appropriately be modelled as events (where supported by the programming language).
You would e.g. have a function Attack(Dog), PlayWith(Dog), or Greet(Person) which would trigger the appropriate events.
Attack(dog) // triggers the Dog.Bark event
Greet(johnDoe) // triggers the Person.SaysHello event
As soon as you have more than one parameter, it won't be so easy deciding how to best write the code. Let's say I want to store a new item, say an integer, into a collection. There's many ways to formulate this; for example:
StoreInto(1, collection) // the "classic" procedural approach
1.StoreInto(collection) // possible in .NET with extension methods
Store(1).Into(collection) // possible by using state-keeping temporary objects
According to the thinking laid out above, the last variant would be the preferred one, because it doesn't force an object (the 1) to do something to itself. However, if you follow that programming style, it will soon become clear that this fluent interface-like code is quite verbose, and while it's easy to read, it can be tiring to write or even hard to remember the exact syntax.
P.S.: Concerning global functions: In the case of .NET (which you mentioned in your question), you don't have much choice, since the .NET languages do not provide for global functions. I think these would be technically possible with the CLI, but the languages disallow that feature. F# has global functions, but they can only be used from C# or VB.NET when they are packed into a module. I believe Java also doesn't have global functions.
I have come across scenarios where this lack is a pity (e.g. with fluent interface implementations). But generally, we're probably better off without global functions, as some developers might always fall back into old habits, and leave a procedural codebase for an OOP developer to maintain. Yikes.
Btw., in VB.NET, however, you can mimick global functions by using modules. Example:
Globals.vb:
Module Globals
Public Sub Save(ByVal obj As SomeClass)
...
End Sub
End Module
Demo.vb:
Imports Globals
...
Dim obj As SomeClass = ...
Save(obj)
I guess the answer is "It Depends"... for Persistence of an object I would side with having that behavior defined within a separate repository object. So with your Save() example I might have this:
repository.Save(class)
However with an Airplane object you may want the class to know how to fly with a method like so:
airplane.Fly()
This is one of the examples I've seen from Fowler about an aenemic data model. I don't think in this case you would want to have a separate service like this:
new airplaneService().Fly(airplane)
With static methods and extension methods it makes a ton of sense like in your List.Sort() example. So it depends on your usage pattens. You wouldn't want to have to new up an instance of a ListSorter class just to be able to sort a list like this:
new listSorter().Sort(list)
In strict OOP (Smalltalk or Ruby), all methods belong to an instance object or a class object. In "real" OOP (like C++ or C#), you will have static methods that essentially stand completely on their own.
Going back to strict OOP, I'm more familiar with Ruby, and Ruby has several "pairs" of methods that either return a modified copy or return the object in place -- a method ending with a ! indicates that the message modifies its receiver. For instance:
>> s = 'hello'
=> "hello"
>> s.reverse
=> "olleh"
>> s
=> "hello"
>> s.reverse!
=> "olleh"
>> s
=> "olleh"
The key is to find some middle ground between pure OOP and pure procedural that works for what you need to do. A Class should do only one thing (and do it well). Most of the time, that won't include saving itself to disk, but that doesn't mean Class shouldn't know how to serialize itself to a stream, for instance.
I'm not sure what distinction you seem to be drawing when you say "doing something to an object". In many if not most cases, the class itself is the best place to define its operations, as under "strict OOP" it is the only code that has access to internal state on which those operations depend (information hiding, encapsulation, ...).
That said, if you have an operation which applies to several otherwise unrelated types, then it might make sense for each type to expose an interface which lets the operation do most of the work in a more or less standard way. To tie it in to your example, several classes might implement an interface ISaveable which exposes a Save method on each. Individual Save methods take advantage of their access to internal class state, but given a collection of ISaveable instances, some external code could define an operation for saving them to a custom store of some kind without having to know the messy details.
It depends on what information is needed to do the work. If the work is unrelated to the class (mostly equivalently, can be made to work on virtually any class with a common interface), for example, std::sort, then make it a free function. If it must know the internals, make it a member function.
Edit: Another important consideration is performance. In-place sorting, for example, can be miles faster than returning a new, sorted, copy. This is why quicksort is faster than merge sort in the vast majority of cases, even though merge sort is theoretically faster, which is because quicksort can be performed in-place, whereas I've never heard of an in-place merge-sort. Just because it's technically possible to perform an operation within the class's public interface, doesn't mean that you actually should.

Making best use of Objective-C dynamic features

I have been using Objective-C for a little while but being from a static type background (C#) I think I am using it in a very static way. Declaring objects as id feels alien to me and I can't see what the benefits are. Can anyone shine a light for me to get a better understanding of this?
Objective-C is kind of a hybrid language, in which you can be as dynamic and as static as you want. You can declare all the types of all the variables if you want, you can even declare delegate variables as NSObject<Protocol>* if you want. The id type works less as a real type and more like a hint to the compiler telling him "hey, I know what I'm doing, just trust me on this", making the compiler avoid any type checking on that particular variable.
The first obvious benefit of the Objective-C type system is that container types (NSArray, NSDictionary, NSSet) accept and return id types. This removes the need for templates and generics altogether (like in C++, Java and C#).
Even better, you can actually have containers with elements of any kind inside. As long as you know what goes inside, nobody will complain if you add two NSStrings, one NSNumber and an NSValue inside the same NSArray. You can do that in other languages, but you have to use the "Object" base class, or the void* type, and then you require to box and unbox (or cast up and down) variables in order to get the same behaviour. In Objective-C you just assign, which removes the noise generated by casting operators and boxing operations. Then you can ask "respondsToSelector:" or "class" to each object, in order to know the identity and the operations you can perform with them, at runtime. In Objective-C, reflection is a first class citizen.
Another benefit is the reduced compilation times; the compilation of an Objective-C program is in general much faster than its equivalent in C++, given that there aren't that many type checks performed, and much linking is done at runtime. The compiler trusts more the programmer.
Finally, Objective-C's dynamic type system makes possible to have a tool like Interface Builder. This is the main reason why Cocoa and Cocoa Touch has faster development times; the GUI can generate code with "id" types all over the place, and this is deserialized whenever the NIB is loaded in memory. The only language that comes close to Objective-C in terms of UI design experience is C# (and VB.NET, of course) but at the price of a much heavier application.
I personally prefer to work with a more static type checking, and I even turn on the "Treat Warnings as Errors" setting in the Objective-C compiler; I've written a blog post about it:
http://akosma.com/2009/07/16/objective-c-compiler-warnings/
This is particularly useful when you are working with developers who are new to the language. It makes the compiler whine more often than usual :)
Static type system pundits might disagree with all these points, arguing that static type checking allows for "intellisense" IDEs and better maintenance in general. I worked using .NET for years (2001 - 2006) and I must say that dynamic languages tend to produce less code, are easier to read, and in general, gives more freedom to work. The tradeoff (there's always a tradeoff) is that there is less information at compile time. But as I tend to say, compilers are a poor man's suite of tests. The best thing IMHO is to have a good suite of tests, and a good bunch of human testers torturing your code to find bugs, no matter what language you choose.
Objective-C's dynamism shines not just in the fact that every object is an id. Rather, it shines in the power of the Objective-C runtime and the ease to use it. A few examples of clever uses of runtime by Apple itself:
DO allows you to set up an proxy object for an Obj-C object in a separate app / separate machine. This is done by intercepting all the message sent to the proxy object, packing it up, sending it to the other app, and invoking it there.
KVO is implemented by dynamically replacing the setter method so that it automatically notifies the observers. (Well it's in fact subtler than that...)
CoreData accessors are generated at run time for each subclass of NSManagedObject, etc.
And, you can use the runtime from your code, too. I once used it for a good effect, mimicking CoreData and generating accessors at the run time, and having only their declaration in the header file. Thus you can get the merit of both the static typing (compile time error from the declaration in the header) and the dynamism (runtime generation of methods).
Mike Ash has written an excellent series of blog posts on how the runtime works and how to use it effectively. You just have to read it! DO, KVO, message forwarding and more. There are also many other interesting posts on the net, like fun with kvc and higher-order messaging 1, 2.
It’s actually rather rare that you would need to declare an object as type id, as you should generally know what type you are expecting. Sometimes you might use an id<Protocol> type, if you don’t know the actual type of an object but know that it should conform to a specific protocol.
Is there a particular scenario you are thinking of?
Passing instance as id is common when designing action's method; connecting a button to a method, the target looks like doSomething:(id) sender;.
In this case, it allows different kind of controls to use the same action's method, without prior knowledge of what these controls will be. In the action's method code, you can test for the class of the sender or simply use its tag property, to decide what to do.
-(void) doSomething:(id) sender {
// Get the sender's tag whatever it is
int tag = [sender tag];
switch(tag) {
case 1:
// ...
break;
case 2:
// ...
break;
}
}

What features do you wish were in common languages? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What features do you wish were in common languages? More precisely, I mean features which generally don't exist at all but would be nice to see, rather than, "I wish dynamic typing was popular."
I've often thought that "observable" would make a great field modifier (like public, private, static, etc.)
GameState {
observable int CurrentScore;
}
Then, other classes could declare an observer of that property:
ScoreDisplay {
observe GameState.CurrentScore(int oldValue, int newValue) {
...do stuff...
}
}
The compiler would wrap all access to the CurrentScore property with notification code, and observers would be notified immediately upon the value's modification.
Sure you can do the same thing in most programming languages with event listeners and property change handlers, but it's a huge pain in the ass and requires a lot of piecemeal plumbing, especially if you're not the author of the class whose values you want to observe. In which case, you usually have to write a wrapper subclass, delegating all operations to the original object and sending change events from mutator methods. Why can't the compiler generate all that dumb boilerplate code?
I guess the most obvious answer is Lisp-like macros. Being able to process your code with your code is wonderfully "meta" and allows some pretty impressive features to be developed from (almost) scratch.
A close second is double or multiple-dispatch in languages like C++. I would love it if polymorphism could extend to the parameters of a virtual function.
I'd love for more languages to have a type system like Haskell. Haskell utilizes a really awesome type inference system, so you almost never have to declare types, yet it's still a strongly typed language.
I also really like the way you declare new types in Haskell. I think it's a lot nicer than, e.g., object-oriented systems. For example, to declare a binary tree in Haskell, I could do something like:
data Tree a = Node a (Tree a) (Tree a) | Nothing
So the composite data types are more like algebraic types than objects. I think it makes reasoning about the program a lot easier.
Plus, mixing in type classes is a lot nicer. A type class is just a set of classes that a type implements -- sort of like an interface in a language like Java, but more like a mixin in a language like Ruby, I guess. It's kind of cool.
Ideally, I'd like to see a language like Python, but with data types and type classes like Haskell instead of objects.
I'm a big fan of closures / anonymous functions.
my $y = "world";
my $x = sub { print #_ , $y };
&$x( 'hello' ); #helloworld
and
my $adder = sub {
my $reg = $_[0];
my $result = {};
return sub { return $reg + $_[0]; }
};
print $adder->(4)->(3);
I just wish they were more commonplace.
Things from Lisp I miss in other languages:
Multiple return values
required, keyword, optional, and rest parameters (freely mixable) for functions
functions as first class objects (becoming more common nowadays)
tail call optimization
macros that operate on the language, not on the text
consistent syntax
To start things off, I wish the standard for strings was to use a prefix if you wanted to use escape codes, rather than their use being the default. E.g. in C# you can prefix with # for a raw string. Similarly, Python has the r prefix. I'd rather use #/r when I don't want a raw string and need escape codes.
More powerful templates that are actually designed to be used for metaprogramming, rather than C++ templates that are really designed for relatively simple generics and are Turing-complete almost by accident. The D programming language has these, but it's not very mainstream yet.
immutable keyword. Yes, you can make immutable objects, but that's lot pain in most of the languages.
class JustAClass
{
private int readonly id;
private MyClass readonly obj;
public MyClass
{
get
{
return obj;
}
}
}
Apparently it seems JustAClass is an immutable class. But that's not the case. Because another object hold the same reference, can modify the obj object.
So it's better to introduce new immutable keyword. When immutable is used that object will be treated immutable.
I like some of the array manipulation capabilities found in the Ruby language. I wish we had some of that built into .Net and Java. Of course, you can always create such a library, but it would be nice not to have to do that!
Also, static indexers are awesome when you need them.
Type inference. It's slowly making it's way into the mainstream languages but it's still not good enough. F# is the gold standard here
I wish there was a self-reversing assignment operator, which rolled back when out of scope. This would be to replace:
type datafoobak = item.datafoobak
item.datafoobak = 'tootle'
item.handledata()
item.datafoobak = datafoobak
with this
item.datafoobar #=# 'tootle'
item.handledata()
One could explicitely rollback such changes, but they'd roll back once out of scope, too. This kind of feature would be a bit error prone, maybe, but it would also make for much cleaner code in some cases. Some sort of shallow clone might be a more effective way to do this:
itemclone = item.shallowclone
itemclone.datafoobak='tootle'
itemclone.handledata()
However, shallow clones might have issues if their functions modified their internal data...though so would reversible assignments.
I'd like to see single-method and single-operator interfaces:
interface Addable<T> --> HasOperator( T = T + T)
interface Splittable<T> --> HasMethod( T[] = T.Split(T) )
...or something like that...
I envision it as being a typesafe implementation of duck-typing. The interfaces wouldn't be guarantees provided by the original class author. They'd be assertions made by a consumer of a third-party API, to provide limited type-safety in cases where the original authors hadn't anticipated.
(A good example of this in practice would be the INumeric interface that people have been clamboring for in C# since the dawn of time.)
In a duck-typed language like Ruby, you can call any method you want, and you won't know until runtime whether the operation is supported, because the method might not exist.
I'd like to be able to make small guarantees about type safety, so that I can polymorphically call methods on heterogeneous objects, as long as all of those objects have the method or operator that I want to invoke.
And I should be able to verify the existence of the methods/operators I want to call at compile time. Waiting until runtime is for suckers :o)
Lisp style macros.
Multiple dispatch.
Tail call optimization.
First class continuations.
Call me silly, but I don't think every feature belongs in every language. It's the "jack of all trades, master of none" syndrome. I like having a variety of tools available, each one of which is the best it can be for a particular task.
Functional functions, like map, flatMap, foldLeft, foldRight, and so on. Type system like scala (builder-safety). Making the compilers remove high-level libraries at compile time, while still having them if you run in "interpreted" or "less-compiled" mode (speed... sometimes you need it).
There are several good answers here, but i will add some:
1 - The ability to get a string representation for the current and caller code, so that i could output a variable name and its value easily, or print the name of the current class, function or a stack trace at any time.
2 - Pipes would be nice too. This feature is common in shells, but uncommon in other types of languages.
3 - The ability to delegate any number of methods to another class easily. This looks like inheritance, but even in the presence of inheritance, once in a while we need some kind of wrapper or stub which cannot be implemented as a child class, and forwarding all methods requires a lot of boilerplate code.
I'd like a language that was much more restrictive and was designed around producing good, maintainable code without any trickiness. Also, it should be designed to give the compiler the ability to check as much as possible at compile time.
Start with a newish VM based heavily OO language.
Remove complexities like Operator Overloading and multiple inheritance if they exist.
Force all non-final variables to Private.
Members should default to "Final" but should have a "Variable" tag to override it. (This may require built-in support for the builder pattern to be fully effective).
Variables should not allow a "Null" value by default, but variables and parameters should have a "nullable" tag that indicates that null is acceptable for that variable.
It would also be nice to be able to avoid some common questionable patterns:
Some built-in way to simplify IOC/DI to eliminate singletons,
Java--eliminate checked exceptions so people stop putting in empty catches.
Finally focus on code readability:
Named Parameters
Remove the ability to create methods more than, say, 100 lines long.
Add some complexity analysis to help detect complicated methods and classes.
I'm sure I haven't named 1/10 of the items possible, but basically I'm talking about something that compiles to the same bytecode as C# or Java, but is so restrictive that a programmer can hardly help but write good code.
And yes, I know there are lint-type tools that will do some of this, but I've never seen them on any project I've worked on (and they wouldn't physically run on the code I'm working on now, for instance) so they aren't being very helpful, and I would love to see a compile actually fail when you type in a 101 line method...

What do you call a method of an object that changes its class?

Let's say you have a Person object and it has a method on it, promote(), that transforms it into a Captain object. What do you call this type of method/interaction?
It also feels like an inversion of:
myCaptain = new Captain(myPerson);
Edit: Thanks to all the replies. The reason I'm coming across this pattern (in Perl, but relevant anywhere) is purely for convenience. Without knowing any implementation deals, you could say the Captain class "has a" Person (I realize this may not be the best example, but be assured it isn't a subclass).
Implementation I assumed:
// this definition only matches example A
Person.promote() {
return new Captain(this)
}
personable = new Person;
// A. this is what i'm actually coding
myCaptain = personable.promote();
// B. this is what my original post was implying
personable.promote(); // is magically now a captain?
So, literally, it's just a convenience method for the construction of a Captain. I was merely wondering if this pattern has been seen in the wild and if it had a name. And I guess yeah, it doesn't really change the class so much as it returns a different one. But it theoretically could, since I don't really care about the original.
Ken++, I like how you point out a use case. Sometimes it really would be awesome to change something in place, in say, a memory sensitive environment.
A method of an object shouldn't change its class. You should either have a member which returns a new instance:
myCaptain = myPerson->ToCaptain();
Or use a constructor, as in your example:
myCaptain = new Captain(myPerson);
I would call it a conversion, or even a cast, depending on how you use the object. If you have a value object:
Person person;
You can use the constructor method to implicitly cast:
Captain captain = person;
(This is assuming C++.)
A simpler solution might be making rank a property of person. I don't know your data structure or requirements, but if you need to something that is trying to break the basics of a language its likely that there is a better way to do it.
You might want to consider the "State Pattern", also sometimes called the "Objects for States" pattern. It is defined in the book Design Patterns, but you could easily find a lot about it on Google.
A characteristic of the pattern is that "the object will appear to change its class."
Here are some links:
Objects for States
Pattern: State
Everybody seems to be assuming a C++/Java-like object system, possibly because of the syntax used in the question, but it is quite possible to change the class of an instance at runtime in other languages.
Lisp's CLOS allows changing the class of an instance at any time, and it's a well-defined and efficient transformation. (The terminology and structure is slightly different: methods don't "belong" to classes in CLOS.)
I've never heard a name for this specific type of transformation, though. The function which does this is simply called change-class.
Richard Gabriel seems to call it the "change-class protocol", after Kiczales' AMOP, which formalized as "protocols" many of the internals of CLOS for metaprogramming.
People wonder why you'd want to do this; I see two big advantages over simply creating a new instance:
faster: changing class can be as simple as updating a pointer, and updating any slots that differ; if the classes are very similar, this can be done with no new memory allocations
simpler: if a dozen places already have a reference to the old object, creating a new instance won't change what they point to; if you need to update each one yourself, that could add a lot of complexity for what should be a simple operation (2 words, in Lisp)
That's not to say it's always the right answer, but it's nice to have the ability to do this when you want it. "Change an instance's class" and "make a new instance that's similar to that one" are very different operations, and I like being able to say exactly what I mean.
The first interesting part would be to know: why do you want/need an object changes its class at runtime?
There are various options:
You want it to respond differently to some methods for a given state of the application.
You might want it to have new functionality that the original class don't have.
Others...
Statically typed languages such as Java and C# don't allow this to happen, because the type of the object should be know at compile time.
Other programming languages such as Python and Ruby may allow this ( I don't know for sure, but I know they can add methods at runtime )
For the first option, the answer given by Charlie Flowers is correct, using the state patterns would allow a class behave differently but the object will have the same interface.
For the second option, you would need to change the object type anyway and assign it to a new reference with the extra functionality. So you will need to create another distinct object and you'll end up with two different objects.