lua-users home
lua-l archive

[Date Prev][Date Next][Thread Prev][Thread Next] [Date Index] [Thread Index]


June 10 2016 10:39 PM, "Hisham" <h@hisham.hm> wrote:


> My reasoning for the latter is that using inconsistent, `local x =
> require "y"` types of names is counterproductive: especially when
> looking at someone else's code, having to keep in mind how a module
> author decided to call a well-known library is an avoidable extra
> cognitive load, and having to skim back and forth to look at the
> require() list is annoying.
>
> [...]
>
> So, in short, the way I try to do things is to keep it simple:
> 
> project Foo, rockspec foo, local foo = require("foo")


I think it depends what kind of code you are writing,
and which dependency you are talking about.

First, you cannot always do that. For instance, even
ignoring the pl / penlight distinction, you probably
never want to require "pl" in a large project. So you
do things like:

    local pretty = require "pl.pretty".

Second, the local variable you are going to use is
an abstraction whereas the module is an implementation.
It makes a lot of sense to write something like:

    local json = require "cjson"

because json and cjson can (in most cases) be used
interchangeably.

Third, for modules that behave like classes but I need
a singleton, I often want to keep the name for the
singleton, i.e.:

    local Redis = require "redis"
    local redis = Redis.new(...)

Fourth, for larger projects I tend to always use
dependency injection, which means I will write
something like:

    local Something = require "something"
    local Redis = require "redis"
    local redis = Redis.new(...)
    local something = Something.new {
        json = require "cjson",
        redis = redis,
    }

Finally, I am starting to like the practice of module
namespacing by organization, i.e. "mycompany.util.stack".
However when doing this I am unsure how to package those
modules as rocks. Make a single "mycompany" rock?
Make "mycompany-util"? Make "mycompany-util-stack"?

For close source, pure Lua modules I am shifting towards
the second solution, but still allow users to just require
a part of it (i.e. the Penlight model minus the global
namespace pollution when requiring "pl"). For Open
Source the third one appears to make more sense, but
I am wondering if the trade-off in usability from the
second one would not make sense as well ("mycompany"
could be anything else, like "org.conman" here).

-- 
Pierre Chapuis