On 03/15/2016 07:29 AM, WhatMeWorry wrote:

>> SpriteRenderer Renderer;  // Although, I would name it 'renderer'

> Ok. I was trying something more D like, by doing:
>
> SpriteRenderer Renderer = new SpriteRenderer();

That would work if the variable were const or immutable and if everything needed to execute the expression were available at compile time:

const(SpriteRenderer) renderer = new SpriteRenderer();
immutable(SpriteRenderer) renderer = new SpriteRenderer();

(Note: Associative arrays literals still cannot be initialized with that syntax and arrays may have performance implications.)

For mutable variables and for anything in general, module variables can be initialized in 'statit this()' and 'shared static this()' scopes:

static this() {
    renderer = new SpriteRenderer();
}

The difference is that 'static this()' is executed at runtime before any code in the module gets executed. It is like the constructor of the whole module. (You can have many disjoint 'static this()' blocks, which would all get executed.)

> In large projects with 1000s of
> line of code and many many modules, classes, structs, and functions; is
> it probably true that most of the time the vast majority of variables
> are going to be inside one of above constructs?

In D, everything will be inside one of those constructs because you included "modules". :) Like many modern languages, D lacks a global scope. Although we are advised to use the global scope much less in general, it is less applicable to D. In other words, it is fine to have module variables. For example, if a module consists of a single class, there wouldn't be any difference between making a variable class-static or module-scope. (Others, please correct me if you know any differences.)

> And is there a name for the variables that fall outside of the above
> constructs?

I think module-scope or module would work.

> I see so many tiny code snippets in books and docs, that when I do look
> at large dub/github projects, I'm not sure how to organize the "stuff"
> that slops over the edges.

That's always hard :) but "cohesion" seems to be a winning goal: program constructs should have little responsibilities.

Ali

Reply via email to