Amazon.com Widgets Nick Hodges | A man's got to know his limitations

Even Hints Can Reveal Errors

By Nick at February 23, 2013 15:00
Filed Under: Software Development, Delphi

Introduction

I hope that you all know that when you do a full build on your Delphi project, you should never allow hints and warnings to remain in your code.  Warnings, in particular, are an indication that something is going on that you almost certainly don’t want to be going on.  But what about hints?  Hints can’t really be a problem, can they?

Well, yeah, they can definitely point to something happening that you don’t want to happen – or in the case below, of something not happening that you do want to happen. 

The Situation

Let’s say you are maintaining an older Delphi application and you run across some code that looks like this:

begin
  Screen.Cursor := crSQLWait;
  // A bunch of database code that might make
  // the user wait
  Screen.Cursor := crDefault;
end;

And naturally you think “Oh my, that will never do.  What happens if an exception occurs in that database code! The cursor might be stuck!  That needs a try…finally block around it!”.  And so you do the following:

begin
  Screen.Cursor := crSQLWait;
  try
  // A bunch of database code that might make
  // the user wait
  finally
    Screen.Cursor := crDefault;
  end;
end;

And that’s better, but something is still nagging at you, and it suddenly hits you – "what if the cursor wasn’t actually crDefault to start with?  Shouldn’t you restore the cursor to whatever it was before you started?”  So you are feeling a bit cocky and you proceed with a bit too much haste and you do this:

var
  OldCursor: TCursor;
begin
  OldCursor := Screen.Cursor;
  Screen.Cursor := crSQLWait;
  try
  // A bunch of database code that might make
  // the user wait
  finally
    Screen.Cursor := crDefault;
  end;
end;

But like I said, you are feeling a bit cocky, and you think “I’ll be this is all over the place” and you search for similar code patterns and you are right and you go off and fix this “omission” that is scattered all over your codebase.  Things are great, right? 

Finally you compile and there is a <shudder> hint in your code! 

[dcc32 Hint] Unit5.pas(29): H2077 Value assigned to 'OldCursor' never used

and you’re like “Whaaat?  It’s just a silly hint, who cares!”.  But of course, your conscience is nagging at you, and you remember that Nick told you to not allow any hints or warnings, not even stupid hints like this one, and you suddenly realize that your code has an <another shudder> bug in it and it is not doing at all what you wanted and intended for it to do.

And of course, you fix the subtle bug of forgetting to actually set the cursor back to its original value:

var
  OldCursor: TCursor;
begin
  OldCursor := Screen.Cursor;
  Screen.Cursor := crSQLWait;
  try
  // A bunch of database code that might make
  // the user wait
  finally
    Screen.Cursor := OldCursor;  // <--- forgot this part
  end;
end;

And then you think “Dang, that Nick dude was right!  Hints really can indicate problems”, and you never let another hint slide for as long as you live.

And of course, I should say that I totally made this scenario up, and that I would never, ever, ever do anything like that.  Nope, not me.  Nope.  No way. Neeeever happened.

Flotsam and Jetsam #80

By Nick at February 22, 2013 09:04
Filed Under: Flotsam and Jetsam, Delphi
  • Despite all my slaving over a hot keyboard, bringing you a never ending supply of intellectually stimulating and hopelessly useful content, in the entire history of this website, no one has ever donated to me via PayPal.  And there is a reason for that – the stupid donate button doesn’t work.  Well, I fixed it.  Or at least I think I did. 
  • And now, you can donate Bitcoins to me as well!  Just click on that little blue button on the right that says “Donate Bitcoins”.  Hey, hope springs eternal!
  • I think by now pretty much everyone in the Delphi community knows that Embarcadero has acquired AnyDAC.  I’m pleased by that, and I think you should be, too.  Anyway, it looks like they are going to rename it “FireDAC”.  I like that name.  And according to that link, you’ll be able to download it for XE3.  Just another reason to upgrade to the latest version of RAD Studio XE3. (It appears that this page on the wiki has now been removed.  Hmmm…..)
  • Tim Anderson has an interesting article about cross-platform development and the different strategies a framework can take towards producing a user interface for each platform.  I mention it because he discusses FireMonkey in it. 
  • Jeroen pointed out this cool table that has all the Delphi compiler defines for each specific version.  Nice.

Review of the Mobile Preview Webinar

By Nick at February 21, 2013 17:53
Filed Under: Delphi

I watched the RAD Studio Mobile Preview Webinar today.  Anders O, JT Thomas, Marco, and Sarina DuPont did a very nice job presenting the product, including some pretty cool demos.  Here are my thoughts in my ever-present bullet form.  Everything here is from notes I took during the webinar.

  • First, the webinar was today, and it hasn’t been put up on the web for general consumption yet.  They said that would happen soon.  I’ll make sure to point to it when it is up.
  • Overall, this is very, very impressive.  I really thought it was cool.  It appears that Embarcadero has really made developing for iOS easy and very “Delphi-ish”.  I don’t own any Apple products, but I must confess that this tool might make me jump on the bandwagon (though I am most looking forward to the Android side of things – see below….)
  • The IDE looked great.  The designer works just like the Windows designer you know and love. They showed using FireMonkey in a very nice looking designer with a cool graphic of an iPhone.  You can even choose a “palette” of iPhone 4, iPhone 5, or an iPad and the designer adjusts and looks just like the device.  You can rotate the designer to see how things will render at any orientation. 
  • The styling and controls looked very “iPhone-ish” to me.  I’m not an expert, but it looks like they’ve gone to a large effort to make an iOS-based Fire Monkey app look perfect on an iPhone.  I couldn’t tell exactly how native controls entered into things, but they definitely mentioned that the calendar control and the list box control were native controls.   There were countless styles for the buttons, tabs, and other controls that made everything look like apps on the iPhone/iPad are supposed to look. 
  • This question got asked about 400 times, and the team was very patient in answering it each time.  You need a Macintosh computer to develop and deploy on iOS. I repeat, you need a Mac.  There is no way around this. This isn’t a technical requirement – it’s the rules according to Apple.  They only allow deployment using a Mac and xCode, and so Embarcadero has to honor that.  Further notes in this area:
    • This doesn’t work like Kylix did -- the RAD Studio IDE runs in Windows and Windows only.  It can run in BootCamp or Parallels on the Mac.
    • They said that a MacMini will work fine.  I don’t know much about OS X, but they said that you’ll need at least Lion to run things.
    • Debugging happens via a server on the mac that talks to the IDE over TCP/IP.  You debug in the IDE (on Windows) just like you normally do.
    • Yes, you can develop in Windows on the Mac via a virtual machine, and deploy and run in the same Mac. 
    • You can’t run the simulator on Windows as Apple doesn’t have a simulator that runs on Windows.
    • You can’t run OSX in a virtual machine on Windows because Apple doesn’t allow that – you can only run OSX on Apple hardware.
    • Sarina deployed both to the simulator and her actual device (though her device was emulated on the screen by an app designed to do that – she did hold it up to take a picture and you can see that in the presentation…….)
  • Database access was interesting and appeared to be very much what we’d expect it to be.
    • Marco demonstrated a clientdataset hooking  up to a local file.  Then he demoed the dbExpress controls talking to both SQLite and Interbase ToGo locally – that is, to the DB itself residing on the device.  Or at least that was how I understood it.
    • Having TClientDataset on mobile devices is very cool.  I presume this means that the providers will work and allow you to talk to a DataSnap server.  That could be very powerful and cool.  I can see this being a cool thing for sharing apps between phones and the web.
    • No mention of how AnyDAC will enter into things.
  • A bunch of people asked about Android development, including me.
    • JT said that it would be available later this year.  Same with C++ for both iOS and Android.
    • He said the goal was to have the same exact FireMonkey code compile and run on iOS and Android.  That would be very, very cool.  The question that I had was about styling – but I presume there is a way to dynamically change the styling depending on the OS.  I hope so, as I don’t want an Android app looking like an iOS app, or vice-versa.
    • There were a lot of folks asking about this – I personally am really looking forward to doing Android development with Delphi.  A lot.
  • The compiler is Embarcadero’s – no more FreePascal involved anywhere in the tool chain.
  • Pricing, packaging and all that kind of stuff will come later.  You can get on the beta if you are an XE3 customer.  Just another reason to buy Delphi XE3
  • Did I mention that you need a Mac to develop for iOS?
  • Further thoughts:
    • I’m anticipating that there will be many Delphi-built apps showing up on Apple’s AppStore in the coming year, including some cool DataSnap-based apps.
    • The mobile development space has finally come alive, and Delphi’s right there on the leading edge.  Xamarin has recently announced a cross-platform solution for Android and iOS, but they don’t provide a UI framework.  FireMonkey is right there with everything you need.  This should be a very compelling and competitive offering from Embarcadero.    And they appear to be doing this just at the right time as things really get hopping in the mobile tooling marketplace. 
    • For once, Delphi will be doing something that Microsoft will never, ever do.  Microsoft will never provide tools for developing for iOS and Android.  Or at least I can’t conceive of them ever doing it.  So this is green fields for Delphi.  Competitors are broader and smaller – HTML5 and JavaScript (for which they have an excellent tool in HTML5 Builder) and Xamarin appear to be the main competitors at this point.  This is a nice change and a great opportunity for Embarcadero to get away from the head-to-head competition with Microsoft. 

Again, I was very impressed overall.  The demos were pretty cool, FireMonkey looks really good on the iPhone, and the database access looks like it’s exactly what we Delphi developers would expect.  This is a cool opportunity for Delphi developers.

Delphi and the Factory Pattern: Simple Factory

By Nick at February 17, 2013 07:54
Filed Under: Delphi, Patterns

I’m currently reading “Head First Design Patterns”, and am finding it very useful and educational.  One problem, though – it’s all in Java.  So I thought that as part of the exercises, I’d translate the code to Delphi.  And also as part of my learning process, I thought it would be a good idea to post an article about each of the patterns.  I also strongly encourage you to buy the book and read it for yourself.

Let me be clear – I’m not doing much more than reproducing the demos in the book.  My purpose is to make the book more approachable for Delphi developers.  The result isn’t always the perfect way to do the pattern since the samples from the book are designed to be as simple as possible to illustrate the point.  I’m very aware that there are better ways to implement the patterns than are shown here. 

The chapter on the Factory Pattern in HFDP is pretty long, and divided into three main sections.  I’ll do a post on each section: General discussion and the Simple Factory, the Factory Method Pattern, and the Abstract Factory. 

General Discussion

Regular readers of this blog will know that I’m a huge proponent of Dependency Injection.  I’ve gone so far as to say that Dependency Injection should just be a way of life for a developer.  If you aren’t following the principles of Dependency Injection, you aren’t writing good, clean code.

One of the basics of Dependency Injection is the notion that the creation of objects is a “single responsibility” and that your class shouldn’t take on that responsibility because it, too, should only have a single responsibility.  If a class is taking care of its responsibility and creating the things that it needs, it is doing too much. The notion of creating things is a big responsibility, and not something that should be taken lightly.  Creating things should be done by classes whose specific job it is to create things. 

And one of the basic tenets of development is to code against abstractions and not concrete implementations.  Well, every time you call Create means you are coding against a concrete implementation.  That should be avoided as much as possible, right?  If you press all your Create calls back to a factory, then you can minimize the number of calls to Create and keep them well sequestered away. 

Thus we have the Factory Pattern.  The job of the factory pattern is to remove the worry and concern of creating things and make it happen pretty much automatically.  A while back I even wrote a blog post entitled “Life is Too Short to Call Create”.  In other words, the main job of the Factory Pattern is to hide via encapsulation the process of creating something.  Factories are the main places where your calls to Create should happen.

The Simple Factory

HFDP uses the example of a pizza store to show how a factory might be used to create pizzas.  So following along with their example, we can declare a pizza class and some specific types of pizzas:

type

  TSimplePizza = class(TObject)
    procedure Prepare;
    procedure Bake;
    procedure Cut;
    procedure Box;
  end;

  TCheesePizza = class(TSimplePizza );
TPepperoniPizza = class(TSimplePizza );
TVeggiePizza = class(TSimplePizza );
...

{ TPizza }

procedure TSimplePizza .Bake;
begin WriteLn('Bake the pizza'); end; procedure TSimplePizza .Box;
begin WriteLn('Put the pizza in a box'); end; procedure TSimplePizza .Cut;
begin WriteLn('Cut the pizza'); end; procedure TSimplePizza .Prepare;
begin WriteLn('Prepare the Pizza'); end;

There’s nothing special here, just some classes that represent pizzas.  The pizzas know how to be prepared.  Now, of course, we have to have a place to make our pizzas, so we declare a pizza store that knows how to take a pizza order:

 TSimplePizzaStore = class
    function OrderPizza(aPizzaType: string): TSimplePizza;
  end;

...

function TPizzaStore.OrderPizza(aPizzaType: string): TSimplePizza;
begin
  if aPizzaType = 'cheese' then
  begin
    Result := TCheesePizza.Create;
  end else
  begin
    if aPizzaType = 'pepperoni' then
    begin
      Result := TPepperoniPizza.Create;
    end else
    begin
      if aPizzaType = 'veggie' then
      begin
        Result := TVeggiePizza.Create;
      end else
      begin
        raise Exception.Create('I don''t know what kind of pizza that is: ' + aPizzaType);
      end;
    end;
  end;

  Result.Prepare;
  Result.Bake;
  Result.Cut;
  Result.Box;
end;

Now that works great.  But what happens when you want to add a pizza?  You have to change the OrderPizza method.  But what if you want to do something else to the pizzas?  Say you want to use the pizza class to program your point of sale, and provide pricing and descriptions?  You’d have to do another one of those big ugly if statements there as well, resulting in two places to change the code for a new pizza.  And of course, if you came up with a delivery scheme, that might be a third place. 

The code for creating the pizzas is something that seems likely to change and be duplicated, and so that screams out “Encapsulate me!”.  This is a good example of a class trying to do two things:  order a pizza and create a pizza.  It’s not doing one thing like all good classes that follow the Single Responsibility Principle should.  When a class tries to do two things, it has two reasons to change, and when a class has more than one reason to change, it becomes less useful, more coupled, and more complicated to change. 

So instead of doing the pizza creation right in the OrderPizza method, let’s create a class whose sole job is to create the correct pizza on demand.  This class will be a “simple factory” class, and it will take the pizza creation code out of the OrderPizza method and put it into its own method:

type
  TSimplePizzaFactory = class
    function CreatePizza(aPizzaType: string): TSimplePizza;
  end;
...

{ TSimplePizzaFactory }

function TSimplePizzaFactory.CreatePizza(aPizzaType: string): TSimplePizza;
begin
  if aPizzaType = 'cheese' then
  begin
    Result := TCheesePizza.Create;
  end else
  begin
    if aPizzaType = 'pepperoni' then
    begin
      Result := TPepperoniPizza.Create;
    end else
    begin
      if aPizzaType = 'veggie' then
      begin
        Result := TVeggiePizza.Create;
      end else
      begin
        raise Exception.Create('I don''t know what kind of pizza that is: ' + aPizzaType);
      end;
    end;
  end;
end;

TSimplePizzaFactory is pretty straight-forward:  it creates the kind of pizza you ask it for.  Simple.

Now that we have a class that has the sole responsibility for creating pizzas, we can simplify the TSimplePizzaStore class, passing it a TSimplePizzaFactory:

  TSimplePizzaStore = class
  private
    FFactory: TSimplePizzaFactory;
  public
    constructor Create(aPizzaFactory: TSimplePizzaFactory);
    destructor Destroy; override;
    function OrderPizza(aPizzaType: string): TSimplePizza;
  end;

...

{ TSimplePizzaStore }

constructor TSimplePizzaStore.Create(aPizzaFactory: TSimplePizzaFactory);
begin
  inherited Create;
  FFactory := aPizzaFactory;
end;

destructor TSimplePizzaStore.Destroy;
begin
  FFactory.Free;
  inherited;
end;

function TSimplePizzaStore.OrderPizza(aPizzaType: string): TSimplePizza;
begin
  Result := FFactory.CreatePizza(aPizzaType);

  Result.Prepare;
  Result.Bake;
  Result.Cut;
  Result.Box;
end;

The new pizza store takes the pizza factory as a parameter on its constructor and stores it.  Then the OrderPizza method uses that factory to create the pizza instead of doing the creation itself.  That unpleasant if statement is neatly hidden away in the TSimplePizzaFactory class where it can be re-used by anyone that needs it.  The pizza store just knows that the factory will create the right pizza for it.

So tying it all together, the following code will create a pepperoni pizza:

procedure MakeSimplePizza;
var
  SimpleStore: TSimplePizzaStore;
begin
  SimpleStore := TSimplePizzaStore.Create(TSimplePizzaFactory.Create);;
  try
    SimpleStore.OrderPizza('pepperoni');
  finally
    SimpleStore.Free
  end;
end;

Things to Note

Okay, here are some things to note about all of this:

  • Sure, the code for creating pizzas didn’t really change – we still have that big ugly if statement.  But it is nestled away in a single class – isolated, decoupled, and ready for use anywhere.  It is also a single place to add new pizza types.
  • The code above simply calls Create on the factory as a direct parameter in the constructor for the pizza store.  The pizza store then owns, and thus frees, the factory. 
  • Strictly speaking, this use of a simple factory isn’t a pattern.  Or at least that is what the folks in HFDP argue.  I’m not sure that I agree with them.  This is a pretty simple yet effective pattern in my mind.
  • Now, remember, I’m just implementing the basics of the code in the book.  There are some clear improvements that could be made to this code, and indeed the next two blog articles will cover much of those improvements, but I’ll mention a couple here:
    • First, both TSimplePizza and TSimplePizzaStore (and even TSimplePizzaFactory) could implement interfaces, enabling us to code against interfaces.
    • The CreatePizza method on TSimplePizzaFactory could have been declared as a class static method, making it so that you don’t even have to create an instance of the factory.
    • Passing in the pizza type as a string isn’t perfect either – it should be an enumerated type
  • The code for this project can be found on BitBucket.

Conclusion

So that’s the first look at a simple factory – a class whose job is to create things for you instead of you creating them yourself.  That’s the heart of what Dependency Injection is all about, and it’s a critical part of making sure that your code is as loosely coupled as possible.

Flotsam and Jetsam #79

By Nick at February 14, 2013 15:30
Filed Under: Delphi, Flotsam and Jetsam
  • Today is Delphi’s 18th Birthday.  I'll always wear it as a badge of honor that I was there at the launch at SD ‘95 in the Moscone Center.  Quite a privilege.  Thanks to everyone who has made Delphi such a great tool to use.
  • I am signed up for the RAD Studio Mobile Preview Webinar.  Are you going to attend?
  • Colin Johnsun reports that the JVCL has migrated over to use GitHub.  I consider this good news.  While I prefer Mercurial, Git is a Distributed Version Control System, and DVCS’s are vastly superior to server based systems like SVN.  First off, they are designed to branch and merge with ease, meaning that coordinating development and contributing changes is way, way easier (the process of “pull requests” that Colin talks about).  If you aren’t using a DVCS, you don’t know what you are missing.
  • In case anyone cares, my entire tweet archive is now online here on my site.  Here’s the tweet that started it all.

Flotsam and Jetsam #78

By Nick at February 09, 2013 10:39
Filed Under:

Flotsam and Jetsam #77

By Nick at February 06, 2013 16:43
Filed Under: Delphi, Flotsam and Jetsam, Tweet Expansion

Delphi and the Decorator Pattern

By Nick at February 04, 2013 09:23
Filed Under: Delphi, Patterns

I’m currently reading Head First Design Patterns, and am finding it very useful and educational.  One problem, though – it’s all in Java.  So I thought that as part of the exercises, I’d translate the code to Delphi.  And also as part of my learning process, I thought it would be a good idea to post an article about each of the patterns.  I also encourage you to buy the book and read it for yourself.

Let me be clear – I’m not doing any more than reproducing the demos in the book.  I’m very aware that there are better ways to implement the patterns than are shown here.  The idea is to learn the pattern, not optimize the code.

Continuing on through HFDP, the next pattern we’ll cover is the Decorator Pattern. 

One of the themes of the book is to make your code as flexible as possible at runtime, and to design your code to prefer runtime flexibility over compile time flexibility.  Anytime you determine something at compile-time, you lock that feature in to your code.  It can’t be changed at runtime. 

Inheritance is a pillar of OOP, but it is a compile-time construct.  Inheritance is powerful, but inflexible at runtime.  You have the classes you have, and they can’t be altered or changed once you set them in the stone that is compiled code. If you are trying to come up with differing combinations to decorate each class, you can end up having a huge number of descendent classes which can become difficult to manage and maintain.  Changes to one of the features means any number of descendants might need to change as well. 

The decorator pattern is a way of circumventing these limitations, and providing the power of inheritance while at the same time providing run-time flexibility.  It actually uses some simple inheritance to “wrap up” a given class and provide additional functionality without having to change the original class. 

Here is the formal definition from Wikipedia:  The Decorator Pattern attaches additional responsibilities to an object dynamically.  Decorators provide a flexible alternative to sub-classing for extending functionality.  You can read more about the pattern on Wikipedia.

It’s actually pretty straight-forward.  Here’s what you do:

  • First, you start with the notion of a class that needs to be decorated.  It becomes the “base” class.  The example in HFDP is that of a coffee drink.  They coffee itself – a beverage – is the base class which can be any number of different coffee types. Each will be decorated with various flavorings, etc., such as milk, mocha, and cream whip. 
  • Then you create a single descendant that will be the base decorator class.  That class will take as a property an instance of the original base class.  The base decorator should have a constructor that takes the original base class as a parameter. 
  • Next, you create concrete instances of decorators that override the necessary methods and properties of the base decorator class.
  • From there, you can start with the base class, and then chain together as many decorators as you want.

Okay, let’s take a look at that in code.  Here is the base class, TBeverage:

type
  TBeverage = class
  private
    FDescription: string;
  protected
    function GetDescription: string;  virtual;
    procedure SetDescription(const Value: string);
  public
    function Cost: Double; virtual; abstract;
    property Description: string read GetDescription write SetDescription;
  end;

The base class is abstract.  It has two properties, with the Cost property being read-only and having an abstract, virtual getter. 

TBeverage is the base class for the beginning of the wrapping process.  We create descendants that will form the base class described above.  These classes override the Cost method, providing their own prices.  They will be the starting point for decorating.  In our case, we’ll create specific base coffee types that can be wrapped:

 TEspresso = class(TBeverage)
    constructor Create;
    function Cost: Double; override;
  end;

  THouseBlend = class(TBeverage)
    constructor Create;
    function Cost: Double; override;
  end;

  TDarkRoast = class(TBeverage)
    constructor Create;
    function Cost: Double; override;
  end;

  TDecaf = class(TBeverage)
    constructor Create;
    function Cost: Double; override;
  end;

The interesting part comes in the base decorator class:

  TBeverageDecorator = class(TBeverage)
  private
    FBeverage: TBeverage;
  public
    constructor Create(aBeverage: TBeverage);
    destructor Destroy; override;
  end;

TBeverageDecorator does three things.  One, it descends from TBeverage. Two, it gets another instance of TBeverage from its constructor in order to “wrap” itself around the starting base class.  And three, the destructor ensures that the internally stored instance gets freed properly when that time comes. 

Since TBeverageDecorator is itself a TBeverage, you can continue wrapping the previous result in a new one, decorating the decorator as it were.  In addition, it will have the exact same interface as the base beverage class, so it can act like a beverage because, well, it is one.   

As for classes that do the decorating, they will descend from TBeverageDecorator:

  TMocha = class(TBeverageDecorator)
  protected
    function GetDescription: string; override;
  public
    function Cost: Double; override;
  end;

  TSoy = class(TBeverageDecorator)
  protected
    function GetDescription: string; override;
  public
    function Cost: Double; override;
  end;

  TWhip = class(TBeverageDecorator)
  protected
    function GetDescription: string; override;
  public
    function Cost: Double; override;
  end;

Each of these classes does two things. 

First, they override the getter for the Description property.  They do it in an interesting way.  Since they are decorating the base Beverage, they assume that they are “additive”, that is that they will be adding on to the base description.  The TMocha.GetDescription method looks like this:

function TMocha.GetDescription: string;
begin
  Result := FBeverage.GetDescription + ', Mocha';
end;

This method grabs the description from the class that it is wrapping and adds on a comma and its own description.

Second, the Cost method is overridden to add the cost to the price of the class that it is decorating.

function TMocha.Cost: Double;
begin
  Result := 0.20 + FBeverage.Cost;
end;

So, now we have a bunch of types of coffee – the base classes --and a bunch of flavors to wrap around those classes and themselves.  Let’s put it all together:

First, we’ll create a routine to write out the coffee type to the console:

procedure OutputBeverage(aBeverage: TBeverage);
begin
  WriteLn('A ', aBeverage.Description, ' costs ', '$', Format('%2f', [aBeverage.Cost]));
  WriteLn;
end;

Then, we’ll create an Espresso and wrap it with Double Mocha and Whip:

procedure OrderCoffee;
var
  Beverage: TBeverage;
begin
  Beverage := TEspresso.Create;
  try
    Beverage := TMocha.Create(Beverage);
    Beverage := TMocha.Create(Beverage);
    Beverage := TWhip.Create(Beverage);
    OutputBeverage(Beverage);
  finally
    Beverage.Free;
  end;
end;

This will build the description and calculate the correct price, and result in:

 

 

 

Another way that you can create a coffee is by simply nesting each decorator in the constructor of the previous one.  This method actually provides a coding representation of how each decorator wraps up the previous one:

  // Alternate way to call the same thing as above....
  Beverage3 := TWhip.Create(TMocha.Create(TMocha.Create(TDarkRoast.Create)));
  try
    OutputBeverage(Beverage3);
  finally
    Beverage3.Free;
  end;

The complete implementation of our little coffee shop application can be found on BitBucket.  That code should be a faithful representation of the final project in the book.  And I have mentioned that I strongly recommend that you buy the book, right?

So, to summarize:

  • The whole thing starts with base class that will be decorated.
  • The decorator classes both descend from and maintains a reference to that base class. This means that they will have the same interface, yet the reference will allow composition instead of inheritance. 
  • One or more decorators can be wrapped around the base class and each other to produce a single entity. 
  • The Decorator can augment the behavior of the class it is wrapping.  We see this with the Cost and Description properties. 
  • You can dynamically decorate objects at anytime, enabling you to create any combination of decorators without having to create a descendent class for each.
  • Decorators allow you to extend behavior of existing classes without needing to modify existing code. 

There are some problems here – you can end up with a lot of little classes to manage; that might bother some people.  Use of decorators can lead to complex code and implementations – use them with care. 

However, the basic idea is to simplify and add flexibility to your code over a complex inheritance model. In addition, it makes it easier to build a single instance at run-time of complicated combinations of features or items.

Next up:  The Factory Pattern

Delphi and the Observer Pattern

By Nick at January 27, 2013 20:46
Filed Under: Delphi, Patterns, Software Development

I’m currently reading Head First Design Patterns, and am finding it very useful and educational.  One problem, though – it’s all in Java.  So I thought that as part of the exercises, I’d translate the code to Delphi.  And also as part of my learning process, I thought it would be a good idea to post an article about each of the patterns.  I also encourage you to buy the book and read it for yourself.

The first real pattern that the book shows is the Observer Pattern.  You should use the observer pattern when you have one object that notifies other objects when events occur.    Or more succinctly, use it when you have an object that needs to notify other objects about stuff that happens. 

HFDP uses the example of a simple weather station that gathers data about the weather.  Each time the weather station takes readings, it needs to update the views of that weather. The weather station reports on Temperature, Humidity, and Pressure.  There are three views that the application provides – current conditions, statistics about the weather, a simple forecast.

The idea here is that the weather station is the subject – it is the object being observed and doing the notifying.  The different displays for the information are the observers – they watch what happens on the weather station and update themselves based on the notifications that they receive from the weather station.  Another way to look at it is that the weather station is a publisher of information, and the displays are subscribers.

The formal definition given for the Observer Pattern goes like this: The Observer Pattern defines a one-to-many dependency between objects so that when one object changes state, all of its dependents are notified and updated automatically. 

But when it comes time to implement this, the temptation is to simply embed the displays inside of a method of the weather station.  You might create classes for each view, instantiate them in the weather stations constructor, and then simply update the views in a method called MeasurementsChanged.

But of course if you do this, you are breaking some of the base design rules.  First, you’d be coding against an implementation instead of against an interface.  Second, you’ve made it really hard to add a new data display should that become necessary.  Displays are hard-coded into the weather station and can’t be added or removed at runtime.  If we do want to add more displays, we’d need to modify the weather station itself.  Or, put more succinctly, the weather station and its displays are tightly coupled to each other.  And if you know one thing about me, I abhor tight coupling.  And you should too.

In any event, there is a better way – the Observer Pattern.  As noted above, observer pattern consists of a Subject that is monitored by Observers.   We’ll implement a very simple version of the observer pattern. The first thing we will do of course, is declare two interfaces:

type
  IObserver = interface
  ['{69B40B25-B2C8-4F11-B442-39B7DC26FE80}']
    procedure Update(aTemperature: integer; aHumidity: integer; aPressure: Double);
  end;

  ISubject = interface
  ['{A9240295-B0C2-441D-BD43-932AF735832A}']
    procedure RegisterObserver(aObserver: IObserver);
    procedure RemoveObserver(aObserver: IObserver);
    procedure NotifyObservers;
  end;

The first interface is IObserver, which the observing classes will implement.  In it they’ll be updated with all the weather information that the weather station has for us.  The second is ISubject, which will be implemented by the weather station.  It takes three methods, two for handling the connecting and disconnecting of IObservers, and the third for doing the actual notification to the observers. 

The first implementation we’ll look at is the Weather Station.  Here is its implementation declaration.

type
  TWeatherData = class(TInterfacedObject, ISubject)
  private
    FTemperature: integer;
    FHumidity: integer;
    FPressure: double;
    FObserverList: TList<IObserver>;
    function GetTemperature: integer;
    function GetHumidity: integer;
    function GetPressure: double;
  public
    constructor Create;
    destructor Destroy; override;
    procedure SetWeatherInformation(aTemperature: integer; aHumidity: integer; aPressure: double);
    procedure RegisterObserver(aObserver: IObserver);
    procedure RemoveObserver(aObserver: IObserver);
    procedure NotifyObservers;
    procedure MeasurementsChanged;
    property Temperature: integer read GetTemperature;
    property Humidity: integer read GetHumidity;
    property Pressure: double read GetPressure;
  end;

The plumbing for managing the weather implementation is all what you’d expect.  The interesting part, of course, is the implementation of ISubject.  Internally, it uses a TList<IObserver> to manage all the observers that get registered with it.  The RegisterObserver and RemoveObserver methods simply insert and remove, respectively, instances of classes that implement the IObserver interface.

The real action occurs in the NotifyObservers method.  We’ll get to that in a second.  First, though, let’s take a look at the observers.  Since all the displays are very similar, this is a good time to use good old-fashioned inheritance to declare a base class that implements the needed functionality, and then have descendent classes that do the work of providing the specified displays.  Here, then, is the interface for TWeatherDataDisplay:

TWeatherDataDisplay = class(TInterfacedObject, IObserver, IDisplay)
  private
    FSubject: TWeatherData;
    FTemperature: integer;
    FHumidity: integer;
    FPressure: Double;
  public
    constructor Create(aWeatherData: TWeatherData);
    destructor Destroy; override;
    procedure Update(aTemperature: integer; aHumidity: integer; aPressure: Double); virtual;
    procedure Display; virtual; abstract;
  end;

TWeatherDataDisplay has fields to keep track of the current weather information.  It’s descendants can do with it as they please.  It also implements the IDisplay interface so that it can report out what it has to say.  The Update method will allow the Subject – in this case the weather station – to update the displays.  Update is a virtual method, by the way, so that descendants can do different things with the incoming information. 

Okay, so let’s look under the hood.  The weather station can accept and remove IObserver implementers at runtime.   implements the NotifyObservers method as part of the ISubject interface.  It gets called whenever the weather information changes.  It is implemented as follows:

procedure TWeatherData.NotifyObservers;
var
  Observer: IObserver;
begin
  for Observer in FObserverList do
  begin
    Observer.Update(Temperature, Humidity, Pressure);
  end;
end;

This is pretty simple – it merely enumerates over each item in the observer list and calls the Update method, passing along the new weather data.  The base class stores the information, and its descendants process it.

The real “work” gets done when the weather station updates the temperature data and calls NotifyObservers:

procedure TWeatherData.SetWeatherInformation(aTemperature, aHumidity: integer; aPressure: double);
begin
  FTemperature := aTemperature;
  FHumidity := aHumidity;
  FPressure := aPressure;
  MeasurementsChanged;
end;

The entire implementation of our little weather station can be found as part of my demo code on BitBucket.org.

So all of this comes together in a method to create a weather station and add observers:

procedure DoWeatherStation;
var
  WeatherStation: TWeatherStation;
  CurrentDisplay: IDisplay;
  ForecastDisplay: IDisplay;
  StatsDisplay: IDisplay;
begin
  WeatherStation := TWeatherStation.Create;
  try
    CurrentDisplay := TCurrentConditionsDisplay.Create(WeatherData);
    ForecastDisplay := TForecastDisplay.Create(WeatherData);
    StatsDisplay := TStatisticsDisplay.Create(WeatherData);;
    WeatherStation.SetWeatherInformation(70, 55, 28.90);
    WeatherStation.SetWeatherInformation(68, 59, 28.96);
    WeatherStation.SetWeatherInformation(35, 66, 27.40);
    WeatherStation.SetWeatherInformation(55, 55, 27.40);

  finally
    WeatherStation.Free;
  end;
end;

Here are some interesting things to note:

  • This code doesn’t write anything to the console.  All of that is done by the display objects that get registered as observers.  Each observer is registered, and the code pretty much forgets about them.  To the weather station, they are merely IObserver interfaces, and the only thing you can do to an IObserver is call it’s Update method.  From the Weather Station’s perspective, there’s nothing else to it.
  • Four calls to SetWeatherInformation result in for reports from all of the updates to the temperature information.
  • Once you have a reference to a TWeatherStation, you can add or remove displays at runtime.
  • TWeatherStation doesn’t know anything about Weather displays – it only knows about IObservers.  This means that you could have observers that do other things besides being Weather Displays.  You could simply store the weather data, or anything else at all.  For instance, you could create a TWriteWeatherInfoToDatabase class that implements the IObserver interface.  The Weather Station itself neither knows nor cares.  IObservers are under no obligation to do anything specific with the data passed to them. 
  • We can change the observers anytime we want without altering the Subject.  We can add new observers, too.  Basically, observers and subjects are very loosely coupled, and either can be changed, altered, updated, and added to without having to worry about changing the other. 

So that should be a quick rundown on how the observer pattern works.  The obvious weakness here is that our IObserver interface is very specific to weather data.  You can create your own interface for your specific implementation.  The pattern remains the same no matter how the IObserver interface is designed.  This is obviously a good place for generics to enter the picture, and in fact, the Delphi Spring framework implements a generic IObservable<T> interface and implementing class.

So in summation, the Observer pattern ensures that publishing classes (subjects) can communicate updates to their subscribing (observer) classes with very loose and flexible coupling.  Observers can be updated and removed at runtime.  Adding observers requires no change to subjects.  Subjects don’t know much at all about what the observers are up to.  It’s all very easy and elegant and loosely coupled – just like you want it.

Next up – the Decorator Pattern.

Flotsam and Jetsam #76

By Nick at January 26, 2013 13:11
Filed Under: Delphi, Flotsam and Jetsam
  • There are a lot of cool things that an IDE could do, but it’s getting to the point where my one top feature for the IDE is the automatic addition of interface methods.  If I declare a class that implements a given interface, the IDE should automatically fill those in for me.  That would be really sweet.  This feature is in third place in the IDE section of Delphi’s User Voice page. Feel free to vote for it.
  • The fine folks at TMS Software are organizing a Delphi/TMS day in the Benelux region – if you are around you should go.  They  have early bird registration until 01 March 2013.
  • Embarcadero has announced the coming of Delphi for iOS.  I’m not an iOS guy – I’m waiting for the Android stuff.  I don’t have an Apple device at all, and you need one to develop on.  (There’s no iOS emulator or simulator for Windows – everything has to run on Apple hardware/software…) so it’s not of any use to me at the present.  However, I’ll be keeping a close eye on this, as I’ll be developing for Android as soon as I can with Delphi, and I suspect I’ll eventually be wanting the results of that to run on iOS as well.  After all, that is one of the promises of FireMonkey – to have a single codebase that runs on Windows, iOS, and Android.  In any event, no one can say that Delphi isn’t alive and kicking.  The new offering includes a Delphi compiler for ARM chips, which is pretty exciting if you’ve been wanting Delphi to branch out.  And the best part is you can get early access to the beta if you buy XE3.
  • Looks like David I has something up his sleeve this year on Delphi’s birthday
  • Delphi Developer Days is back this year – with two dates in Europe and just one in the US (Chicago).  Cary has all the details.  I’ve been to a couple of the events, and they are really fun and well worth the time.  If you can make it, I strongly recommend the event.  Dr. Bob is certainly a more than able replacement for Marco.  With no Delphi Live in the future, this is really the only US conference where Delphi folks can gather.  I’d like to see them add an East Coast date in the US.  Otherwise, I’ll try to get to the Chicago event. 

Flotsam and Jetsam #75

By Nick at January 20, 2013 12:44
Filed Under: Delphi, Flotsam and Jetsam
  • Now here’s a blog after my own heart:  LooseCouplings.com  Sadly, it hasn’t been updated in a while, and there are only a few articles, but what is there is really good.  There are four or five articles about Dependency Injection (particularly about how it doesn’t necessarily mean using a DI Container…..) and we’d all do well to read and heed. Thanks to Stefan Glienke for pointing me to it.
  • RAD Studio won the “Top Innovator: Developer Tools” at the Developer Week Conference.  Nice thing to see.
  • I wanted to strengthen my SQL skills, so I decided to give Head First SQL a try.  It was my first foray into the world of the Head First Series, and I was pleasantly surprised. I wasn’t quite sure what to expect, but what I got was a great review/tutorial on SQL.  The examples were simple but to the point, the style a touch irreverent but enjoyable, and I actually did, and learned from, the exercises.  Now I’m working on Head First Design Patterns which so far is the same: excellent, interesting, and attention-holding. I do believe that I'll seek out Head First titles in the future if I want to learn something new.
  • I’d like to put in another plug for the Google Plus Delphi Developers Community.  We’ve been having a lot of fun over there – or at least I have, maybe the rest of the folks are sick of me.  Winking smile  In any event, please stop by and participate. 
  • Shameless Plug of the WeekSign up for Sprint cell phone service.

Flotsam and Jetsam #74

By Nick at January 13, 2013 21:56
Filed Under: Delphi, Flotsam and Jetsam
  • A while back I wrote a “How Not To Code” about not using Booleans as method parameters.  This line of real-world code that I ran across today -- myMonster.Run(cSourceStateLicenseWebNew, '1', '', False, False); -- is a perfect example of why this shouldn’t be done.  Who the heck knows what those last two parameters mean?
  • Does anyone know if that is real Chinese they speak in Firefly?
  • I don’t know if this is good or bad, but apparently I’ve visited StackOverflow on 1001 distinct days.  Yikes. (Maybe more by the time you read this….)
  • This is a really nice article on attributes by Francois Piette. I’m bummed because he used the example that I was going to use in my book.  Anyone got any better ideas?
  • Okay, I did a little more research on Arduino vs. Raspberry Pi, and I think I’m going to start with the Arduino. It seems more “science project-y” whereas the Raspberry Pi seems more like a complete computer solution.  Both sound great, but I’m more interested in the “controlling something” aspect rather than the “use all that small but powerful computing power”.  I think the Arduino would provide more stuff for me to do with my kids in terms of “making it all come alive”.  That’s kind of what I’m interested in, really – the “Mr. Science” kind of stuff.  Thanks to you all for the feedback.
  • I never talk much about Lazarus/FreePascal because I don’t use it and I’m not much interested in it, but it is starting to move more to the center of my radar as apparently you can use it to program a Raspberry Pi.  In fact, our friend Jeff Duntemann has set up a Raspberry Pi as a “regular” computer, and is using Lazarus to write code for it.  Not only that, he’s working on rewriting his classic “Borland Pascal from Square One” for Free Pascal, the current version of which you can download as a PDF.  He also reports that he’s doing a book on Lazarus.  It’s always good to see activity in the world of Pascal and Delphi Programming. Now if we could just get Delphi for Arduino, I’d be in heaven.  Winking smile   
  • I for one welcome our new drone overlords.

Enumerating and the for…in Loop

By Nick at January 12, 2013 15:05
Filed Under: Delphi, Software Development

One of those fun little issues in our business is trying to figure out the difference between iterating and enumerating.  This StackOverflow answer does a pretty good job of explaining it.  Iterating is doing something – usually a series of steps – over and over again.  Enumerating is going over each item in a given collection.  A subtle difference, sure.  One usually iterates when enumerating. 

Okay, so enumerating is going over each item in a collection.  IEnumerable can enumerate over the items in a collection as we saw in my last article.  But you can enumerate over other things as well.  For instance, in Delphi, you can use the for…in statement to enumerate over the characters in a string. 

But this makes me wonder:  how does something become, well, enumeratable?  How do you make something so that you can use with the for…in statement? 

Well, it’s pretty easy.  The rules for Delphi are simple:

  • To create a class or record to enumerate, it must provide a method called GetEnumerator() which in turn needs to be a function that returns a class, an interface, or a record that is an enumerator.
  • To be returned as an enumerator, that class, record, or implemented interface needs to have the following:
    • A method called MoveNext that returns a Boolean indicating whether the end as been reached or not
    • A read-only property called Current that indicates the item that is currently being “looked at” as the enumeration occurs. 

So, at this point, a simple demo would be helpful, eh?

You can already enumerate the characters in a string, but it’s a simple example, and so the following example implements this easy to understand enumeration on a string:

TForInDemoClassEnumerator = class
  private
    FString: string;
    FIndex: integer;
  protected
    function GetCurrent: Char; virtual;
  public
    constructor Create(aString: string);
    function MoveNext: Boolean;
    property Current: Char read GetCurrent;
  end;

TForInDemo = class
  private
    FTheString: string;
    procedure SetTheString(const Value: string);
  public
    constructor Create(aString: string);
    function GetEnumerator: TForInDemoClassEnumerator;
    property TheString: string read FTheString write SetTheString;
  end;

 

This code declares two classes.  The first class is the enumerator – the class that does the work of  moving over each item, and which will be returned by the call to GetEnumerator.  The second is the class that will be enumerated.  Notice, too, that TForInDemoClassEnumerator has the read-only property Current with the reader GetCurrent and MoveNext methods.  The TForInDemo class has a call to GetEnumerator that returns an instance of TForInDemoClassEnumerator

First let’s look at TForInDemoClassEnumerator.  You create it by passing the constructor the item to be enumerated – in this case a string.  Hence, the constructor:

constructor Create(aString: string);

Here is the implementation of the MoveNext method:

function TForInDemoClassEnumerator.MoveNext: Boolean;
begin
  Result := FIndex < FString.Length;
  if Result then
  begin
    Inc(FIndex);
  end;
end;

This code does two things.  First, it sets the result. The function returns True if the enumerator is able to move to the next item, and False if it has reached the end of the items to be enumerated.  In this case, it merely checks to see the index is before the length of the string.   If the end has not yet been reached, it just increases the FIndex field.  So it’s job here is merely to move the index along, and report if the end has been reached.

The actual item itself is returned by the GetCurrent method, which is self-explanatory:

function TForInDemoClassEnumerator.GetCurrent: Char;
begin
  Result := FString[FIndex];
end;

And that is it for the enumerator.  It’s pretty simple.  But we’ll soon see that you can do some cool things with these enumerators because you have complete control over how they return the data that they are enumerating over.

The next step is to see how the actual class to be enumerated provides its enumerator to the compiler.  When the compiler builds the for…in loop construct, it looks at the in part of the construct and thinks “Hey, I need an enumerator here, so I’ll call GetEnumerator”.  If the item in question indeed has a method called GetEnumerator, it calls it, and all is well.  If not, the compiler raises an error because the type in the in part of the for…in loop isn’t enumeratable. 

But of course, our TForInDemo class has such a method, and it is quite simple:

function TForInDemo.GetEnumerator: TForInDemoClassEnumerator;
begin
  Result := TForInDemoClassEnumerator.Create(FTheString);
end;

It merely creates and returns an instance of our enumerator, passing it the string value it is storing for the purpose of enumerating.   Pretty easy and straight forward, really.

Now that we’ve created all these classes, you can run the following code:

procedure DoStuff;
var
  ForInDemo: TForInDemo;
  C: Char;
begin
  ForInDemo := TForInDemo.Create('HelloWorld');;
  try
    for C in ForInDemo do
    begin
      Write(C, ',');
    end;
    WriteLn;

  finally
    ForInDemo.Free;
  end;
end;

 

IEnumerator<T> Interface

Now the above discussion talks a lot about specific methods that must be included as part of an enumerator, and as part of a class that wants to be enumerated.  And of course, that should immediately make you think “Interfaces!”.  And sure enough, there are some nice interfaces that fall out of this. (You knew I’d work interfaces into things here eventually, didn’t you.  Yes, you did.) 

Consider this interface:

type
  IEnumerator<T> = interface
  ['{DD445F01-975D-405E-BCC1-09D3E78CB0FF}']
    function GetCurrent: T;
    function MoveNext: Boolean;
    property Current: T read GetCurrent;
  end;

That should look awfully familiar.  It’s the exact two methods and one property needed to implement an enumerator – hence the name. 

I’ve declared this IEnumerator<T> interface myself, but the Delphi RTL includes a similar one in the System.pas unit. And at its base, IEnumerable<T> is all about implementing the GetEnumerator method.   

It leverages generics because the type of what is being enumerated doesn’t matter as far as the interface is concerned.  And remember when I said that a call to GetEnumerator could return an interface?  Well it can, and the compiler will happily use an IEnumerator<T> to implement the for…in loop.

Thus, your enumerators can implement this interface and your calls to GetEnumerator can return this interface, and you can add flexibility to how they are implemented.  Here’s an example:

  TStringEnumerator = class(TInterfacedObject, IEnumerator<Char>)
  private
    FIndex: integer;
    FString: string;
    function GetCurrent: Char;
  public
    constructor Create(aString: string);
    function MoveNext: Boolean;
    property Current: Char read GetCurrent;
  end;

  TInterfaceEnumeratorDemo = class
  private
    FTheString: string;
    procedure SetTheString(const Value: string);
  public
    constructor Create(aString: string);
    function GetEnumerator: IEnumerator<Char>;
    property TheString: string read FTheString write SetTheString;
  end;

Notice that the call to GetEnumerator returns an IEnumerator<Char> which is actually the individual type being iterated. In this case, the generic type needs to be the same type as the variable being returned in the for part of the for…in loop.  

This enables you to do the following:

procedure DoInterfaceStuff;
var
  InterfacedEnumerator: TInterfaceEnumeratorDemo;
  c: Char;
begin
  InterfacedEnumerator := TInterfaceEnumeratorDemo.Create('GoodbyeWorld');
  try
    for c in InterfacedEnumerator do
    begin
      Write(C, ',');
    end;
    WriteLn;
  finally
    InterfacedEnumerator.Free;
  end;
end;

 

Specialized Enumerators

The implementation of an enumerator is, as I mentioned, really simple.  But what if you wanted to get a little creative in the GetCurrent method?  After all, at that point you have complete control over what the enumerator returns.  In our simple case with characters and strings, what if we decided to, say, always return the upper case version of the character?  Or if we were iterating over integers, return the squares of the numbers in the collection?  That would be super easy, right? Well, yes, it would.

Consider this code:

  TForInDemoClassUpperCaseEnumerator = class(TForInDemoClassEnumerator)
  protected
    function GetCurrent: Char; override;
  end;
...
function TForInDemoClassUpperCaseEnumerator.GetCurrent: Char;
begin
  Result := UpCase(inherited GetCurrent);
end;

This class descends from TForInDemoClassEnumerator and overrides the existing enumerator for our demo class and returns the upper case of the character in question. 

If we wanted, we could return this class from our GetEnumerator call, but that would be sort of playing a trick on the user of our code. How about if we provide two different enumerators, and then make each available for enumeration in a for…in loop.  Surely that is possible, right?  Of course it is. 

First, we’ll look at the end result and then work our way backwards to see how it was implemented, because you have to play a little trick to expose more than one enumerator for a class:

procedure DoMoreStuff;
var
  C: Char;
  ForInExtraDemo: TForInDemoExtraIterators;
begin

  ForInExtraDemo := TForInDemoExtraIterators.Create('Greetings');
  try
    for C in ForInExtraDemo.AsUpperCase do
    begin
      Write(C, ',');
    end;
    WriteLn;
end;

This little routine will display the string “Greetings” as “G,R,E,E,T,I,N,G,S” in the console.  But note in the for…in loop that the actual class is not passed to the in clause, but a method that returns a “proxy” class that has the desired enumerator attached to it instead.  This is implemented as follows:

TUpperCaseEnumeratorProxy = class
  private
    FOwner: TForInDemo;
  public
    constructor Create(aOwner: TForInDemo);
    function GetEnumerator: TForInDemoClassUpperCaseEnumerator;
  end;
..
constructor TUpperCaseEnumeratorProxy.Create(aOwner: TForInDemo);
begin
  inherited Create;
  FOwner := aOwner
end;

function TUpperCaseEnumeratorProxy.GetEnumerator: TForInDemoClassUpperCaseEnumerator;
begin
  Result := TForInDemoClassUpperCaseEnumerator.Create(FOwner.TheString);
end

This is just another class that can be enumerated – it has a call to GetEnumerator – and thus be returned by a method call on our “real” enumerating class.  It returns an instance of an enumerator called TForInDemoClassUpperCaseEnumerator which we looked at above.  So, if you want to iterate over the upper case version of the strings, you call it as we did in the DoMoreStuff method above.  The trick here is that instead of iterating over the class itself, you iterate over the proxy class using ForInExtraDemo.AsUpperCase.  It’s a neat little trick, eh?

Thus, the enumerating class becomes:

  TForInDemoExtraIterators = class(TForInDemo)
  private
    FUpper: TUpperCaseEnumeratorProxy;
  public
    constructor Create(aString: string);
    property AsUpperCase: TUpperCaseEnumeratorProxy read FUpper;
  end;
...
constructor TForInDemoExtraIterators.Create(aString: string);
begin
  inherited Create(aString);
  FUpper := TUpperCaseEnumeratorProxy.Create(Self);
end;

Conclusion

So, that should give you a little insight into what happens with for…in loops and  how you can create classes that participate automatically.  I’m working towards never using the old for I := 0 to Count –1 do; construct, and making my classes enumeratable.

The code for this article with further examples can be found with my demo code on BitBucket.

Stuff I’ve Been Reading And Watching

By Nick at January 12, 2013 10:50
Filed Under: Delphi, General

Flotsam and Jetsam #73

By Nick at January 07, 2013 20:51
Filed Under: Flotsam and Jetsam, Delphi
  • Do you think it is safe to say that this map is a pretty good illustration and approximation of world-wide Delphi use?  It’s a map of visitors to http://www.spring4d.org.  There are even Delphi users in Iceland! The information you get from this Google Trends search also reveals some interesting geographical information.  It seems that there are a lot of Delphi developers in Russia.  (These types of searches are complicated by the fact that Delphi is also a major auto parts company…)
  • The new year means an updated look at the TIOBE Index!  And guess what language is #1 for 2012?  C.  Not C++, C.  It’s moved past Java as the most popular language.  That’s kind of a surprise to me, anyway.  Delphi continues to hold it’s spot in the “A” language at #15.  They seemed to have combined “Delphi” and “Object Pascal”, but put “Pascal” in its own category. This makes no sense to me, but oh well.  If you combine the numbers all up, “Delphi/Object Pascal/Pascal” ends up at number 11 ahead of Ruby. Completely respectable if you ask me. Another surprising thing to me on the index is how low Javascript ranks. 
  • New Delphi Blog of the Week comes from Francois Piette
  • The Delphi Developers Community on Google Plus is quite active – if you aren’t a member, you should join up and contribute.  Maybe you’ll be the 1000th member!
  • New Delphi Components of the Week:   Chrome Tabs – It’s open source, too.  Pretty nice. 
  • Question of the Day: Arduino or Raspberry Pi?  Why?

My Book

A Pithy Quote for You

"No concept is so difficult that it cannot be conquered by the repeated attacks of the ordinary mind"    –  Morrison Hodges, MD (My Dad)

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.

Month List