Import improvement

Andrei Alexandrescu SeeWebsiteForEmail at erdani.org
Mon Oct 15 08:37:06 PDT 2012


On 10/15/12 8:43 AM, Manu wrote:
> So I'm getting sick of this in my files:
[snip litany of imports]
> This is obviously silly.

Agreed.

> I know this could be improved with some care, more liberal public
> imports (dangerous, you risk ending up with EVERYTHING as public import
> if it sticks as a standard convention), better maintained
> dependencies... but it's not realistic in a production environment. That
> sort of maintenance just never happens.
>
> I suggest expanding the selective import mechanism to extend to modules,
> not just functions within a module, eg:
>
> module stache.states.ingamestate;
>
> import fuji: filesystem, render, matrix, material, primitive, system, font;
> import std: xml, string, conv, random, algorithm;
> import stache: game, battlecamera;
> import stache.i: statemachine, entity, collider;
> import stache.entity: combatant, paimei;
> import stache.thinkers: localplayer, nullthinker;
> import stache.sound: soundset, music;
> import stache.util.eventtypes;
>
> This is much better! Saved ~25 lines of import rubbish, and it also
> enforces logical grouping; individual import statements tends to lead to
> related submodules being distanced from eachother, this way, they appear
> on the same line.
>
> Surely this has been considered before. Any reasons it's not supported?

I don't think imports from a specific package have been considered.

In my personal opinion, imports are a necessary evil and it's sort of a 
bummer that the most accessible place in any source file - the top lines 
- is occupied by the crappy legal disclaimer (which, after having talked 
to a lawyer, I always put at the bottom since being at the top is not a 
requirement), and the litany of imports that the module is using. I'd 
make all imports local or put them at the bottom of the file if it 
weren't too much of a shock to others.

Three remarks on this particular problem.

1. I expect large packages to introduce a module "all.di" or "_.di" to 
publicly import everything in the package. That could help some use cases.

2. The import declaration accepts a list of modules, and several may be 
on one line. I think that's a significant positive difference from C, 
C++, or Go, all of which force one imported module per line. I always 
advocate imports from the same package in the same "import" declaration, 
ordered alphabetically:

import fuji.filesystem, fuji.font, fuji.material, fuji.matrix,
     fuji.primitive, fuji.render, fuji.system;
import std.algorithm, std.conv, std.random, std.string, std.xml;
...

That makes the existing system much more palatable.

3. I think local imports are currently underutilized. It would be 
interesting to see what kind of project dynamics they enable.


Andrei


More information about the Digitalmars-d mailing list