Skip to main content

Anonymous Classes vs Delegates !!!

I am not a java programmer. By that, I do not mean I am against Java. As a programmer by profession and passion, I try to learn things along the way. That includes a little of bit of Java. I should say that my proper encounter, so to say, with Java is a simple application that I am trying out with Android. There might be some hard core differences and/or limitations in the Android version of Java. But I am almost certain that I am using only primary level features of Java.

In android, there is this OnClickListener interface, which is used as a callback interface for a button click. So, it is used something like this:-

// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
    public void onClick(View v) {
        // do something when the button is clicked
    }
};

protected void onCreate(Bundle bundle) {
    ...

    Button button = (Button)findViewById(R.id.someButton);
    button.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
        // Click handler action code...
        }
    });
    ...
}

OnClickListener, which is an interface with a single method onClick, represents a type for the button click event. The highlighted portion of the code that registers an event handler for the button click action is called an Anonymous Class definition. That is some really some clever syntax; although it seems a wrong tool for our purpose here. Actually the click event requires only a method to call when the button is clicked. Nothing more. So why do we need an interface here?

I know of a better way in C#. Back there, it is called a delegate. In simple words, a delegate is an object-oriented pointer to a function, and it could point to any public\private instance\static function of any class. So a delegate is a good fit for our situation here. If the highlighted portion of the code (event registration) were to be written in C#:-

button.setOnClickListener(delegate(View v) {
    // Click handler action code....
});

I have gone one step further and used an anonymous delegate, which is even more succinct. Sometimes, less syntactic noise is a good feeling for a programmer. I am not doing a language war here. I am just trying to vote for delegates in Java. I am not sure if they are already there in one of the latest versions.

But there is a C# fanatic inside of me, which compels me to show the world how better and good-looking (see pascal casing) C# code actually is.

protected void OnCreate(Bundle bundle)
{
    var button = FindViewById<Button>(R.Id.SomeButton);
     button.Click += delegate(View v) {
        // Click handler code.
    };
}

Beauty lies in the eyes of the beholder!

Nevertheless, anonymous class is definitely a wonderful and powerful syntax, but does not look good in the example above.

Comments

Carsten said…
It's always better imho to have all listeners in one place. So instead of creating a separate listener for each thing (Button.setOnClickListener, Button.setOnMoveListener), my API would rather contain one big listener ButtonListener with all the Button related methods required: onClick, onMove, etc. in one place. Unneeded listeners in the base class would be just empty bodies you're are free to ignore or override. This way we have to write much less code than in C# and overall it looks less spagetthi unlike C#. Java's approach is inherently better. Microsoft's JVM introduced delegates just to make their JVM incomptible with Sun's JVM, in the context of their "embrace extend extinguish" strategy, and when they were hurriedly baking C# 1.0 as a reincarnation of J++ (i.e. basically a Java clone), they added the delegates without much thought. Of course now in C# they're needed because standard library was deliberately badly designed to support delegates, but otherwise delegates are simply a fancy historical leftover.

Popular posts from this blog

Implementing COM OutOfProc Servers in C# .NET !!!

Had to implement our COM OOP Server project in .NET, and I found this solution from the internet after a great deal of search, but unfortunately the whole idea was ruled out, and we wrapped it as a .NET assembly. This is worth knowing. Step 1: Implement IClassFactory in a class in .NET. Use the following definition for IClassFactory. namespace COM { static class Guids { public const string IClassFactory = "00000001-0000-0000-C000-000000000046"; public const string IUnknown = "00000000-0000-0000-C000-000000000046"; } /// /// IClassFactory declaration /// [ComImport(), InterfaceType(ComInterfaceType.InterfaceIsIUnknown), Guid(COM.Guids.IClassFactory)] internal interface IClassFactory { [PreserveSig] int CreateInstance(IntPtr pUnkOuter, ref Guid riid, out IntPtr ppvObject); [PreserveSig] int LockServer(bool fLock); } } Step 2: [DllImport("ole32.dll")] private static extern int CoR

Extension Methods - A Polished C++ Feature !!!

Extension Method is an excellent feature in C# 3.0. It is a mechanism by which new methods can be exposed from an existing type (interface or class) without directly adding the method to the type. Why do we need extension methods anyway ? Ok, that is the big story of lamba and LINQ. But from a conceptual standpoint, the extension methods establish a mechanism to extend the public interface of a type. The compiler is smart enough to make the method a part of the public interface of the type. Yeah, that is what it does, and the intellisense is very cool in making us believe that. It is cleaner and easier (for the library developers and for us programmers even) to add extra functionality (methods) not provided in the type. That is the intent. And we know that was exercised extravagantly in LINQ. The IEnumerable was extended with a whole lot set of methods to aid the LINQ design. Remember the Where, Select etc methods on IEnumerable. An example code snippet is worth a thousand

sizeof vs Marshal.SizeOf !!!

There are two facilities in C# to determine the size of a type - sizeof operator and Marshal.SizeOf method. Let me discuss what they offer and how they differ. Pardon me if I happen to ramble a bit. Before we settle the difference between sizeof and Marshal.SizeOf , let us discuss why would we want to compute the size of a variable or type. Other than academic, one typical reason to know the size of a type (in a production code) would be allocate memory for an array of items; typically done while using malloc . Unlike in C++ (or unmanaged world), computing the size of a type definitely has no such use in C# (managed world). Within the managed application, size does not matter; since there are types provided by the CLR for creating\managing fixed size and variable size (typed) arrays. And as per MSDN, the size cannot be computed accurately. Does that mean we don't need to compute the size of a type at all when working in the CLR world? Obviously no, else I would