Frage

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.

War es hilfreich?

Lösung

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
scroll top