{"id":2523,"date":"2017-02-14T20:34:23","date_gmt":"2017-02-14T08:34:23","guid":{"rendered":"https:\/\/www.deltics.co.nz\/blog\/?p=2523"},"modified":"2017-02-18T11:04:12","modified_gmt":"2017-02-17T23:04:12","slug":"anonymous-classes-dynamic-objects","status":"publish","type":"post","link":"https:\/\/www.deltics.co.nz\/blog\/posts\/2523\/","title":{"rendered":"Anonymous Classes: Anonymous POCO&#8217;s"},"content":{"rendered":"<span class=\"rt-reading-time\" style=\"display: block;\"><span class=\"rt-label rt-prefix\">[Estimated Reading Time: <\/span> <span class=\"rt-time\">5<\/span> <span class=\"rt-label rt-postfix\">minutes]<\/span><\/span><p>There is another use case for anonymous classes, even simpler than that of providing implementations of interfaces:  Anonymous POCO&#8217;s.<\/p>\n<p><!--more--><\/p>\n<p>We&#8217;re all familiar with the idea of declaring a class that identifies the members that all instances (objects) of that class have, and then creating instances of that class.  Anonymous classes, as the name suggests, allows us to instead define the members of a class at the very moment that we instantiate the class.<\/p>\n<p>In this case, the class is not identifiable by any name given it in the code.<\/p>\n<p>A simple example might be drawn from C#\/.net, when configuring a route in an ASP.NET MVC application:<\/p>\n<pre class=\"brush: csharp; title: ; notranslate\" title=\"\">\r\n\r\n   routes.MapRoute\r\n   (\r\n      &quot;Default&quot;,\r\n      &quot;{controller}\/{action}\/{id}&quot;,\r\n      new\r\n      { \r\n         controller = &quot;Home&quot;, \r\n         action     = &quot;Index&quot;, \r\n         id         = &quot;&quot;\r\n      }\r\n   );\r\n\r\n<\/pre>\n<p>The formatting here is to keep everything easily in view in the source code presentation of the blog template and to draw attention to what is going on rather than indicate any preferred style.<\/p>\n<p>The first two parameters in the call to <strong>MapRoute<\/strong> are clearly strings.  But the third is rather strange.  We have the <strong>new<\/strong> keyword but instead of being followed by a class identifier we then have what appears to be a <em>statement block<\/em> consisting of assignment statements separated by commas rather than statement terminators.<\/p>\n<p>This is an example of an object instantiated in-place (or in-line if you prefer) but without reference to any identifiable class name.  Hence &#8220;anonymous class&#8221; (though it isn&#8217;t really anonymous as we shall see).<\/p>\n<p>There is nothing exotic about the parameter passing mechanism itself.  The parameter to <strong>MapRoute<\/strong> involved is declared simply as <strong>object<\/strong> and so any object is legitimate, even one which is an instance of an anonymous class.<\/p>\n<p>The specific anonymous class instantiated here in the C# will have three properties, <strong>controller<\/strong>, <strong>action <\/strong>and <strong>id<\/strong>, with the values as initialised.  But we could have identified and initialized whatever member names we needed, to correspond to the values identified in the second parameter.<\/p>\n<h2> What&#8217;s the Point ? <\/h2>\n<p>For those not familiar with this Api, allow me to explain.  Others can skip ahead to the <strong>Oxygene Approach<\/strong>, if you prefer.<\/p>\n<p>The third parameter to the <strong>MapRoute<\/strong> call is an object that provides default values for the variable or templated components of the url provided in the <em>second<\/em> parameter (the variables are those parts of the url enclosed in { braces }).  The names of the members in the object correspond to those url variables.<\/p>\n<p>To match the properties of the default object to these named url variables the <strong>MapRoute<\/strong> method will (I presume) use reflection to discover the properties of the object, matching them up to those url values as required, by name.<\/p>\n<p>Of course, a url template in an application may consist of any number of parts, and each application will have different names for those parts, so the <strong>MapRoutes<\/strong> Api cannot dictate a specific class with prescribed value names to be passed.<\/p>\n<p>In this case the designers of the <strong>MapRoute<\/strong> Api could perhaps have used a <strong>dictionary&lt;string, string&gt;<\/strong> but anonymous classes are far more flexible and powerful than just providing a set of string\/string name\/value pairs.<\/p>\n<p>But before we look at that, let&#8217;s look at the Oxygene equivalent to the above C# code.<\/p>\n<h2> The Oxygene Approach <\/h2>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\r\n\r\n   routes.MapRoute\r\n   (\r\n      'Default',\r\n      '{controller}\/{action}\/{id}',\r\n      new class\r\n      (\r\n         controller := 'Home',\r\n         action     := 'Index',\r\n         id         := ''\r\n      )\r\n   );\r\n\r\n<\/pre>\n<p>Again, the code is formatted for comparison with the previous C# example, not indicative of the style I would actually use.<\/p>\n<p>We can see that Oxygene uses a <em>very<\/em> similar syntax to the C# version.<\/p>\n<p>The primary difference is that we use the <strong>new class<\/strong> combination of keywords to indicate that we are instantiating a <a href=\"https:\/\/en.wikipedia.org\/wiki\/Plain_Old_CLR_Object\">POCO<\/a>, rather than an implementation of an interface (<strong>new interface<\/strong>).<\/p>\n<p>Unlike C#, with its use of what to me looks like a perversely formatted pseudo-statement block, Oxygene employs a consistency in it&#8217;s approach.<\/p>\n<p>The members of an anonymous class are defined and initialised with what is essentially (in Oxygene terms) an &#8220;extended constructor&#8221;.<\/p>\n<p>The result is that in Oxygene we use the same syntax for initialising (and defining) the properties of an anonymous class as would be used to initialise the properties of <em>any<\/em> instantiated class in its constructor by specifying additional property assignments as &#8220;parameter expressions&#8221; following any actual constructor parameters.<\/p>\n<p>You may recall, <a href=\"https:\/\/www.deltics.co.nz\/blog\/posts\/2511\">from my previous post on anonymous classes<\/a>, that this is also how we provide the implementation of the methods in an anonymous class implementing an interface, by assigning method bodies to the appropriate method identifiers in similar constructor assignments.<\/p>\n<h2> So, What is the Point ? <\/h2>\n<p>As I mentioned above, anonymous classes have some advantages when compared to the alternatives such as simply encoding name\/value information in a string or using some generalised class for passing around name\/value pairs.<\/p>\n<p>Most of the advantages should be obvious in terms of clarity or simplicity.<\/p>\n<p>More than a couple of values in an encoded string quickly becomes a pain to read and maintain, not to mention the possible challenges of safely encoding values with more than just simple alphanumeric content in the values; instantiating and initialising a dictionary or other similar collection of name\/value pairs is awkward and cumbersome by comparison, to say the least.<\/p>\n<p>But beyond this, the main strength of anonymous classes is the <em>type safety<\/em> they provide.<\/p>\n<p>That might sound like a strange thing to say about a class that by definition has no identifiable type.  Even though it may not be obvious, an anonymous class is in fact strongly typed.  More obviously, the member properties <em>are<\/em>.<\/p>\n<p>Consider this code:<\/p>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\r\n\r\n  var foo := new class( Bar := 'Forty two' );\r\n  var s   := foo.Bar;\r\n\r\n<\/pre>\n<p><strong>Q:<\/strong> What type is <strong>foo<\/strong> ?<br \/>\n<strong>A:<\/strong> object<\/p>\n<p>Well, yes and no.  Technically what happens is that compiler will derive a complex and unique name for the class, since we did not provide one ourselves (the same thing happens when we use an anonymous class to implement an interface).<\/p>\n<p>But since we don&#8217;t know what that class name is in our code then for the purposes of passing these things around, the ultimate ancestor of all classes is all we have to work with.  You could get at the generated classname if you really wanted, but it isn&#8217;t going to be of much use that I can see.<\/p>\n<p>How about these&#8230;<\/p>\n<p><strong>Q:<\/strong> What type is <strong>foo.Bar<\/strong> ?<br \/>\n<strong>Q:<\/strong> What type is <strong>s<\/strong> ?<\/p>\n<p>This is far more straightforward:  Both are <strong>string<\/strong>.<\/p>\n<p>The type of <strong>foo.Bar<\/strong> is inferred as <strong>string<\/strong> and so, being strongly typed, the type of <strong>s<\/strong> is itself inferred from the type of <strong>foo.Bar<\/strong>.<\/p>\n<p>We can prove this by forcing a compilation error, explicitly declaring the type of the in-place variable <strong>s<\/strong> as a type not assignment compatible with a string:<\/p>\n<pre class=\"brush: oxygene; title: ; notranslate\" title=\"\">\r\n\r\n  var foo := new class( Bar := 'Forty two' );\r\n  var s: Integer := foo.Bar;  \/\/ Compiler says NO!\r\n\r\n<\/pre>\n<p>And this code works whether compiling for .net, Java\/Android or iOS\/macOS.<\/p>\n<p>Visual Studio code completion will even present the <strong>Bar<\/strong> property for the <strong>foo<\/strong> object, along with all the usual members we expect on every object, so for .net:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-net.jpg?resize=381%2C168&#038;ssl=1\" alt=\"\" width=\"381\" height=\"168\" class=\"aligncenter size-full wp-image-2549\" srcset=\"https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-net.jpg?w=381&amp;ssl=1 381w, https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-net.jpg?resize=300%2C132&amp;ssl=1 300w, https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-net.jpg?resize=380%2C168&amp;ssl=1 380w\" sizes=\"(max-width: 381px) 100vw, 381px\" data-recalc-dims=\"1\" \/><\/p>\n<p>And for Java\/Android:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-java.jpg?resize=365%2C223&#038;ssl=1\" alt=\"\" width=\"365\" height=\"223\" class=\"aligncenter size-full wp-image-2550\" srcset=\"https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-java.jpg?w=365&amp;ssl=1 365w, https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-java.jpg?resize=300%2C183&amp;ssl=1 300w\" sizes=\"(max-width: 365px) 100vw, 365px\" data-recalc-dims=\"1\" \/><\/p>\n<p>And Linux\/Win32\/Win64:<\/p>\n<p><img decoding=\"async\" loading=\"lazy\" src=\"https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-linux.jpg?resize=372%2C227&#038;ssl=1\" alt=\"\" width=\"372\" height=\"227\" class=\"aligncenter size-full wp-image-2546\" srcset=\"https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-linux.jpg?w=372&amp;ssl=1 372w, https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/code-completion-linux.jpg?resize=300%2C183&amp;ssl=1 300w\" sizes=\"(max-width: 372px) 100vw, 372px\" data-recalc-dims=\"1\" \/><\/p>\n<p>In the latter case you might be wondering where the very idea of an <strong>object<\/strong> comes from in projects of this type ?<\/p>\n<p>The answer is that for the <a href=\"http:\/\/blogs.remobjects.com\/2016\/05\/23\/island\/\">Island platforms<\/a> (the umbrella name for the Win32\/64 and Linux targets) there is a minimal RTL provided and built-in, to make core language features such as this even work (among other things).<\/p>\n<p>Pretty neat.<\/p>\n","protected":false},"excerpt":{"rendered":"<p><span class=\"rt-reading-time\" style=\"display: block;\"><span class=\"rt-label rt-prefix\">[Estimated Reading Time: <\/span> <span class=\"rt-time\">5<\/span> <span class=\"rt-label rt-postfix\">minutes]<\/span><\/span> There is another use case for anonymous classes, even simpler than that of providing implementations of interfaces: Anonymous POCO&#8217;s.<\/p>\n","protected":false},"author":2,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"jetpack_post_was_ever_published":false,"jetpack_publicize_message":"","jetpack_is_tweetstorm":false,"jetpack_publicize_feature_enabled":true,"jetpack_social_post_already_shared":true,"jetpack_social_options":[]},"categories":[4,180],"tags":[311,13,181],"jetpack_publicize_connections":[],"jetpack_featured_media_url":"","jetpack_shortlink":"https:\/\/wp.me\/p1TKYv-EH","jetpack_sharing_enabled":true,"jetpack-related-posts":[{"id":2574,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/2574\/","url_meta":{"origin":2523,"position":0},"title":"Anonymous Classes: Identity Exposed!","date":"18 Feb 2017","format":false,"excerpt":"In my previous post on Anonymous Classes I erroneously referred to them as \"dynamic objects\" (thanks to commentors for pulling me up on that). Dynamic objects are something else entirely (although what precisely they might mean can vary on different platforms and in different languages). I have now corrected that\u2026","rel":"","context":"In &quot;Delphi&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2511,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/2511\/","url_meta":{"origin":2523,"position":1},"title":"Anonymous Classes: Implementing Interfaces","date":"11 Feb 2017","format":false,"excerpt":"A few years ago (2011 to be precise) someone asked a question on StackOverflow about support for anonymous classes in Delphi. The reason for the question was that the poster was trying to use Delphi to develop for Android and on that platform the widespread use of callback interfaces makes\u2026","rel":"","context":"In &quot;Android&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2252,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/2252\/","url_meta":{"origin":2523,"position":2},"title":"Making a Noise About on a Thread","date":"13 Aug 2014","format":false,"excerpt":"I'm working on an Android app at the moment, and for a bit of fun I decided to add a startup sound to brighten the day of every user that launches it. Which gives me another opportunity to present some of the advanced language features in Oxygene that make threading\u2026","rel":"","context":"In &quot;Android&quot;","img":{"alt_text":"","src":"https:\/\/i0.wp.com\/www.deltics.co.nz\/blog\/wp-content\/uploads\/Audio-Resource.png?resize=350%2C200&ssl=1","width":350,"height":200},"classes":[]},{"id":1624,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/1624\/","url_meta":{"origin":2523,"position":3},"title":"Exploring Listeners With Oxygene","date":"16 Sep 2013","format":false,"excerpt":"Part 2 in a short series demonstrating the development of a simple camera app for Android using Oxygene. In the previous instalment we looked at the basic framework of our app. For this instalment I was going to show how to implement the camera preview or viewfinder for this instalment,\u2026","rel":"","context":"In &quot;Android&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2470,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/2470\/","url_meta":{"origin":2523,"position":4},"title":"Mix-in Unified and Segregated Syntax: An (Extended) Example","date":"25 Nov 2016","format":false,"excerpt":"Yesterday I initially posted that you couldn't mix Unified Syntax with \"traditional\" interface and implementation sections. Or what I am now calling Segregated Syntax. As sometimes happens, shortly after writing what I thought I knew to be true I discovered it wasn't ! Sorry about that. :) I promised to\u2026","rel":"","context":"In &quot;Cooper&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]},{"id":2265,"url":"https:\/\/www.deltics.co.nz\/blog\/posts\/2265\/","url_meta":{"origin":2523,"position":5},"title":"Nullable Types.  Not!","date":"23 Aug 2014","format":false,"excerpt":"I recently mentioned that RemObjects have placed their OS X native IDE - a.k.a. Fire - into public beta. I haven't been using it myself (yet) but have been following developments in the RemObjects Talk forums with interest, and a new feature in the Elements 8.0 compiler (also part of\u2026","rel":"","context":"In &quot;Delphi&quot;","img":{"alt_text":"","src":"","width":0,"height":0},"classes":[]}],"_links":{"self":[{"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/posts\/2523"}],"collection":[{"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/users\/2"}],"replies":[{"embeddable":true,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/comments?post=2523"}],"version-history":[{"count":15,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/posts\/2523\/revisions"}],"predecessor-version":[{"id":2573,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/posts\/2523\/revisions\/2573"}],"wp:attachment":[{"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/media?parent=2523"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/categories?post=2523"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/www.deltics.co.nz\/blog\/wp-json\/wp\/v2\/tags?post=2523"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}