D versus Objective C Comparison
Nick Sabalausky
a at a.a
Mon Feb 2 22:59:08 PST 2009
"Michel Fortin" <michel.fortin at michelf.com> wrote in message
news:gm8dhq$sj7$1 at digitalmars.com...
> On 2009-02-02 21:19:52 -0500, Daniel Keep <daniel.keep.lists at gmail.com>
> said:
>
>>
>>
>> Michel Fortin wrote:
>>> [stuff]
>>
>> Wouldn't this be just as well served with Walter's "universal function
>> syntax"; ie:
>>
>> void backup(File this, string backupPath)
>> {
>> copy(this.path, backupPath ~ "/" ~ this.name);
>> }
>>
>> File someFile;
>> someFile.backup(backupPath);
>
> It would work in your example, but not in mine. Note the difference:
>
> foreach(child; children)
> child.backup(backupPath ~ "/" ~ this.name);
>
> Statically, child is a Node here. If at runtime child is a File, the
> backup function is overriden by the FileBackup extension of File, so it'd
> call the backup function from FileBackup, not NodeBackup. If at runtime
> child is a Directory, it'll call DirectoryBackup's backup function. At
> least, that's what it would do in Objective-C using categories. And that's
> why you don't need the visitor pattern in Objective-C.
>
> --
> Michel Fortin
> michel.fortin at michelf.com
> http://michelf.com/
>
I had been slowly coming around to the idea of having that universal
function syntax instead of C#-style explicit extension methods, but maybe
this need for dynamic dispatch is a good reason to prefer explicit extension
methods:
// As in C#, the "this" means backup() is an extension method
void backup(this Node obj, string backupPath)
{
// base impl
}
void backup(this File obj, string backupPath)
{
copy(obj.path, backupPath ~ "/" ~ obj.name);
}
void backup(this Directory obj, string backupPath)
{
foreach(child; children)
child.backup(backupPath ~ "/" ~ obj.name);
}
I'm not exactly sure what C# does in this case, but what I'm proposing here
is that this could (somehow) cause dynamic dispatch to be used. Maybe by
adding "backup" to appropriate vtables or automatically generating something
like this that gets swapped in wherever "backup" is called:
void _backup(this Object obj, string backupPath)
{
if(cast(File)obj)
backup(cast(File)obj, backupPath);
else if(cast(Directory)obj)
backup(cast(Directory)obj, backupPath);
else if(cast(Object)obj)
backup(cast(Object)obj, backupPath);
else if(obj is null)
throw new NullPointerException();
else
{ /* shouldn't happen unless compiler's static type checking messed
up */ }
}
Or something else to that general effect.
More information about the Digitalmars-d
mailing list