tag:blogger.com,1999:blog-38293498053016272652024-03-08T07:06:48.719+00:00MetaTechnologyThoughts about (mostly Information) TechnologyPhil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.comBlogger12125tag:blogger.com,1999:blog-3829349805301627265.post-29207268420217063142009-09-28T07:01:00.002+00:002009-09-28T08:07:14.389+00:00This blog has moved - please update RSS readersThis blog is now deprecated and all new posts (as well as a few old ones) will now be posted to my new blog site at <a href="http://www.levelofindirection.com">www.levelofindirection.com</a>. I hope you'll agree it's much nicer.Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com0tag:blogger.com,1999:blog-3829349805301627265.post-81873203053199794382009-09-21T06:59:00.003+00:002009-09-28T07:00:54.378+00:00Code formatting in C++ Part OneThis blog is now deprecated and all new posts (as well as a few old ones) will now be posted to my new blog site at <a href="http://www.levelofindirection.com">www.levelofindirection.com</a>. <br /><br />The article that would have appeared here (which I removed due to formatting issues, ironically) can be found at: <a href="http://www.levelofindirection.com/journal/2009/9/23/code-formatting-in-c-part-one.html">http://www.levelofindirection.com/journal/2009/9/23/code-formatting-in-c-part-one.html</a>Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com0tag:blogger.com,1999:blog-3829349805301627265.post-9034523883616107932009-04-29T10:17:00.008+00:002009-09-28T06:57:43.532+00:00Elegant XML parsing with Objective-C<span style="font-style:italic;">[This blog has moved and this article can now be found at <a href="http://www.levelofindirection.com/journal/2009/9/24/elegant-xml-parsing-with-objective-c.html">http://www.levelofindirection.com/journal/2009/9/24/elegant-xml-parsing-with-objective-c.html</a>. It still appears here for archival purposes]</span><br /><br />If you write for the Mac you get two Objective-C XML APIs, one tree-based, DOM-like interface, and the other a SAX-like event-driven interface.<br /><br />If you write for the iPhone you only get the SAX interface. For many purposes this should be all your need.<br /><br />I was a little disappointed, though, when I first looked at the NSXMLParser class, that it didn't really take advantage of what Objective-C could offer. Probably this was a performance trade-off, as we'll discuss later, but as it is there are only two benefits I can see to using it over a lower level C API: (1) string conversions are done for you and (2) attributes are already set into dictionaries.<br /><br />I feel you can do so much more, though. So I did!<br /><br />In this post I'm going to walk through my own wrapper for NSXMLParser, which I developed while writing my iPhone game, <a href="http://www.vconqr.com/">vConqr</a>, and at the end give you access to my complete source, which is not terribly large or complex but due to some simplifying assumptions may need some tweaking to meet your needs. I'll bring those assumptions out as we go through.<br /><br /><h2>What's in a name?</h2><br />To start with, what's wrong with NSXMLParser? Well nothing as far as it goes. It looks like most SAX-like APIs. You provide a delegate object with methods like:<br /><br /><pre name="code" class="Cpp:nocontrols"><br />-(void) parser: (NSXMLParser*) parser<br /> didStartElement: (NSString*) elementName<br /> namespaceURI: (NSString*) namespaceURI<br /> qualifiedName: (NSString*) qName<br /> attributes: (NSDictionary*) attributeDict<br /></pre><br /><br />This is probably the most important method in the interface. This will be called every time the opening tag for a new element is found. As you can see you get passed the parser object itself (which seems a waste, if you wanted it you'd surely just hold a reference at the start), the name of the element, a couple of namespace strings and all the attributes as a dictionary.<br /><br />Aside from the redundant parser object, I also usually find that for my own small scale, app-specific, xml formats I don't bother with namespaces. If we're wrapping this API we'll probably drop all of those (this is where the first simplifying assumption comes in. If you do need the namespace data it's trivial to extend my code to add it back in - and even make it optional, as we'll see).<br /><br />That leaves the element name and attributes. It doesn't get much simpler than that, does it? Well think about this for a moment. What's the first thing you're going to do in your handler method? I suspect there's not much you can do that's not element specific (actually there are a few things, but we'll even pull those out shortly). So you're probably going to need to switch on the element name.<br />Of course, in Objective-C you can't write a switch statement on a string, so you'll end up with something like:<br /><br /><pre name="code" class="Cpp:nocontrols"><br />if( [elementName isEqualToString: @"elephant"] )<br />{<br /> // Do something with elephant elements<br />}<br />else if( [elementName isEqualToString: @"giraffe"] )<br />{<br /> // Do something with giraffe elements<br />}<br />else if ( /* next check */ )<br />{<br /> // ...<br /></pre><br /><br />did you remember not to compare strings with == ? (catches a lot of newer, and sometimes not so new, Objective-C programmers out). Using == would compile but silently fail at runtime (it compares the pointers, not the strings).<br /><br />So we have needless, repetitive, boilerplate with at least one thing that's easy to get wrong. Furthermore, if this is any more than a couple of checks and a small amount of code in each if block, you'll almost certainly want to forward on to more specialised methods anyway, such as handleElephantElement).<br /><br />Can we do better? It seems that what we want here is a way to do dynamic dispatch of methods based on names we don't know until runtime. If that's not what a Dynamic Programming Language gives us then I don't know what it is.<br /><br />Objective-C, or at least NSObject, has a class method called performSelector: that we can use for dynamic dispatch. But performSelector: takes a selector (of type SEL) as it's argument. Can we get a SEL from a string? Yes we can. There's a function called NSSelectorFromString() which does just that! Now, if we build our selector dynamically we can call it - but what happens if we don't implement a handler for every element? We'll get a runtime error, which will usually result in terminate being called. That's a bit harsh. Fortunately the common idiom of calling respondsToSelector: first serves us well here. Putting this all together we get something like:<br /><br /><pre name="code" class="Cpp:nocontrols"><br /> SEL sel = NSSelectorFromString( [NSString stringWithFormat:@"handleElement_%@:", elementName] );<br /> if( [delegate respondsToSelector:sel] )<br /> {<br /> [delegate performSelector:sel withObject: attributeDict];<br /> }<br /></pre><br /><br />Don't forget to include the : at the end of the selector name as you build it (so we can pass the attributes as the, currently, sole argument).<br /><br />So now, with all that boilerplate pushed to the generic wrapper, we'll be able to write handlers like this:<br /><br /><pre name="code" class="Cpp:nocontrols"><br />-(void) handleElement_elephant: (NSDictionary*) attributes;<br />-(void) handleElement_giraffe: (NSDictionary*) attributes;<br /></pre><br /><br />which I think you'll agree is much cleaner. Clearly there is some overhead here (hence my comments about performance earlier), but for most cases this is not going to be an issue at all.<br /><br />We can do the same for end tags, but the attributes are not needed. I called this method, handleElementEnd_{name}: (where {name} is the name of the element) and used the same techniques.<br /><br />So, that's elements and attributes handled, but there's one more entity that we need before we can parse any useful documents: Text nodes.<br /><br /><h2>Don't text me, I'll text you</h2><br />There are a number of aspects of text nodes that make them tricky to deal with in a SAX-like interface.<br />The first problem is what to do with whitespace? Often, within a text node, whitespace should be preserved - but at the beginning and end you just want it stripped.<br /><br />Text nodes occur at any point in a document, within the root document and outside of element tags. That means that even just the newlines and indentation spaces you probably have between adjacent element tags will be represented as text nodes.<br /><br />A common solution to the first issue, which may solve the second too, is to trim whitespace at the extremities (beginning and end), or better still, make it an option. If you do trim, then you need to make sure you don't raise an event for an empty text node. With text nodes trimmed, and empty text nodes suppressed, no events will be raised for formatting whitespace between tags.<br /><br />The second problem (which you also need to allow for before trimming), is that a single element may contain any number of text nodes. According to most SAX-like API specs (and NSXMLParser is no exception here), there is no guarantee how the text that belongs to an element will be split up, if at all. In practice you can usually count on getting a separate event for text before any child elements, each gap between child elements, and any more text after child elements. If any of those blocks of text are large (for some value of large) it's likely they will be broken down further for memory contraint reasons (imagine that the input processor probably has a buffer it's writing text nodes into. I've certainly implemented a parser exactly that way before).<br /><br />Attaching any meaning to how text is broken up is probably misguided at best, so before you process your text nodes you will almost certainly want to collate the text nodes into a single string (unless you're expecting very large blocks of text. We'll make the simplifying assumption here that that's not the case).<br /><br />So, to collect our text nodes we'll need to maintain some state as to the current aggregated text. This problem is complicated if you have a mixture of text and child elements, and the text may appear before or after (or between) child elements. To manage this you'll have to maintain some sort of stack of text blocks, mapped to elements - with unbounded memory requirements.<br /><br />In practice, mixing child elements and non-whitespace text is uncommon, so one way to simplify this is to ignore the whole problem. If we just take the first, or last, text nodes (ie before or after any potential child elements) then at worst the text will be truncated. For my purposes, where I was completely in control of the schema this was the route I took and is reflected in the code here (any time we see a child node we reset our text buffer). If you want to implement the more general case you'll have to look at the stack-based idea (perhaps a future blog article).<br /><br />Tracking text nodes this way becomes quite simple. I declare an instance variable to hold the current text value:<br /><br /><pre name="code" class="Cpp:nocontrols"><br />NSMutableString* currentTextString;<br /></pre><br /><br />Now to collect the text we need to implement the method parser:foundCharacters: on our delegate. This will simply append the incoming string to our current string state, or create a new mutable string copy as necessary:<br /><br /><pre name="code" class="Cpp:nocontrols"><br />-(void) parser: (NSXMLParser*) parser<br /> foundCharacters: (NSString*) string<br />{ <br /> if( string && [string length] > 0 )<br /> {<br /> if( !currentTextString )<br /> {<br /> currentTextString = [[NSMutableString alloc] initWithCapacity:4];<br /> }<br /> [currentTextString appendString:string];<br /> }<br />}<br /></pre><br /><br />The choice of 4 characters to preallocate was entirely arbitrary and could be tweaked to your needs. Also, you might want to check if this is the first text node being appended, and is entirely whitespace (and whitespace at the ends is being trimmed), then don't even bother creating a new mutable string here just to throw it away. My version is simple and works for my needs.<br /><br />In order to implement my simplification of throwing away any text before a child node we need to add a bit to parser:didStartElement:namespaceURI:qualifiedName:attributes: to release the string object if it's non-empty:<br /><br /><pre name="code" class="Cpp:nocontrols"><br /> if( currentTextString )<br /> {<br /> [currentTextString release];<br /> currentTextString = nil;<br /> }<br /></pre><br /><br />Now how do we get the text we've accumulated to the delegate? One way would be to create a new event method, handleText: for example. But you'll almost always want to tie the text up to the current element, so you'll want to track that and pass it to. I decided that this already looks so much like our end element handler that I just made it look like an extended version -<br /><br /><pre name="code" class="Cpp:nocontrols"><br />-(void) handleElementEnd_tiger: (NSDictionary*) attributes withText:(NSString*) text;<br /></pre><br /><br />Note that if an end tag is found and there is non-empty text, <em>both</em> events will be fired, if implementations exist, so you can get handleElementEnd_tiger: <em>and</em> handleElementEnd_tiger:withText:<br /><br />You could use the same technique of looking for two versions of a method, one with more arguments, to optionally pass namespace data, if you like.<br /><br />So now, with elements, attributes and text nodes sorted we can start doing some basic parsing. However we soon run up against another issue.<br /><br /><h2>In my element</h2><br />When we write an element (start or end) handler, with our without text nodes, we know our immediate context. We at least know the current element name.<br /><br />However XML is a hierarchy. While it is certainly possible to write XML such that any given element name can occur at exactly one level of the hierarchy, this is a bit limiting to enforce all the time. For example, in <a href="http://www.vconqr.com/">vConqr</a> I have an element called path that contains the vector coordinates of part of the border of a territory. But my borders are split up into three types - internal, external and continent (where continent means an internal border that separates two continents). There are two ways to represent that relationship in XML. One is to make the border type a property of the border element (type="internal" etc). The other is to build it into the name (internalBorder, externalBorder, etc).<br /><br />I chose to go with the latter because maintaining a stack of element names is easier than maintaining a stack of elements and attributes. To properly implement the element and attributes stack I'd be going down the road of building partial DOM objects in memory - which in the general case is not a direction I wanted to go in.<br /><br />But just keeping a stack of element names is much simpler, and so I added this to the wrapper class.<br /><br />I just have an instance variable for the stack:<br /><br /><pre name="code" class="Cpp:nocontrols"><br /> NSMutableArray* elementStack;<br /></pre><br /><br />and I push and pop the element names on and off the stack in parser:didStartElement:... and parser:didEndElement:... respectively.<br /><br />Access is by a simple method:<br /><br /><pre name="code" class="Cpp:nocontrols"><br />-(NSString*) ancestorElementAtIndex:(int) index<br />{<br /> return [elementStack objectAtIndex: elementStack.count-(index+1)];<br />}<br /></pre><br /><br />Now, in my handleElement_path: method. I can call [parser ancestorElementAtIndex:1] and get back the border element that the path belongs to and act appropriately.<br /><br /><br /><h2>Thanks a bundle</h2><br />With the handler code nicely simplified all that remains is to kick the parser off. This also has a fair bit of boilerplate associated with it. Again, I've made a few assumptions that are appropriate to the way I tend to use this. In particular I'm assuming that I'm targeting the iPhone, and that the XML files in question are in my application bundle. In my next version I have to deal with XML that I download elsewhere too, so I have an alternative version of the parser launching method that handles that.<br /><br />For now, though, I have loadFromBundle:, which starts with the following code that generates the filename, looks it up in the application bundle and initialises the NSXMLParser with it:<br /><br /><pre name="code" class="Cpp:nocontrols"><br /> NSString* filename = [NSString stringWithFormat:@"%@.xml", name ];<br /> NSString *path = [[[NSBundle mainBundle] bundlePath] stringByAppendingPathComponent:filename];<br /><br /> NSURL* url = [NSURL fileURLWithPath: path];<br /> NSXMLParser* parser = [[NSXMLParser alloc] initWithContentsOfURL:url];<br /></pre><br /><br />Then some more simplifying assumptions:<br /><br /><pre name="code" class="Cpp:nocontrols"><br />[parser setShouldProcessNamespaces:NO];<br />[parser setShouldReportNamespacePrefixes:NO];<br />[parser setShouldResolveExternalEntities:NO];<br /></pre><br /><br />Remember, we're not dealing with namespaces. We're also not interested in referencing external entities.<br /><br />The wrapper class subclasses NSXMLParser, so the delegate is self (the wrapper maintains it's own delegate).<br />And we can start the parsing:<br /><pre name="code" class="Cpp:nocontrols"><br />parser.delegate = self;<br />parser parse];<br /></pre><br /><br />The parser will call back the low level handlers on the subclass, which will translate those to the dynamic handler names we discussed earlier, maintaining the text nodes and element path stack, and keeping the application code simple, elegant and expressive.<br /><br />The full source code for my XML wrapper can be found here:<br /><br /><a href="http://pan.europe.googlepages.com/TbcXml.h">TbcXml.h</a><br /><a href="http://pan.europe.googlepages.com/TbcXml.m">TbcXml.m</a>Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com0tag:blogger.com,1999:blog-3829349805301627265.post-25850122167551538162009-04-26T22:57:00.004+00:002009-09-28T06:56:36.219+00:00ACCU 2009 - after the math<span style="font-style:italic;">[This blog has moved and this article can now be found at <a href="http://www.levelofindirection.com/journal/2009/9/24/accu-2009-conference.html">http://www.levelofindirection.com/journal/2009/9/24/accu-2009-conference.html</a>. It still appears here for archival purposes]</span><br /><br /><br />It's 23:57. That can only mean it's time to blog about the ACCU conference again!<br /><br />First I'd like to say that the <a href="http://search.twitter.com/search?max_id=1623438200&page=6&q=%23accu_conf&rpp=20">#accu_conf hashtag</a> for the conference was a great success, yielding 11 pages of tweets at the current count. I strongly believe that twitter is becoming more important every day, and that it's power to change the way we look at communication has yet to be fully assessed.<br /><br />As for the conference programme itself - I can reaffirm my statement that this is the premiere developer's conference in the world! What really sets it apart is that the content is almost exclusively about programming, rather than about specific tools and libraries, and the delegates genuinely do subscribe to the "professionalism in programming" ethic of the ACCU.<br /><br />To give you a flavour, here's a tweet from "<a href="http://www.objectmentor.com/omTeam/martin_r.html">Uncle Bob</a>" (Robert Martin - of Agile Alliance and Object Mentor fame): "<span style="font-style: italic;">This is probably the geekiest conference I've been to. Lots of coding, lots of interesting discussions. Wow</span>.". And later, "<span style="font-style: italic;">And now for the long trek home. I wish I could stay, this is a really fun conference."<br /><br /><span style="font-style: italic;"><span style="font-style: italic;"><span style="font-style: italic;"></span></span></span></span>Sadly, for a combination of reasons, I missed about half the sessions this year - but what I did see were at least as high quality as I have come to expect.<br /><br />It was especially revealing hearing about the threading support being added to C++0x (already starting to be referred to as C++1x) - then shortly after hearing about the concurrency support being added to D 2.<br />In the former case the focus<span style="font-style: italic;"> <span style="font-style: italic;"><span style="font-style: italic;"><span style="font-style: italic;"></span></span></span></span>was on catching up in terms of the memory model and library primitives.<span style="font-style: italic;"> <span style="font-style: italic;"></span></span>Welcome additions to be sure. However D continues to move forward in ways that only a language not constrained by it's own legacy can do. It's contributions this year expanded on last year's functional support with transitive immutable and const modifiers, to add keywords that mark variables as shared - thus making explicit the communication paths that have been the bane of just about every imperative language before by their implicitness.<br /><br />D's concurrency was presented to us by Walter Bright (who first designed the language). However, I found it amusing how Andrei Alexandrescu, in both his presentations, appeared to be talking about C++, but held D up as being the true answer to just about every tricky point he raised. More subtle than Russell Winder's continuing "C++ serves no useful purpose" theme, to be sure, but no less damning!<br /><br />As usual, half of the real content of the conference took place after hours in the hotel bar (or restaurants in Oxford). John Lakos' absence from this ritual was, therefore, all the more noticeable. He arrived on friday, apparently jet-lagged, and had to rush through his 400-odd slides at such a rapidly increasing rate that it appeared his head would explode before he finished it! I can report that his head did survive to see another day, but it wasn't seen in the bar.<br /><br />Perhaps he felt he wasn't required to put a new puzzle out this year, as there was a cryptography contest going on already in aid of raising funds for <a href="http://www.bletchleypark.org.uk/content/museum.rhtm">Bletchley Park Museum</a>.<br /><br />In all the message is clear. If you weren't at the conference you missed out on something rather special. Make every preparation now to be there next year.Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com1tag:blogger.com,1999:blog-3829349805301627265.post-6177252043189079772009-04-19T22:53:00.004+00:002009-04-26T22:55:33.245+00:00ACCU Conference 2009Next week (or this week, depending on how you count it... oh it's 23:57, by the time I finish this post it will be this week either way) is the 2009 Annual Conference of the ACCU (which doesn't stand for the Association of C & C++ Users... anymore).<br /><br />I'm just finishing my slides for my presentation on Thursday morning where I'll be talking about Objective-C. I expect a full room, of course, and anyone at the conference who doesn't come must make it up to me by buying me a drink.<br /><br />It seems like every year the conference programme gets stronger (despite my contributions to some of them) - and when I first started going (six years ago) it was already the best developer-oriented conference around.<br /><br />This year has a special track on patterns, and has some world class experts on the subject presenting. The usual world class experts on other subjects will also be presenting too, of course. I won't say more because I'll only be repeating <a href="http://accu.org/index.php/conferences">what you can already read here</a>.<br /><br />If you use Twitter (and if not, why not?) you can follow all the twitter-chatter about the conference, including what interview puzzle John Lakos will be posing in the bar this year, by following the <a href="http://hashtags.org/tag/accu_conf/messages">#accu_conf</a> hashtag.<br /><br />If you use a twitter client that supports it (and if not, why not?) I find it's best to subscribe to a <a href="http://search.twitter.com/search?q=%23accu_conf">search for the tag</a>, rather than rely on hashtags itself picking up all the tweets (seems to have a hit rate of about 30% at the moment). Personally I use TweetDeck, which I have found pretty good - but am looking forward to Tweetie for Mac being released tomorrow (or later today). But that's getting off topic.<br /><br />See you all there!Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com0tag:blogger.com,1999:blog-3829349805301627265.post-21431740193212661802009-02-17T13:32:00.002+00:002009-09-28T06:53:37.955+00:00Getting at pixel data from a UIImage for iPhone dev<span style="font-style:italic;">[This blog has moved and this article can now be found at <a href="http://www.levelofindirection.com/journal/2009/9/24/getting-at-pixel-data-from-a-uiimage-for-iphone-dev.html">http://www.levelofindirection.com/journal/2009/9/24/getting-at-pixel-data-from-a-uiimage-for-iphone-dev.html</a>. It still appears here for archival purposes]</span><br /><br /><br />UIImage is a fairly thin wrapper for a CGImage (so most of this applies to standard Mac dev too), but CGImage is an opaque type. You can't get at the raw image data (actually you can, but it's in it's encoded form).<br /><br />If you want to test individual pixel values you must render the image into a bitmap context, having supplied the context with a memory buffer that you control.<br /><br />This is not as complex as it sounds, but still has quite a few steps - and hunting around for the information may take you down a few blind alleys or unnecessary steps.<br /><br />Erica Sadun, in her iPhone Developer's Cookbook has a recipe for this, but I'd already come up with some code beforehand. I believe mine is more concise, and doesn't suffer from the sub-pixel problem (that an earlier version of mine had, and I believe Sadun's is susceptible to too). So while I recommend the book, I'm presenting my code here too.<br /><br />As written it is only interested in alpha values, but some small tweaks will let you get at the colour information too.<br /><br /><pre name="code" class="Cpp:nocontrols"><br />//<br />// AlphaPixels.h<br />//<br />// Created by Phil Nash on 26/10/2008.<br />// Copyright 2008 Two Blue Cubes Software<br />//<br />// Distributed under the Boost Software License, Version 1.0.<br />// (see: http://www.boost.org/LICENSE_1_0.txt)<br /><br />#import <UIKit/UIKit.h><br /><br />@interface AlphaPixels : NSObject<br />{<br />unsigned char* pixelData;<br />int width;<br />}<br /><br />-(id) initWithImage: (UIImage*) image;<br />-(float) alphaAtX:(int) x y:(int) y;<br /><br />@end<br /></pre><br /><br /><pre name="code" class="Cpp:nocontrols"><br />//<br />// AlphaPixels.m<br />//<br />// Created by Phil Nash on 26/10/2008.<br />// Copyright 2008 Two Blue Cubes Software<br />//<br />// Distributed under the Boost Software License, Version 1.0.<br />// (see: http://www.boost.org/LICENSE_1_0.txt)<br />//<br /><br />#import "AlphaPixels.h"<br /><br />@implementation AlphaPixels<br /><br />-(id) initWithImage: (UIImage*) image<br />{<br /> // We'll be needing a chunk of memory to hold the rendered (alpha channel of the) image...<br /> width = image.size.width;<br /> int height = image.size.height; <br /> pixelData = malloc( width * height );<br /> <br /> if( !pixelData )<br /> {<br /> NSException *exception = [NSException exceptionWithName:@"AlphaPixelsException" <br /> reason:@"Unable to allocate memory for pixel data" <br /> userInfo:nil];<br /> @throw exception;<br /> }<br /> <br /> // ... and a bitmap context to describe how to render - the alpha only constant<br /> // is the important bit here (no need to provide a colorspace)<br /> CGContextRef context = CGBitmapContextCreate ( pixelData,<br /> width, <br /> height, <br /> 8, <br /> width, <br /> NULL, <br /> kCGImageAlphaOnly ); <br /> <br /> if( !context )<br /> {<br /> NSException *exception = [NSException exceptionWithName:@"AlphaPixelsException" <br /> reason:@"Unable to create bitmap context" <br /> userInfo:nil]; <br /> @throw exception;<br /> }<br /> <br /> // Render the image into the context (ending up in our buffer)<br /> CGContextDrawImage( context, CGRectMake(0, 0, width, height), image.CGImage );<br /> CGContextRelease( context );<br /> <br /> return self;<br />}<br /><br />-(void) dealloc<br />{<br /> free( pixelData );<br /> [super dealloc];<br />}<br /><br />-(float) alphaAtX:(int) x y:(int) y<br />{<br /> // Simple calculation to get the offset into the buffer for the coordinate values<br /> // - but note these are all integer values. Floats representing sub-pixel values would<br /> // need to be rounded before doing something similar<br /> return pixelData[y * width + x]/255;<br />}<br /><br />@end<br /></pre>Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com3tag:blogger.com,1999:blog-3829349805301627265.post-74010494830314188922008-05-13T20:13:00.007+00:002008-05-16T17:39:47.586+00:00ACCU 2008: On Snowflakes and Architecture - Steve Love<div>"A talk on how architectural decisions in software can influence its design, and affect different aspects of the whole thing, specifically its adaptability, testability, portability and maintainability..."<a href="http://accu.org/index.php/conferences/accu_conference_2008/accu2008_sessions#On%20Snowflakes%20and%20Architecture" style=""><span class="Apple-style-span" style="color: rgb(0, 0, 0); text-decoration: none;"> </span></a><a href="http://accu.org/index.php/conferences/accu_conference_2008/accu2008_sessions#On%20Snowflakes%20and%20Architecture">More details (and slides) here</a></div><div><br /></div><div><embed id="VideoPlayback" style="width:400px;height:326px" flashvars="" src="http://video.google.com/googleplayer.swf?docid=-5921684762697120624&hl=en" type="application/x-shockwave-flash"></embed> </div>Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com0tag:blogger.com,1999:blog-3829349805301627265.post-28046326340715245202008-05-13T20:08:00.004+00:002008-05-16T17:43:29.713+00:00ACCU Conference 2008Last month I attended the <a href="http://accu.org/index.php/conferences">2008 ACCU Conference</a>.<br />Needless to say it was awesome!<br />There were a few things that came up during the conference that I hope to blog about in the near future. I won't be doing session breakdowns (others have been doing a good job there - I'll try and post some links).<br />However, while I was there I took a number of videos of the sessions. At the time this was for my own purposes - I could only attend one session at a time - but others running in parallel looked so tempting... Videoing seemed the ideal solution.<br />Being for my own purposes the quality wasn't of paramount importance. Room noise, peoples heads, clipping of the beginning and/ or end were all evident.<br /><br />But quite a few people asked if I would make the videos available for them to see too. Enough people that I thought I'd see what was possible.<br />I have had no objections from the conference committee, and none (so far) from the presenters I have asked directly.<br />Therefore I have begun the process of uploading the video files to YouTube (*update - YouTube rejected them as they were too long, so I'm putting them on Google Video instead = so far so good).Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com0tag:blogger.com,1999:blog-3829349805301627265.post-69927082641397950472007-06-18T15:41:00.001+00:002009-09-28T06:51:09.366+00:00Readable RAII in C# ?<span style="font-style:italic;">[This blog has moved and this article can now be found at <a href="http://www.levelofindirection.com/journal/2009/9/24/raii-and-readability-in-c.html">http://www.levelofindirection.com/journal/2009/9/24/raii-and-readability-in-c.html</a>. It still appears here for archival purposes]</span><br /><br />In my last post I made the following comment:<br /><br /><span style="font-style: italic;">"Of course, in C# there is the using keyword, along with the IDisposable interface, which gives you a little more C++-like scoped disposal. Even this is less clean and more awkward than the C++ model, and I believe also has scalability problems (caveat - I haven't really used this in real C# programs)."<br /></span><br />Since that time I have been using C# almost exclusively and have had a chance to explore the using statement a bit more. In this post I'm going to expand a little on the theme of: "I believe [the using statement] also has scalability problems". How true is that statement, and what can we do to improve on things?<br /><br />First - a quick review: what is the using statement?<br />Well, C#, like Java, but unlike C++, has non-deterministic destructors. That is, you don't know when destructors will be called because they are called by the garbage collector, rather than the point at which the object they are to be called on goes out of scope.<br /><br />In C++, having deterministic destructors is very useful for implementing RAII (Resource Acquisition Is Initialization) techniques, a big part of which is cleaning up resources in the destructors. This includes, but is not limited to, memory allocations. Other resources could be file handles, database connections, GUI drawing object handles, or even more abstract "resources" such as closing tags in an XML outputer!<br /><br />The subtlety comes in the face of exceptions - which could occur at moments that are difficult to determine from the static code. I'm glossing here, of course, because many other articles have been written on the details of RAII and exception safety.<br /><br />In Java you can only really deal with exceptions when you have resources other than memory by using the try-finally construct. The finally clause gives you a place to put common clean-up code. You can abstract this further using Execute-Around. All this is covered in my previous post.<br /><br />In C# the story is much the same, with try-finally available. But C# goes one better by supplying the using statement. The using statement gives us back much of what we had in C++, by allowing a method on the object (Dispose, a method of the IDisposable interface that you must derive from) to be called at the end of the scope - whether that scope is exited by the normal flow of execution, or by an exception.<br /><br />However, we still have to put something in the client code - the using statement itself - and if you follow the traditional patterns you do, indeed, reach a scalability problem in terms of readability.<br /><br />To illustrate, imagine you have a class, Foo, which implements IDisposable. To use it you'd write code much like this:<br /><PRE> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span>( Foo foo <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo() )<br /> {<br /> <span style="color: Green; font-family: Courier New; font-size: 11px; background-color: White">// do stuff with foo here<br /></span> <br /> } <span style="color: Green; font-family: Courier New; font-size: 11px; background-color: White">// <-- foo's Dispose method is called here<br /></span></PRE><br />This looks nice and clean so far. But imagine if you need three Foos:<br /><PRE> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (Foo foo1 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo())<br /> {<br /> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (Foo foo2 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo())<br /> {<br /> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (Foo foo3 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo())<br /> {<br /> <span style="color: Green; font-family: Courier New; font-size: 11px; background-color: White">// Do stuff with foos here<br /></span> }<br /> }<br /> }<br /></PRE><br />Contrast that with what we'd need to to similar in C++:<br /><PRE> { <br /> Foo foo1;<br /> Foo foo2;<br /> Foo foo3;<br /> <br /> <span style="color: Green; font-family: Courier New; font-size: 11px; background-color: White">// Do stuff with foos here<br /></span> }<br /></PRE><br />In our C# version, the more disposable objects you have the more the readability suffers!<br />Imagine too, that the declarations are more complex (as they usually will be), and things start to get messy.<br /><br />But how often do you really need so many objects with deterministic disposal in C#? After all most things are going to be managed anyway, aren't they?<br /><br />Well, one common example might be with database connections, along with transactions, command objects, etc - all needing to be composed together, then disposed of at the right times.<br />Another might be something that generates XML or HTML. Even when using such things as XmlWriter there are times it is helpful to represent the hierarchy with RAII.<br /><br />So, can we improve on this situation?<br /><br />Well, the first thing to note is that there is a way to assign multiple objects to one using statement in C#. However there is one important caveat: all the objects must be of the same type!<br /><PRE> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (Foo foo1 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo(),<br /> foo2 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo(),<br /> foo3 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo())<br /> {<br /> <span style="color: Green; font-family: Courier New; font-size: 11px; background-color: White">// Do stuff with foos here<br /></span> } <br /></PRE>This is certainly better. However, if the declarations get more complex it can tend to suffer from readability problems along similar lines to passing anonymous delegates to methods - too much code between commas!<br />Also, that single type limitation is a cruel one. It won't help with our database connection, transaction etc problem.<br /><br />However there is another way! It allows different types to be declared. It can co-exist with the previous construct for multiple declarations of the same type, and it doesn't use any new language features! (thanks to <a href="http://code2code.net/">George Moudry</a> for suggesting this).<br />In fact, on first appearances it might even appear a bit of a hack - but bear with me here.<br />The secret is to go back to our first example - with the nested using statements. The trouble was all the redundant braces and indentation. So remove them! What? Yes, you don't actually need them! the braces just allow you to write multiple lines of code and have it appear to the compiler as a single block. However, if your multiple lines are another using statement, then it's already a single block.<br />Before you bring out the flame-throwers, take a look at this example:<br /><PRE> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (Foo foo1 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo())<br /> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (Foo foo2 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo())<br /> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (Bar bar <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Bar())<br /> {<br /> <span style="color: Green; font-family: Courier New; font-size: 11px; background-color: White">// do stuff with foos and bars here<br /></span> } <br /></PRE><br />It actually looks quite neat. How about something more realistic (thanks to Vishal Doshi for this example):<br /><PRE> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (<span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> System.Transactions.TransactionScope())<br /> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (OracleConnection conn <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> m_DB.GetConnection())<br /> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (OracleTransaction tx <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> conn.BeginTransaction())<br /> {<br /> <span style="color: Green; font-family: Courier New; font-size: 11px; background-color: White">//use conn, tx within the transaction scope<br /></span> } <br /></PRE><br />Also, remember I said you can mix it with C#'s construct for multiple declarations of the same type. Our foo-bar example could be written as:<br /><PRE> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (Foo foo4 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo(),<br /> foo5 <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Foo() )<br /> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">using</span> (Bar bar <span style="color: Red; font-family: Courier New; font-size: 11px; background-color: White">=</span> <span style="color: Blue; font-family: Courier New; font-size: 11px; background-color: White">new</span> Bar() )<br /> {<br /> <span style="color: Green; font-family: Courier New; font-size: 11px; background-color: White">// Do stuff with foos and bars<br /></span> } <br /></PRE>So, in conclusion: I still prefer the elegance of C++'s RAII capabilities - but creative use of C#'s using statement make using using more usable!Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com3tag:blogger.com,1999:blog-3829349805301627265.post-77604623027452184522007-02-16T11:12:00.001+00:002009-09-28T06:48:29.095+00:00RAII and closures in Java<span style="font-style:italic;">[This blog has moved and this article can now be found at <a href="http://www.levelofindirection.com/journal/2009/9/24/raii-and-closures-in-java.html">http://www.levelofindirection.com/journal/2009/9/24/raii-and-closures-in-java.html</a>. It still appears here for archival purposes]</span><br /><br />One of the biggest reasons I still prefer C++ over newer brethren such as Java and C# is its support for RAII (<a href="http://en.wikipedia.org/wiki/RAII">Resource Acquisition Is Initialisation</a>). Unlike C++, Java and C# have the <font face="Courier">finally</font> construct, to give you a place to do clean up of resources. The trouble is this doesn't scale very well. If you have several resources in a scope you may have to nest try-catch-finally blocks. A good article describing this problem from a Java perspective is <a href="http://www.javalobby.org/java/forums/t19048.html">here</a>.<br /><br />Of course, in C# there is the <font face="Courier">using</font> keyword, along with the IDisposable interface, which gives you a little more C++-like scoped disposal. Even this is less clean and more awkward than the C++ model, and I believe also has scalability problems (<i>caveat</i> - I haven't really used this in real C# programs).<br /><br />One way to work around the lack of deterministic destruction in such languages is to use the <a href="http://www.octopull.demon.co.uk/java/ACCU-Spring-2001/img15.htm">Execute-Around idiom</a> (more detailed coverage in <a href="http://www.two-sdg.demon.co.uk/curbralan/papers/AnotherTaleOfTwoPatterns.pdf">this pdf</a>). This allows you to factor out the resource acquisition, initialisation and release code, from the code that uses the resource. It scales better than inline try-catch-finally, but can result in much more fragmented (using a named class) or messy (using an anonymous class) code. In some cases the fragmentation may be a good thing - after all Extract Method is a valuable refactoring tool. But other times it may be too much, especially in such languages with a more imperative bias.<br /><br />In languages with decent support for <a href="http://en.wikipedia.org/wiki/Closure_%28computer_science%29">Closures</a>, Execute-Around can be a much more natural and pleasant experience with less fragmentation (although more because of the side-effect of decent language syntax, than because of the formal benefits of closures).<br /><br />But while C# has closures, as of .Net 2.0, Java doesn't. That is, not at the time of this writing. There are serious proposals afoot to add them to the language - and from the sound of this <a href="http://gafter.blogspot.com/2007/01/definition-of-closures.html">blog entry from Neal Gafter</a> (former Java co-designer, now at Google),they should have all the features that make them useful for techniques such as Execute-Around (as well as a whole load of other benefits, of course, but you can read about this elsewhere - such as in the cited article).<br /><br />Perhaps the time will yet come when I can use Java seriously without too many grimaces!Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com3tag:blogger.com,1999:blog-3829349805301627265.post-58935814842494160532007-02-15T15:00:00.000+00:002007-02-15T15:12:25.705+00:00ACCU conferenceHow better to kick off my technoblog than to mention the upcoming <a href="http://accu.org/index.php/conferences">ACCU conference</a>, and, of course, <a href="http://accu.org/index.php/conferences/accu_conference_2007/accu2007_sessions#Meta-Intelligent%20Design">my involvement in it</a> :-)<br /><br />For anyone wondering what the ACCU is, it stands for the <a href="http://accu.org/">Association of C and C++ Users</a>, but its membership covers a broader range of, mostly C-family, languages (inc. Java, C# and a number of dynamic languages). The group has a number of industry names in its fold - and a friendly, pub-like, atmosphere.<br />The conference is, according to many, <i>the</i> best programming related conference around, attracting top names such as Stroustrup, Sutter, Alexandrescu, Meyers and many others. At the same time many of the unlettered membership are given the opportunity to stand on the shoulders of giants, and this year I'll be one of them!<br /><br />My presentation is on the subject of "Meta-Intelligent Programming", and is a continuation of my "Organic Programming" concept that I kicked off at the ACCU conference three years ago. I'll start writing more about Organic programming itself in my dedicated blog (<a href="http://organic-programming.blogspot.com/">http://organic-programming.blogspot.com/</a>) - but suffice to say that it is not about programming, per se, but rather about how we use our minds (and bodies) more effectively in a software development environment. Think "<a href="http://en.wikipedia.org/wiki/Neuro-linguistic_programming">NLP</a> for software development" and you won't be far out. It mixes in a lot of <a href="http://en.wikipedia.org/wiki/Tony_Buzan">Tony Buzan</a> stuff too.Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com0tag:blogger.com,1999:blog-3829349805301627265.post-27940621998336562862007-02-15T14:49:00.000+00:002007-02-15T14:54:28.132+00:00What's this blog about?I'll be writing from my thoughts about technology in general or in specifics.<br />At least, that's the plan!Phil Nashhttp://www.blogger.com/profile/07697983218189410572noreply@blogger.com0