Lets say I have a function which takes some input structure and returns some output structure (which may be related to but different to the input structure).
I don't want to enforce these input/output structures to a particular type, I just want to ensure they have a few behaviors that I need.
Should I?
a) Define a class which has the appropriate extraction methods and force the input data to be an instance of that class? OR
b) Have the function accept another parameter which is function(s) that define how one extracts data.
Also I have the same question for the output structures (except this time the required functionality is mutation)?
Whenever you have to choose between explicit function arguments and type classes you should ask yourself this most important question: Are the functions specific to the type or to the application? An example of the former is sort
, and an example of the latter is map
.
Passing functions is always more flexible, but it may be overkill for your situation and cause unnecessary code bloat. Type classes on the other hand result in much smaller code, but they are also less flexible.
Without further information it's not possible to give a more precise answer here.
It depends.
The advantage of a type class is that you don't have to explicitly pass around the functions to any helper functions. So, if you have more than two functions or if you're expecting a lot of functions to work with the same basic transformation functions, a type class is probably better.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With