Structuring code, question

Say, I have this:

    a1 = where(Model, [x], x.user_id == ^user.id)
    |> first()
    |> Repo.one()

or this:

      a2 =
        if Map.has_key?(params, "key1") do
          case Repo.get_by(Model1, key1: params["key1"]) do
            nil -> {:error, %{code: 404, message: "noooooo"}}
            x -> x.id
          end
        else
          if Map.has_key?(params, "key2") do
            params["key2"]
          else
            {:error, %{code: 422, message: "key2 isn't specified"}}
          end
        end

what’s the most common and de-facto convention to align such code?

Primarily I mean, should the code, by thge most convention, after "a1 = " and "a2 = " remain on the same line or new one?

Hello and welcome,

If You use mix format, You will get this result…

a1 =
  where(Model, [x], x.user_id == ^user.id)
  |> first()
  |> Repo.one()

a2 =
  if Map.has_key?(params, "key1") do
    case Repo.get_by(Model1, key1: params["key1"]) do
      nil -> {:error, %{code: 404, message: "noooooo"}}
      x -> x.id
    end
  else
    if Map.has_key?(params, "key2") do
      params["key2"]
    else
      {:error, %{code: 422, message: "key2 isn't specified"}}
    end
  end

See https://hexdocs.pm/mix/master/Mix.Tasks.Format.html

It is simple to just trust the formatter :slight_smile:

BTW If You use credo, it will probably warn You about not starting a pipeline with a value…

a1 =
  Model
  |> where([x], x.user_id == ^user.id)
  |> first()
  |> Repo.one()
2 Likes