On Tue, Jul 11, 2023, at 5:28 PM, Robert Landers wrote: >> Real code I wrote a week ago (specifically, for a series of events in a >> domain model): >> >> https://gist.github.com/Crell/f5929e2ee44decd4e9353c41874f26c8 >> >> Two different interfaces, that I want to be able to check against, but their >> implementations are trivial. One of them is used in 2 classes, the other in >> 3. A base class simply wouldn't work, both because it's semantically >> incorrect (these events are not all "special cases of" some common >> definition, that's not the data model), and because then I couldn't have the >> class that uses only one of them. Traits, for now, are the best solution, >> and this is an approach that gets taken a lot. > > Ah, I see. I would have simply created an ErrorResponseCarrier class, > then had PreRouting and PostRouting extend them and implement whatever > other interfaces they needed. > > IMHO, using a shared base class reflects the inheritance better > because they are siblings (at least these appear to be logical > siblings out of context, IMHO) and should look like siblings in a > class diagram. Their current dis-jointed-ness strikes me as odd and > the usage of traits in this way strikes me as an anti-pattern. But I > came from a PHP world where traits were nearly forbidden or used very > sparingly.
Traits are a surgical tool with a narrow set of uses, and systems that over-use them cause problems. (You know which framework you are...) But this is one of their main valid uses. In context, the classes are not siblings, and it would be incorrect for them to extent from a base class. They just both happen to implement the same *interface*, but that the same as having the same "is a special case of" relationship with a base class. Having a common base class instead would, as noted before, mean as soon as I added a third "carries" option, I'd have to add four more base classes to cover all combinations. It quickly gets absurd, and those base classes have no valid type usage; they're purely there as an alternative to copy-paste. Using inheritance as an alternative to copy-paste is the wrong way(tm) to do it. Both inheritance and copy-paste. Freshman CS classes still love to talk about inheritance as a great thing for code reuse but... it's really not, and many of the 21st century languages have been drifting away from that. Traits/default-method-interfaces are a better alternative that doesn't conflate "copy-paste avoidance" with "is a special case of." Honestly, I almost never use class inheritance in my greenfield code these days. --Larry Garfield -- PHP Internals - PHP Runtime Development Mailing List To unsubscribe, visit: https://www.php.net/unsub.php