Is there a way to forward-declare interfaces to avoid module interdependencies?

Steven Schveighoffer schveiguy at yahoo.com
Thu Nov 11 08:21:16 PST 2010


On Thu, 11 Nov 2010 11:07:42 -0500, Per Ångström <d-news at autark.se> wrote:

> On 2010-11-11 15:51, Jacob Carlborg wrote:
>> First you have to import ITeacher in Student.d (if I'm reading this
>> right).
>
> No, the code works fine as is, but if I move the import of ITeacher from  
> IStudent.d to Student.d, IStudent.d won't compile:
>
> IStudent.d(4): Error: identifier 'ITeacher' is not defined
> IStudent.d(4): Error: ITeacher is used as a type
>
>> Second, D has (generally) no problems with circular references.
>
> No, but I have! ;-) To be honest, I would have wanted D to outright  
> outlaw circular references.

First, you can't forward-declare classes in one file that are defined in  
another file, instead of importing.  The reason is because in D, the  
module is the namespace that the class is declared in.

So for instance, when you define IStudent in IStudent.d, it's full name is  
IStudent.Istudent

if you did something like:

interface IStudent;

in ITeacher.d, then it's full name would be ITeacher.IStudent, not  
IStudent.IStudent.  So it's not the same.

Second, you are only having fits about forward declarations because you  
aren't used to it :)  That being said, D has had many forward reference  
bugs (I believe there are still a few active ones), so it doesn't always  
*just work*.  Plus there's the issue of circular imports causing code to  
fail at runtime due to module construction dependencies.

But in any case, you shouldn't worry about it, just import away, and the  
compiler can take it.

>> You only get problems when two modules is a part of a circular reference
>> and both have module constructors. If you porting C++ code you will not
>> have this problem since C++ doesn't have module constructors.
>
> Actually, I'm more thinking whether D would be a good language for  
> building really big systems. If the language more or less requires many  
> modules to import each other, that's a big drawback in my opinion, since  
> that makes a mess of the dependency graph. It also makes independent  
> testing of individual modules a lot harder.

um... Java anyone?  I think there's been one or two big systems built with  
Java, but I might be guessing :)

>> BTW, you generally don't separate your interface and implementation in D
>> (you can to that if you want to hide your implementation).
>
> I think information hiding is essential for a large-scale design to be  
> comprehensible as a whole. Agreed, the module system in D hides a lot of  
> implementation detail from being included in each compilation unit, but  
> we must also consider not overloading the programmer with needless  
> information.
>
> But then again, maybe I just need to stop thinking in C++.

Yes :)

-Steve


More information about the Digitalmars-d-learn mailing list