Strategies for resolving cyclic dependencies in static ctors

Graham St Jack Graham.StJack at internode.on.net
Tue Mar 22 16:12:04 PDT 2011


On 23/03/11 03:41, Steven Schveighoffer wrote:
> On Mon, 21 Mar 2011 20:12:55 -0400, Nick Sabalausky <a at a.a> wrote:
>
>> I'm intending this thread as somewhat of a roundtable-like discussion.
>> Hopefully we can come up with good material for a short article on 
>> Wiki4D,
>> or maybe the D website, or wherever.
>>
>> The scenario: A coder is writing some D, compiles, runs and gets a 
>> "Cyclic
>> dependency in static ctors" error. Crap! A pain for experienced D 
>> users, and
>> very bad PR for new D users. (Hopefully we'll eventually get some 
>> sort of
>> solution for this, but in the meantime D users just have to deal with 
>> it.)
>>
>> The question: What now? What strategies do people find useful for 
>> dealing
>> with this? Any specific "first steps" to take? Best practices? Etc.
>
> What one can try is to factor out the initialization code into a 
> separate module.  Essentially if you have:
>
> module a;
> import f : someFunction;
> import b; // conflicts because of circular dependencies
>
> int aglobal;
>
> static this()
> {
>   aglobal = someFunction();
> }
>
> You can do something like:
>
> module a_static;
> import f : someFunction;
>
> int aglobal;
>
> static this()
> {
>    aglobal = someFunction();
> }
>
> in a.d:
> module a;
> public import a_static;
> import b;
>
> Of course, there can be reprecussions -- you may need to have aglobal 
> declared in a.d.  In those cases, one can try to hide the cycle as Max 
> Samuckha stated, but I'd rather see a compiler option than these kinds 
> of workarounds.  The workarounds can be unobvious, but can be just as 
> dangerous.
>
> -Steve

My own solution to this "problem" is to never have circular imports at 
all. The build system I use prohibits them, so any careless introduction 
of a circularity is spotted immediately and I refactor the code to 
eliminate the circularity. I have never come across a valid need for 
circularities, and have never had any trouble eliminating any that creep in.

Avoiding circularities has plenty of advantages, like progressive 
development, testing and integration. On bigger projects these 
advantages are very important, and even on small ones they are useful.

-- 
Graham St Jack



More information about the Digitalmars-d mailing list