So, let's say I have two classes: class A and class B. They both have to perform a common operation, but it would be pointless to get both of them from the same object, so instead we go with the composition. Basically, "makes sense" where "no."
Now each of the two classes creates an instance of this object and uses it to perform a common operation, and all this is good. Now everything is all right.
The problem arises when each of these two classes must expose an event that the general procedure should raise. Oh oh Now what?
Well, we could do something similar in each of the two classes:
public event EventHandler CommonEvent { add { theCommonObject.CommonEvent += value; } remove { theCommonObject.CommonEvent -= value; } }
But now this code needs to be duplicated in each of the two classes, and code readers may be somewhat confused by this code. add and remove , at least not often found keywords.
However, there is duplicate code in both of these two classes, and not only that, but this solution will not always work!
For example, what if theCommonObject locally created in one method and its scope is only inside one method.
Well, then in this case we cannot even use the quick access code published earlier, and we must completely duplicate the code in both classes. Not only that, but simply shouting inefficiency, because we basically just revise a copy of the event for customers.
Example code that should be duplicated in each class in this case:
public event EventHandler SomeCommonEvent; private void SomeMethod() { theCommonObject = new theCommonObject(); theCommonObject.DoSomething(); theCommonObject.SomeCommonEvent += thisClass_SomeCommonEvent; } private void thisClass_SomeCommonEvent(object sender, EventArgs e) { var handler = SomeCommonEvent; if (handler != null) { handler(this, e); } }
As you can see, there is duplicated code in both cases, but even more in the second, because the object is local to the method, and not to the member variable.
I can’t think about it other than using inheritance, but I don’t think it makes sense in a semantic sense, and many often argue that composition surpasses inheritance in terms of complexity - reduction, understanding, etc.