2016-11-30 50 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 

這並不漂亮,但它仍然是相當清楚發生了什麼事情。再次不知道這種方法的背景是什麼,很難做得更好。