Reputation: 23214
Coming from an OOP background, I've got some issues with the concept of immutable objects/records/messages in functional programming.
Lets say I pass an PurchaseOrder record through a pipeline of functions where each function is supposed to add or update data in this record.
When dealing with mutable state, I would simply set some specific properties of the message beeing passed around.
When dealing immutable records, are there some design tricks making things easier on this matter? Copying every single field in order to change just one field is just a pain.
{ A = x.A ; B = x.B ; C = x.C ; D = x.D ; E = somethingnew; }
I guess grouping data as much as possible is a good way to deal with it, thus avoiding to copy all fields. Are there any other ways or design guidelines for this?
Upvotes: 2
Views: 141
Reputation: 2400
I'm from an extremely pure and extremist OOP background, and my OOP designs tend to be 99% immutable objects (Even in languages which allow mutation). If you have a pipeline of functions where each function is supposed to add or update data in a record, in my experience, each function will deal with a subproblem and subconcept of that record, so you should create a class/type/whatever for each of those to follow OOP best practices like SRP, SoC. If any class/record/type has more than 4 or 5 fields/variables/attributes I think you are probably putting too much responsibility there. If you split the problem into several subproblems, each function of your pipline will create a sub record of the record, and the main function will just combine them all to create the main record. In my experience following traditional OOP drives you to a design that will allow you to achive what you want to achive without any mutation.
Upvotes: 0
Reputation: 25516
You can just do
let myRecord3 = { myRecord2 with Y = 100; Z = 2 }
(example from the MSDN records page - http://msdn.microsoft.com/en-us/library/dd233184.aspx)
Upvotes: 9