1

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.

Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
Ross Scott
  • 1,690
  • 9
  • 16
  • 1
    is there a specific question? – Marc Gravell Feb 22 '11 at 12:30
  • Sorry, yes. Have I got myself into some kind of Pattern that doesn't promote the readability of the code? I'm not a fan of naming parameters usually, but it seemed that it would help the readability in this case, do you think this is correct? – Ross Scott Feb 22 '11 at 12:35

1 Answers1

3

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");
Jan Jongboom
  • 26,598
  • 9
  • 83
  • 120