Function body is nested too deep

I have a case statement that is failing in credo. Giving me this error

“Function body is nested too deep” I know we can use “with” here but I’m failing to use it correctly

  case NaiveDateTime.from_iso8601(valid_time) do
      {:ok, datetime} ->
        case Somefunction(which give me true or false) do
          true -> true
          false -> false
        end

      {:error, _} ->
        "datetime is not valid"
    end

Guide me

learn to use with correctly

2 Likes

As you are mapping the return value of the function to itself, you can just avoid the inner case:


case NaiveDateTime.from_iso8601(valid_time) do
  {:ok, datetime} ->
    Somefunction(which give me true or false)

  {:error, _} ->
    "datetime is not valid"
end

In this case, I don’t think that with would help (but it might, depending on the code outside the outer case statement, which we don’t see).

5 Likes

In this particular case, @lucaong already provided the best suggestion. In general, we usually introduce a private function with several clauses in such a case.

valid_time
|> NaiveDateTime.from_iso8601()
|> do_validate_instead_of_case()

[...]

defp do_validate_instead_of_case({:ok, datetime}) do
  case Somefunction(which give me true or false) do
    ...
  end
end

defp do_validate_instead_of_case({:error, _}),
  do: "datetime is not valid"
3 Likes

Thanks :).

1 Like