Skip to content

Instantly share code, notes, and snippets.

@jbrains
Created December 6, 2017 10:35
Show Gist options
  • Save jbrains/ed48d2b9f41a11be44af0753785bc54d to your computer and use it in GitHub Desktop.
Save jbrains/ed48d2b9f41a11be44af0753785bc54d to your computer and use it in GitHub Desktop.
Which, in your opinion, is "better"?
-- This version returns a constructor for a PlayerModel, needing only a "name"
playerNeedingName : Maybe PlayerModel -> List PlayerModel -> (String -> PlayerModel)
playerNeedingName selectedPlayer players =
selectedPlayer
|> Maybe.map withName
|> Maybe.withDefault (nextPlayerModel players)
-- This version returns either the existing player or the new player ID,
-- requiring the client to create the PlayerModel "from scratch"
playerNeedingNameNewVersion : Maybe PlayerModel -> List PlayerModel -> Either PlayerId PlayerModel
playerNeedingNameNewVersion selectedPlayer players =
selectedPlayer |> Either.rightFromMaybe (nextNumericId (List.map .id players))
@jbrains
Copy link
Author

jbrains commented Dec 6, 2017

I need to do create-or-find for a PlayerModel in a List PlayerModel. Nothing should map to "new player" and Just player should map to the matching player in the list.

A PlayerModel has an ID and a name.

Which version of the function do you prefer and why? Upon what does it depend?

@Morendil
Copy link

Morendil commented Dec 6, 2017

I like the first version better, absent more context. The main reason is that in the first version, other than the familiar Maybe stuff, the other names seem obviously related to the domain in straightforward ways. In the second version, the use of nextNumericId feels like dropping down half a layer of abstraction, and I'm less sure whether Either makes sense; it feels as if a player ID and a player aren't on the same plane and stuffing both of them in a sum type might work against the grain. Either is less familiar to me than Maybe though.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment