Transformation traits and single use structs

I'm not sure if it's the right terminology, but there are certain traits that are designed for transforming types. For example, From, FromStr or Actix's Responder. (This last one being what's prompted the question in the first place)

In many cases, these get implemented because that transformation is done in many places, so it's avoiding repetition.

However, in some cases the this will only be done once. Converting an internal struct into one returned from a REST API, for example.

Obviously I can just do the transformation in place where it's needed. But I could also do it via the appropriate trait, which feels like a bit more code to manage but also a lot easier to unit test - the transformation can be tested on it's own in as many varieties as needed without anything else.

Is this implementation of such a trait for a single use a reasonable/common style? Or is it more trouble than its worth?


If you feel the code is simplified by putting the conversion in a From impl, then you should do so. Otherwise don't.

It feels like it's probably more testable that way. I'm just curious if it's a common pattern or if I'm likely to be making more work for myself with little benefit. When you're still new to a language it's hard to know what's sensible and what's crazy :slight_smile:

It is, in general and in all languages, good practice to factor out code into a separate function, if it is sufficiently complex such that the function call increases the code's readability. I'm assuming it is a rather complex conversion, since you feel the need to test it.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.