Using aliases for Fubar.Fubar named module?

I’m playing around with something like this:

defmodule Todo.User do
  defstruct name: nil
end

defmodule Todo.Todo do
  defstruct text: nil
  def complete(%Todo.Todo{} = todo, %Todo.User{} = completer), do: nil
end

Now, writing %Todo.Todo{} and %Todo.User{} is tedious. Especially if you have a lot of references to the types from a lot of functions. I would prefer %Todo{} and %User{}.

What is the best way of doing this? Is there any good reason not to look for a shorthand here?

I tried this:

defmodule Todo.Todo do
  alias Todo.User
  alias Todo.Todo
  defstruct text: nil
  def complete(%Todo{} = todo, %User{} = completer), do: nil
end

and it works, but now the order of the alias:es is important and I have to alias everything with the Todo prefix. Doesn’t feel right.

1 Like

The module aliases itself? Interesting. I’ve never seen that before. What’s more common is to use __MODULE__ as a compile time reference to the current module.

1 Like

I’ve seen that in GenServers, but how would that translate to this case?

defmodule Todo.Todo do
  alias Todo.User
  # alias Todo.Todo
  defstruct text: nil
  def complete(%__MODULE__{} = todo, %User{} = completer), do: nil
end

That just looks wierd to me. But I’m new to Elixir, perhaps my eyes haven’t adjusted yet :slight_smile:

1 Like

If the naming schema is confusing, I can’t think of a better option besides changing the name. Why not call it Todo.List for the whole list and Todo.ListItem or similar for every element?

1 Like

So in general, avoid using the same name fragments for different parts of the module name?

1 Like

If you want to alias them, then surely. Otherwise you will run into the conflicts you described.

3 Likes