Elixir: Define criteria for choice between `__MODULE__` and module name

Created on 17 Aug 2018  ·  10Comments  ·  Source: elixir-lang/elixir

When defining a @type t :: %_{}, we vary between __MODULE__ and the actual module name.

In general we use the form:

@type t :: %__MODULE__{}

But in the following modules we use the actual module name:

  • lib/elixir/lib/range.ex
  • lib/elixir/lib/calendar/time.ex
  • lib/elixir/lib/calendar/date.ex
  • lib/elixir/lib/calendar/naive_datetime.ex
  • lib/elixir/lib/kernel.ex

Do we want to be consistent, or do we think that the current mix of approaches is a non-issue?

For discussion, see #8103.

Elixir Discussion

Most helpful comment

Personally, I would go with __MODULE__. While sometimes the module name is shorter, __MODULE__ has the guarantee of being easy to recognize and it always means the same thing, "the current module", regardless of the name.

All 10 comments

Personally, I would go with __MODULE__. While sometimes the module name is shorter, __MODULE__ has the guarantee of being easy to recognize and it always means the same thing, "the current module", regardless of the name.

I agree. Being consistent here does not sacrifice clarity.

I would also go with __MODULE__.

Besides, using the module name also opens the debate of using the fully qualified name:

@type t :: %MyApp.Context.MyModule{ ... }

or the module name + alias:

alias MyApp.Context.MyModule
# or alias __MODULE__ ?
@type t :: %MyModule{ ... }

I second what @whatyouhide said, using __MODULE__ also makes renaming easier.

Alright! @basdirks can you please send a PR that changes them all once? Sorry for the back and forth.

Will do. No problem 👍

8113 contains the proposed changes.

Looking at #8113, should __MODULE__ be also used when creating structs?

For example, in the Date module there is:

{:ok, %Date{year: year, month: month, day: day, calendar: calendar}}

and that could be written as:

{:ok, %__MODULE__{year: year, month: month, day: day, calendar: calendar}}

for the same reasons mentioned above:

  • guarantee of being easy to recognize and it always means the same thing, "the current module", regardless of the name
  • makes renaming easier.

However, in this case I prefer the %Date{} syntax 🤷‍♂️

Other option is to accept that we do not need to be "consistent" in this case, and both __MODULE__ and the module name can be used interchangeably.

I'd prefer to see us always use __MODULE__, it benefits from clarity of purpose, and leaves no debate about when it should or shouldn't be used, and most importantly, always using it makes things consistent, which is easier for people submitting PRs, as well as for the core team when reviewing them.

I agree. I left it out of the current PR because it leads to a different, broader discussion with more nuances.

Was this page helpful?
0 / 5 - 0 ratings