2

I've run into a common annoyance where I'll have an event that sends a parameter, but some consumers of the event don't need the parameter at all. So I wrap it in another function that decouples the signature from the actual method call. This adds one more level of thought that a reader needs to parse before understanding the code.

void OnEnable() {
    HeightSnapEvents.OnSnapToHeight += PictureMightHaveMoved; //event has float parameter
}

void PictureMightHaveMoved(float height) {
    AlignWithPictureTaking(); //don't need height at all.
}

void AlignWithPictureTaking() {
    Debug.Log("Aligned!");
}

I've also tried:

void PictureMightHaveMoved(float unused) {
    Debug.Log("Aligned!");
}

I've also considered having the event also call a parameter-less version of itself, but then it adds complexity making sure all the events are fired properly.

Is there a more elegant solution that keeps readability?

Details: I'm programming in c# and Unity, but this shouldn't really matter.

1
  • Why is a consumer getting extra information they don't need a problem? Why can't the consumer just ignore the extra detail? – JimmyJames Mar 9 '20 at 19:16
2

For events you should follow the .NET convention. This makes it easy on implementers, users and automated tools alike.

The convention dictates the following signature:

void SomethingHappened(object sender, EventArgs args)

The sender object is always the object that raises the event. You may use a custom event type but you must descend from EventArgs.

For naming the handlers you use either a passed tense like in the example above for an event that occurs just after the fact or the ing form for events that occur just before the fact.

Stick with this and everybody will be happy. Do not lose any sleep over the possibility that some clients may not be interested in the event arguments, you cannot possibly know what your potential clients may be interested in or not and you should not care. Just make sure you provide them with anything they MAY be interested in.

1
  • Hmmm this does’t exactly answer the question, but is probably the correct course of action. I’ll make is as solved. – Adam B Mar 10 '20 at 23:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.