D versus Objective C Comparison

Michel Fortin michel.fortin at michelf.com
Mon Feb 2 18:09:44 PST 2009


On 2009-02-01 14:45:58 -0500, Walter Bright <newshound1 at digitalmars.com> said:

> Setting aside the technical issues for the moment, isn't that exactly 
> what inheritance is supposed to be good for?

I'll attempt a better example of something useful with class 
extensions. Say you have these classes:

	class Node
	{
		string path();
		string name();
	}

	class File : Node
	{
		...
	}

	class Directory : Node
	{
		Node[] children();
		...
	}

And a couple of functions returning directories and files:

	File getConfigFile();
	Directory getResourceDirectory();
	Directory getDataDirectory();

Now, you may not have control over these functions, if you subclass 
File or Directory to do what you want, it won't cause these functions 
to magically create instances of your class.

Say you want to implement a backup function traversing the filesystem 
tree. In Objective-C, I'd simply create a category adding a new method. 
If you had something like it in D, it could look like this:

	extension NodeBackup : Node
	{
		void backup(string backupPath) { }
	}

Where I'm extending Node with an extension named NodeBackup, allowing 
me to call the backup function as if it was a member of Node. From 
there, I create another extension for File, overriding the backup 
function provided by NodeBackup:

	extension FileBackup : NodeBackup, File
	{
		override void backup(string backupPath)
		{
			copy(this.path, backupPath ~ "/" ~ this.name);
		}
	}

And so on for Directory.

	extension DirectoryBackup : NodeBackup, Directory
	{
		override void backup(string backupPath)
		{
			foreach(child; children)
				child.backup(backupPath ~ "/" ~ this.name);
		}
	}

All this you can do with the visitor pattern if you need to. But the 
visitor pattern is a lot more clumbersome to implement, and much less 
natural to use...

	getDataDirectory.backup("/backup_disk");

vs. something like this:

	getDataDirectory.accept(new BackupVisitor("/backup_disk"));


-- 
Michel Fortin
michel.fortin at michelf.com
http://michelf.com/




More information about the Digitalmars-d mailing list