Checking and assigning a value within cond

I have code like this:

    {rating_check_passed, rating_check_msg} =
      LobbyPolicy.check_rating_to_play(user.id, state)

    cond do
      not rating_check_passed ->

Is there a way to move the calling of the function check_rating_to_play inside the cond itself?

I tried this:

    cond do
      LobbyPolicy.check_rating_to_play(user.id, state) == {false, rating_check_msg} ->
      #I need to do something with rating_check_msg here

but that doesn’t work. The benefit of calling the function within the cond is that if I had some other checks within the cond that satisfy first the function doesn’t get called.

In these cases I usually prefer use case do:

case LobbyPolicy.check_rating_to_play(user.id, state) do
  {true, _msg} -> # ...
  {false, msg} -> # ...
end

Looks like code that can be further broken apart. If you show some more code we’ll help you but as @emadb said, case can be applied here. Or different variants of pattern-matching function heads.

If it helps for me to show more code, here’s what I have originally:

    {rating_check_passed, rating_check_msg} =
      LobbyPolicy.check_rating_to_play(user.id, state)

    {rank_check_passed, rank_check_msg} = LobbyPolicy.check_rank_to_play(user, state)

    cond do
      not rating_check_passed ->
        # Send message
        msg = rating_check_msg
        CacheUser.send_direct_message(get_coordinator_userid(), userid, msg)
        false

      not rank_check_passed ->
        # Send message
        msg = rank_check_msg
        CacheUser.send_direct_message(get_coordinator_userid(), userid, msg)
        false

      #some more stuff here

      true ->
        true
    end

Basically
LobbyPolicy.check_rating_to_play
LobbyPolicy.check_rank_to_play

are always called. But in theory it would be more efficient if it checks one, then if that passes call the other to see if that passes.

Now that sounds like a job for with.

2 Likes