So, I have this issue of how to correctly structure some of the types in my code and I was hoping for a suggestion. A brief description of the problem goes like this:
I have multiple objects which have a lot (if not all) fields which are common
Each object, however, needs to have the behaviour of a different method
When executing various methods any modifications to the common fields are exactly the same across all objects.
So the first two suggest that I should use a trait. However, because of 3, in order not to replicate code, I made a common class, which has as fields the base and a Box. However, I'm not too confident this is a good choice and if there is a better one. Below I provide a short snippet of a simplified version of what I have so far (a playground link - Rust Playground)
Thanks. I think this indeed is the second possible approach. Can't say which one is better either way but thanks for sharing I will need to consider it
Can you say a bit more about how these types would be used? And what are you optimizing for? Readability? Conciseness? Performance? Extensibility? Something else? In other words, what’s the criteria for “better”?
This is a less flexible form, but avoids generics, traits, and boxes. Any closure that doesn’t capture its environment can be coerced to this fn pointer, so you don’t necessarily need pre-baked functions.
Another design option is to use enums; this might work well if you have a closed set of variants that you control. That would obviate the need for boxes as well.
Ok so to give context - I'm trying to migrate ccxt to Rust. The Base class is essentially what they have for an AbstractExchange. The trait API defines what all crypto exchanges must abide in order to be able to fetch relevant data. And the Object is just a convenience for being able to have multiple exchanges in the same type. I do want to add at some point the async calls such that I can fetch multiple exchanges simultaneously, but the main target, for now, is not raw speed, but more readability and conciseness (since usually, the APIs are quite slow you literally can't get too much more out of that bottleneck). I'm thnking how to structure this properly so that it is easy to use and maintain.
Closures are also possible, but I do need to go through all of the Exchanges implemented there to make sure no exchange does not have their own adhoc internal state that needs to be maintained.