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

Steven Schveighoffer schveiguy at yahoo.com
Mon Nov 29 07:39:00 PST 2010


On Sun, 28 Nov 2010 09:58:42 -0500, Per Ångström <d-news at autark.se> wrote:

> On 2010-11-15 16:52, Steven Schveighoffer wrote:
>> On Sun, 14 Nov 2010 05:28:29 -0500, Per Ångström <d-news at autark.se>  
>> wrote:
>>> Fortunately, by separating interface and implementation, one can at
>>> least keep the implementation modules free from interdependencies.
>>> It's not perfect but it's not a complete mess either.
>>
>> It is one way to keep dependencies down. And less dependencies means
>> less coupling, meaning importing one module doesn't make you import (and
>> include the code for) many other modules. The compiler isn't yet mature
>> enough to trim out some code that is never used.
>
> I have found a way to detect unwanted interdependencies between  
> implementation modules, by declaring a static constructor in those  
> modules that should not depend on other implementation modules.
>
> // Student.d
> import IStudent;
> import ITeacher;
>
> class Student : IStudent {
> // ...
> 	void ask(ITeacher teacher)
> 	{
> 		teacher.teach(this);
> 	}
> 	static this() {}
> }
>
> // Teacher.d
> import ITeacher;
> import IStudent;
>
> class Teacher: ITeacher {
> 	void teach(IStudent student)
> 	{
> 		student.learn(this, "knowledge");
> 	}
> 	static this() {}
> }
>
> Now if Teacher and Student were to accidentally import each other, I  
> would get a runtime error:
> object.Exception: Cyclic dependency in module Student
>
> However, I wish the situation could be detected at compile-time.

It could only be detected at link-time, and the linker doesn't do any  
custom processing, it just links.

But in any case, I still don't understand why you want to avoid  
interdependencies.  D is supposed to handle them well.

-Steve


More information about the Digitalmars-d-learn mailing list