Constructor parameter naming for clarity with passing in anonymous methods

340 views Asked by At

I'm interested in the readability of my code when passing anonymous methods into delegate parameters:

                var touchListener = new TouchListener(
                down:(v, e) => 
                {
                    //Handle the down event
                },
                up:(v, e) =>
                {
                   //Handle the up event
                });

As you can see I have named the parameters down and up, so that it is more obvious what these anonymous methods are doing.

Here is the TouchListener class for clarity (it is working against MonoDroid, but that isn't important here):

    public class TouchListener : View.IOnTouchListener
{
    public delegate void OnTouchAction(View v, MotionEvent e);

    private OnTouchAction down;
    private OnTouchAction up;

    public TouchListener(OnTouchAction down, OnTouchAction up)
    {
        this.down = down;
        this.up = up;
    }

    public bool OnTouch(View v, MotionEvent e)
    {
        switch (e.Action)
        {
            case MotionEventActions.Down:
                this.down(v,e);

                break;
            case MotionEventActions.Up:
                this.up(v,e);

                break;
            default:
                break;
        }

        return true;
    }
}

Perhaps my approach is wrong, and I am overusing anonymous methods? However it is saving a lot of code.

1

There are 1 answers

3
Jan Jongboom On BEST ANSWER

From a Javascript / jQuery perspective, this is pretty clear code; even without the named parameters. Tossing anonymous functions around is just the way events are handled.

However, from a C# perspective it's pretty unclear. (Almost?) none of the .NET library uses anonymous functions for event-handling. So save yourself the hassle and just use real events for this.

var touchListener = new TouchListener();
touchListener.OnTouchDown += (v,e) => Console.WriteLine("Hehe, I said touchdown");
touchListener.OnTouchUp += (v,e) => Console.WriteLine("Mweh");