HamHamJ
HamHamJ

Reputation: 425

Proper way to handle OnClick event handlers that do basically the same thing?

Let's say I have a button that does something, and it's OnClick event handler is foo. then I have another button, with event handler bar, that sets some additional values and then does the same thing as foo. foo doesn't actually use any of it's arguments. What is the proper way to handle this?

Option 1:

protected void foo(object sender, EventArgs e) {
//does stuff
}

protected void bar(object sender, EventArgs e) 
{
//does stuff
foo(null, null);
}

Calling foo with those nulls seems bad to me. Is it?

Option 2:

protected void foo(object sender, EventArgs e) 
{
func();
}
protected void bar(object sender, EventArgs e) 
{
//does stuff
func();
}

Having foo be nothing but a call to another function seems needlessly verbose though. This is clearer semantically though.

Not giving foo arguments doesn't seem to be an option, giving a compiler error.

Is there a better option I'm missing?

Upvotes: 0

Views: 108

Answers (2)

alstonp
alstonp

Reputation: 700

When calling events that require no arguments consider using:

foo(this, EventArgs.Empty);

As Per the EventArgs msdn description

To pass an object that does not contain any data, use the Empty field.

By convention event handlers should always include some sender and an EventArgs object.

Upvotes: 0

andreas
andreas

Reputation: 505

I think you have to go with one of the two options you listed.

I don't think it is bad to be a bit verbose sometimes and option two gives you a couple of small advantages.

  • You will never have to do conditional checks to see if the parameters in foo are null.
  • If more logic is added later, the code is already separated nicely making it easier just to add it to the correct place. (Like adding extra logic in the beginning of foo)

Upvotes: 1

Related Questions