"Global" imports vs scoped imports

Jonathan M Davis jmdavisProg at gmx.com
Sun Feb 9 16:24:10 PST 2014


On Sunday, February 09, 2014 19:12:19 Jeremy DeHaan wrote:
> I am working on a library, and I put all imports at the top of my
> source files under the module declaration. I was starting to
> think that it might be a good idea to start scoping some imports
> to reduce the number that might be used by a giving project, but
> how beneficial is this? Are there any kind of general rules for
> when to use module level imports vs scoped imports?

The main place to use scoped imports in templated functions, because then the 
imports are only used if/when the template is instantiated. Outside of 
templated code, it's a matter of style and depends on how much in the module 
needs that import. For instance, if you're using std.range everywhere in a 
module, it's kind of silly to import it in every function in your module, as 
that's a lot of extra lines of code for little benefit. At that point, it's 
arguably better to just import it at the top. On the other hand, if you only 
using it within a handful of functions, by scoping the imports, it's clear 
what's using it, and if those functions all went away or were refactored such 
that they didn't need std.range anymore, then it would be clear that the 
imports could go away, whereas if the import is at the module level, it's not 
always obvious when you don't need it anymore.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list