4
\$\begingroup\$

I have the following code:

 member this.ProcessEvent(sourceStream: OrderResponse) = 
 match sourceStream.Action with
 | Action.Partial
 | Action.Insert ->
 sourceStream.Data
 |> Seq.iter (fun x -> this.orderState.[x.OrderId] <- this.ConvertFullOrder x)
 | Action.Update ->
 sourceStream.Data
 |> Seq.iter (fun x -> this.orderState.[x.OrderId] <- this.UpdateOrder x this.orderState.[x.OrderId])
 | Action.Delete ->
 sourceStream.Data
 |> Seq.iter (fun x -> this.orderState.Remove(x.OrderId) |> ignore)
 | _ -> ()

It is processing a list of events and an action. The data is processed and stored in a dictionary. The action tells to insert, update or delete some of the records and applies to all the events received in the same message.

For each case, I iterate through the sourceStream.Data list.

Is there a better / more readable way where I can declare I am going to process that list and then, based on the Action, have different code? this would allow to remove the multiple sourceStream.Data |> bits and specify it only once.

200_success
146k22 gold badges190 silver badges479 bronze badges
asked Oct 29, 2019 at 21:25
\$\endgroup\$
2
  • 1
    \$\begingroup\$ Whoever VTCd this question, please explain. \$\endgroup\$ Commented Oct 30, 2019 at 12:40
  • 1
    \$\begingroup\$ I didn't VTC but my presumption is that it would be helpful to have sample usage of this function so reviewers can have a better sense of how it is utilized \$\endgroup\$ Commented Oct 30, 2019 at 16:47

1 Answer 1

1
\$\begingroup\$

You have probably found a good solution long time ago, but here is my suggestion:

member this.ProcessEvent(sourceStream: OrderResponse) = 
 let handler: (Order -> unit) = 
 match sourceStream.Action with
 | Action.Partial
 | Action.Insert -> (fun x -> this.orderState.[x.OrderId] <- this.ConvertFullOrder x)
 | Action.Update -> (fun x -> this.orderState.[x.OrderId] <- this.UpdateOrder x this.orderState.[x.OrderId])
 | Action.Delete -> (fun x -> this.orderState.Remove(x.OrderId) |> ignore)
 | _ -> (fun x -> ())
 sourceStream.Data |> Seq.iter handler

I'm not sure. what type x has, so for the illustration I just call it Order in the handler definition.

answered Jul 5, 2020 at 12:16
\$\endgroup\$
1
  • \$\begingroup\$ yes, by now I have a solution, but this is elegant, I like it. \$\endgroup\$ Commented Jul 5, 2020 at 16:26

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.