Do you consider trait-to-extend as a anti-pattern #357
Replies: 2 comments
-
Well, an "extension trait" is the most sane solution to extend foreign structs (e.g. ones from another crate that you have no control over) that I' aware of. So in this case I wouldn't consider this an anti-pattern. For types in the same crate, it surely is questionable why you'd provide functionality for one specific type via a trait, imo. Of course, if you can, in principle, implement the trait to other types in a sensible way it's a whole different story. And this may include cases where the functionality is, in principle, still pinned on some struct. For example, I'm currently working on a little thingy where I want to support accessing some |
Beta Was this translation helpful? Give feedback.
-
If we think it is preferred solution, will it make sense to add to "pattern" section? |
Beta Was this translation helpful? Give feedback.
-
Trait-to-extend ( I don't know what else could I name it )
I am presenting my opinion for another anti-pattern. While I have treated this as anti-pattern some of my friend says it might be pattern instead. So depending upon the discussion we might add it to (anti-)pattern section
Creating a new trait to extend external struct functionality
The pattern
Suppose this is the content of struct
Time
in any external crate:And we are using this crate. Suppose now we start to use this
Style
struct. Now in this application we need to only create Dark style i.e{fg: White. bg: Black}
and Light style i.e{ fg: Black, bg: White }
. What I previoudly did and some of my colleges still do is something like:I Consider this as anti-pattern. What I prefer a better idea for such case is to:
Here the main idea is: there is not a method we want in external struct, since we can't extend external item create a new local trait with desired method and implement it to external item.
What do you think of this? And also if maintainers are willing to add this (anti-)pattern, I would be glad to take responsibility to write this
Beta Was this translation helpful? Give feedback.
All reactions