2016-11-30 35 views
1

在工作中,我遇到了一些看起来不够优雅的代码,编译器抱怨我们有未使用的变量。我想知道处理这个案件的惯用方式是什么。elixir中的模式匹配返回值地图

defp parse_create_case_response({create_status, http_status, body}) do 
    case {create_status, http_status} do 
     {:ok, 201} -> 
      %{"errors" => errors, "id" => id, "success" => success} = Poison.decode! body 
     _other -> 
      {:error, %{message: "Internal error", error_code: :internal_server_error}} 
    end 
end 

编译器抱怨说errorsiderror都不用的。我明白他们为什么没有被使用,但我想知道我应该如何处理这个问题。我应该在每个变量的前面放一个_来告诉编译器它们没有被使用吗?或者完全做其他事情?

代码审查中还会解决其他的代码问题,我只是想知道我应该如何帮助我的同事克服这个问题。

回答

3

从它的外观来看,我假设你将这个函数的结果与另一个函数中的变量相匹配。编译器告诉你,他们正在被闲置,应该是一个很好的暗示,也许整个方法可以被重构。没有看到调用代码很难,但我可能会将匹配移动到调用函数,并返回解析的响应主体。

这将使短绒快乐:)

所以这个:

defp parse_create_case_response({create_status, http_status, body}) do 
    case {create_status, http_status} do 
     {:ok, 201} -> 
      %{"errors" => errors, "id" => id, "success" => success} = Poison.decode! body 
     _other -> 
      {:error, %{message: "Internal error", error_code: :internal_server_error}} 
    end 
end 

将具有此相同的效果:

defp parse_create_case_response({{:ok}, {201}, _body}) do 
    Poison.decode! body 
    end 

    defp parse_create_case_response(_response) do 
    {:error, %{message: "Internal error", error_code: :internal_server_error}} 
    end 

我们不需要图案的原因第二个匹配是因为如果它不能匹配第一个函数头,那么我们真的不在乎结果是什么,因为我们知道我们必须返回什么。

无论其 如果您在返回地图上坚定,那么你可以将其更改为到:

defp parse_create_case_response({{:ok, {201}, body}) do 
    body 
    |> Poison.decode! 
    |> generate_map 
    end 

    defp parse_create_case_response(_response) do 
    {:error, %{message: "Internal error", error_code: :internal_server_error}} 
    end 


    defp generate_map(%{"errors" => errors, "id" => id, "success" => success}) do 
    %{"errors" => errors, "id" => id, "success" => success} 
    end 

这并不漂亮,但它仍然是相当清楚发生了什么事情。再次不知道这种方法的背景是什么,很难做得更好。