- Home /
Parametrize generic event system (DRY it)
Hey guys, been checking out some messaging systems lately. I came across the CSharpMessengerExtended - Kinda nice, but not very DRY - very repetitive, lot's of copy-pasting.
See my question here, as nobody seems to have answered it.
(Nice sad humor in the comments as well =))
Thanks for any help.
Answer by ArkaneX · Nov 07, 2013 at 11:35 PM
I don't have any quick idea how to solve your problem the way you'd like it, but maybe an option is to always send data using a class derived from some base class? Just like in standard .NET event system, where EventArgs (or derived class) is used.
If you want to use a message with no parameters, then you just use EventArgs.Empty (or eventually pass null). If you want any parameters, then create a class derived from EventArgs with a properties of your desired types.
This method requires creating new classes, but in my opinion this is much better than having unnamed generic parameters. With such generic parameters, browsing through code after a few weeks will be more painful, as you'll scratch your head trying to find out what the hell this int, long and string actually mean. Dedicated class with properties having descriptive names is a much better option. That's why I never use classes from Tuple family (not supported in Unity yet).
Thanks for your answer. This is what I actually ended up doing. As I found this system here - just as what you describe.
One thing I don't quite like about it, is the fact that you have to new up stuff, each time an event fires. Imagine someone subscribing to a OnBulletFire
where the bullets are co$$anonymous$$g out of a $$anonymous$$igun - at a very high rate.... newnewnewnewnewn.....
But it is a lot better, than generics. Because:
it's a lot more object-oriented
it follows the rules (the O in SOLID - the open for extension, and close for modification principle). So if you want to add a new event you just create one, extending what you have, while if you wanted to add another generic arg, you'd have to modify the source.
The main problem with generic args, is that you never know the users needs, what if they wanted 5 args, 10 args? you never know - which leads you to considering the worst case, and making a silly amount of overloads, like 16 (just like the
Action
andFunc
) - then you'd fall intoYAGNI
(ya ain't gonna need it) - andDRY
(don't repeat yourself) by copying and pasting... so not very clean.
Speaking of solving the original problem, I don't think there is a way - if there was, there wouldn't be 16 overloads to Func
and Action
.
Your answer
Follow this Question
Related Questions
C# event setup, no result 0 Answers
Sharing delegate types across scripts 1 Answer
Multiple Cars not working 1 Answer
Distribute terrain in zones 3 Answers
Event to change level 1 Answer