forcecraft / aion

An e-learning platform written in Elixir and Elm based on real-time gameplay
6 stars 0 forks source link

enhancement(elm): Handle raw values in Update #177

Closed mrapacz closed 6 years ago

mrapacz commented 6 years ago

Type

Enhancement

Current behaviour We could DRY out our code easily. Right now we are following this pattern:

  1. Whenever there's a new message incoming we are passing it to update
  2. In pattern matching clause we have to match on the decoder's result, which is either
    Ok value -> doActualStuff

    or

    Err error -> model ! []

Expected behaviour We could get rid of this pattern matching on the result and introduce a function that would handle this stuff for us. It would work like this:

withUnpackRaw :
    Decode.Value
    -> Decode.Decoder a
    -> Model
    -> (a -> ( Model, Cmd msg ))
    -> ( Model, Cmd msg )
withUnpackRaw raw decoder model fun =
    case Decode.decodeValue decoder raw of
        Ok value ->
            fun value

        Err error ->
            model ! []

the final usage would look like the following:

        ReceiveUserList raw ->
            withUnpackRaw raw
                userListMessageDecoder
                model
                (\userListMessage ->
                    { model | userList = userListMessage.users } ! []
                )

instead of the current version:

        ReceiveUserList raw ->
            case Decode.decodeValue userListMessageDecoder raw of
                Ok userListMessage ->
                    { model | userList = userListMessage.users } ! []

                Err error ->
                    model ! []

The anonymous function of course could be an actual function. We could pass something like updateUserListMessage here and store the actual implementation in a separate file (thus making our Update shorter!)

Motivation / use case DRYing out the code

@pmrukot @jtkpiotr I'm waiting for your opinions on that. If I get a blessing on that I can replace the unpacking and post a PR with that.

pmrukot commented 6 years ago

Very nice idea, Im all for it. I would give it a little more descriptive name because its unpacking only decoders-like updates (right?).

mrapacz commented 6 years ago

@pmrukot Exactly, the flow is use the decoder and then run the function over extracted value. Do you have any suggestions on better naming?

Maybe decodeAndUpdate? I guess we should store this thing in the Update.elm anyway as that's what it does in the end.

pmrukot commented 6 years ago

Works for me