Archive for the ‘Coding’ Category

Updating the UI from a Task

While we’re talking things Parallel, the other part of the same demo from last post showed spawning a single task that slept for awhile and then called ShowMessage.

Note the comment. Read On…

“But what happens if…” : The Joy of Race Conditions

In my last post, I was trying to highlight the fact that just because you have done a WaitForAny and one of your Tasks has ended, the others don’t just all magically stop somehow. It’s good form for your Task to be checking if it has been Cancelled, and to quit as soon as possible, certainly before making any changes outside the context of the Task.

However, as I mentioned at the end of that post, we’re still not done. There is a window of time, albeit a small one, where things could go wrong, and in this post I want to explore what the problem is and how to resolve it. Read On…

WTF is a Future?

Of the abstractions introduced in the Parallel Programming Library, the IFuture<T> seems to be the one that many people have difficulty understanding.

Both TTask and TParallel.For seem reasonably easy to understand conceptually, even if you don’t understand all the details. TTask is about some code you want to run in parallel to the main thread. TParallel.For is about performing some actions on the items in a collection in parallel. In both cases you are focussed on the actions you want to perform. Read On…

Refactoring Support for Attributes in Delphi 2010

I mentioned earlier that a lot of work in this release had gone into smaller features and feature tweaks. One of the results is that the IDE keeps giving me pleasant surprises. I’ll try to do something without even really thinking about whether it should work or not, and find that it not only works, but that it goes a little further than I might have thought.

One example is around Refactoring support for Attributes. If you look at my first, simple example of Attributes, one of the many things wrong with it is that the Attribute name is terrible. Unless I never plan on writing more than one Attribute, MyAttribute is probably not the best choice.

Read On…

More Attributes in Delphi 2010

In my previous post on Attributes in Delphi 2010, I showed a basic view of the mechanics involved in creating, applying and querying Attributes. I didn’t really cover an example of why you might use them.

Probably the most common example given is for persistence, and indeed, someone over on the Wings of Wind website has posted an example along those lines. I’d like to show off a different use for them: Validation.

Read On…

RTTI and Attributes in Delphi 2010

RTTI (Runtime Type Information) has had a major overhaul in Delphi 2010. RTTI is a central piece on which the Delphi IDE is written, and as such has been around since the first release, however I’ve heard from a number of people over the years that they’d tried to use RTTI and found it too difficult and arcane, especially compared to the Reflection API’s in Java and .NET. That’s a real shame, as the ability to write code to query the details of other objects, without knowing the type up-front, is really powerful.

However, I think that complaint will be a thing of the past with this new API. It’s been not only extended to make it more capable, it is also now much more approachable and easy to use.

One of the new features that I’m very excited about is support for Attributes in Win32. I’m working on a larger example, but here’s a quick run through of creating and then querying custom attributes.

Custom attributes are simply classes that descend from TCustomAttribute. They can have properties, methods, etc, like any other class:

No real surprises here, and the constructor is implemented exactly as you’d expect.

Next, we can apply our attribute to our class:

Here I’ve applied it to both methods, but note I’ve supplied different parameters to the Attribute. Also note the order of the parameters matches the order in the constructor. This is not just limited to methods, you can apply attributes to properties, entire classes, all sorts of things.

Of course, there’s no point adding attributes if you can’t read them from somewhere, so here’s some sample code that uses the new RTTI API to query for our attributes, and display the details in a listbox:

First I grab a reference to the RTTI Context, and load it with the ClassType of my class. I then do a for..in over the methods in my class, and for each method do a for..in over the attributes. Then I check if the attribute is my custom attribute, and if so, grab the values of Name and Age and show them in a list box.

attribscreenshot

As I mentioned earlier, I’m working on another example which is a little more useful, but hopefully this gives you a little taste of some of the new stuff coming in 2010. Also, don’t forget to watch the preview videos at http://www.embarcadero.com/rad-studio-2010/, and subscribe to get notified when new ones are published.

Generic Interfaces in Delphi

Most of the examples I’ve seen of Generics in Delphi, use classes containing a generic type. However, while working on a personal project, I decided I wanted an Interface containing a generic type.

The project uses an in-process publish/subscribe mechanism, and I wanted a subscriber to have a separate Receive method for each event type, rather than a single method which contained a big case statement with branches for each event type. Equally, however, I didn’t want to have to define an interface type for each event type. What I wanted was to have a generic Subscriber interface, that took the event type as a parameter.

However, I had no idea if I could define a generic Interface, let alone implement one. Even assuming I could do both of those things, would Delphi be able to resolve the correct Receive method to invoke? Only one way to find out….

NB: In this example, I’ve stripped out most of the pub/sub stuff, just leaving the pieces needed to show the generic interfaces. I’ll write about the other pieces over the next few posts.

First, I implemented a few sample events. The contents of these are not that interesting:

Then, I defined a generic interface

This is the interface that will need to be implemented by my subscribers in order to receive events of a particular type. Note, the type of event is set up as a generic type T.

Then, my subscribers need to implement an interface for each Event type they want to receive, however because it is a generic interface, it’s pretty straight-forward:

Note there’s no definition of a ISomeEventSubscriber and a ISomeOtherEventSubscriber interface, we can just use ISubscriber<T> and pass the type in in-place. We just need to implement the necessary overloaded Receive events.

You can see the rest of the code in the associated test project, but the above shows you the main aim. Implementing multiple interfaces, each with a strongly-typed Receive event, without actually having to define each of those interfaces.

So, does it work? Well, at my first attempt, no, it didn’t. No matter what type of Event I passed in, or via what interface, it always invoked the last Receive method.

dunit_generic_interfacesRule of life #37: If it’s a choice between Malcolm having screwed up or the Delphi compiler architects, it’s probably Malcolm’s fault.

Yes, my bad. Barry Kelly eventually pointed out the error of my ways. I’d originally defined the generic Interface with a GUID. Habit, really. However, this meant that both ISubscriber<TSomeEvent> and ISubscriber<TSomeOtherEvent>, and indeed any other interface I defined off this generic interface, would have the same GUID. This combined with the fact that I was using an “as” cast to get the Interface reference from the TMySubscribingObject instance, confused Delphi into always giving me the same Interface reference.

Drop the GUID and drop the “as”, and it all worked beautifully.

In future posts I’ll show the other side of the equation, the Publisher, as well as the Event Broker in the middle. One other nice side-effect of indicating the events a class is interested in, using interfaces in this way, is that the event broker can simply inspect the interfaces implemented by a subscriber to know which events they are interested in subscribing to.

Storing code in a collection : TDictionary and Anonymous Methods

In my earlier post, I mentioned you could use the new generic collection classes in Delphi 2009 to store anonymous methods instead of data. I wanted to try this out so I came up with the scenario of implementing factory classes as an excuse to experiment.

Factories can be a very useful way to centralise the creation logic for classes. Very often you see it when you have a base class and a whole bunch of different descendant classes and you want to do the creation in one place. Let’s say you have a reporting application. You may have a base report and a bunch of descendant reports, and you want to enforce some consistency over property values for the different reports that are set at the time of creation. Having these spread around every different place a report could be created may be error-prone. Alternatively, maybe you want to get away from the massive if…then..else blocks you often see in this situation. A Report Factory can give you one place to make sure all reports get created in the certain way, and also let the client code simply request a report by name and have the correct concrete report class created for them.

Problem is usually this means writing a new factory each time you want this, plus creating factory mapping classes to register each concrete report. This is not only a whole bunch of effort and unnecessary classes, it’s more new code to debug.

Instead, I thought I’d try creating a single factory class, that uses Generics to allow you to change the key used to request an instance, and that uses Anonymous Methods to do the creating so as to avoid the necessity for mapping classes. Sticking with my report scenario above, here’s how I wanted to instantiate it:

Where the first generic parameter is the type of the key I will use to request a report, in this case a string representing the report name, and the second is the base type I want the Factory to return.

Here’s how I wanted to register new concrete implementations:

You simply pass in the key value and the anonymous method that will be invoked to do the creation. Lastly, I want to retrieve a particular instance of my report by calling GetInstance on the factory passing in the key value.

Remember however, the type of the key value and the base type of the returned objects should be configurable via generic parameters.

Here’s the class definition I came up with:

As you can see, TKey is the name of the generic parameter representing the type I want to use to request a concrete instance of the base type specified in TBaseType.  RegisterFactoryMethod lets you register an anonymous method of type TFactoryMethod which as we already discussed will do the creating, and there is a matching UnregisterFactoryMethod to remove a key\method pair. GetInstance is there, taking the generic parameter TKey and returning an instance of the base type. There are also a couple of methods to check if a particular key is already registered and another to return the number of registered keys.

Nothing there is terribly interesting if you’ve already played with generic types. However, for me the interesting part is I’m storing the key/method pairs in a TDictionary<TKey, TFactoryMethod<TBaseType>>.  Storing the anonymous method and the key in the dictionary is pretty straightforward:

and retrieving it and executing it is equally so.

With that, we’ve got a very reusable Factory class, so I should have no excuse for avoiding them in the future. Of course, this is a fairly simplistic implementation, it doesn’t handle pipelining during the creation process for example, but this would be relatively straight-forward to add with more anonymous methods stored in a TList<T> for example.

Anyway, hopefully this little experiment has sparked some thoughts in you. The source for both the class and a client implemented as unit tests is available from my delphi-experiments repository on github.

Meanwhile I’m off to do some more playing. Next post will probably be the Pooling example I mentioned earlier but somehow forgot to post.