Widgets Software Development

Flotsam and Jetsam #38

By Nick at July 07, 2011 00:26
Filed Under: Delphi, Flotsam and Jetsam, Software Development

Getting Giddy with Dependency Injection and Delphi Spring #5 – Delphi Spring Basics

By Nick at June 26, 2011 13:12
Filed Under: Delphi, Software Development


Remember, you can download the Delphi Spring Framework on Google Code.


Okay, so we are finally at the point where we can actually start using a framework to do some of the things that we want to do.  So far we’ve seen how the Law of Demeter is important to good code design.  We’ve looked at how important it is to write testable code by reducing the dependencies between objects, and we’ve seen how it’s good to code against interfaces and to keep our constructors simple. I’m finally going to make good on my promise to show you how to write useful code in a unit with nothing in the interface section. 

I hope I’m doing a good job describing why and how you want to use a Dependency Injection framework.  I hope by the end of this, you can see how to use the Delphi Spring Framework.  However, I’m doing a very imperfect job of describing the motivations and reasons behind why you want to do dependency injection. However, all is not lost – I strongly recommend that you watch this outstanding episode of DotNetRocks TV, where a really smart guy (with a delightful Canadian accent – he sounds just like my brother-in-law) named James Kovacs explains the whole underpinnings of Dependency Injection and why it’s good.  He does the presentation in C#, but don’t let that put you Delphi guys off --  the ideas are all there. 

Problems With “DI via Constructor Parameters”

In the last episode, I talked about two rules that you should follow:

  1. Always code against interfaces
  2. Keep your constructors simple

We looked at how exposing only an interface will create clean, uncoupled, and testable code, and how keeping constructors simple will decrease one classes dependency on another.  We saw an example of what I called “Dependency Injection via Constructor Parameters” (DICP) where you don’t create internal classes yourself, but let them get passed in via parameters on a constructor. 

DICP allows you to create the services (classes) you need outside of the consuming class itself, but it still requires that you create specific classes you want in specific places in your code.  Despite having a certain level of inversion of control, you are still coupled to the specific class.  Consider the following code, based on our Pizza Oven code from the last installment:

  MyPizzaOven: TPizzaOven;
  MyPizza: TPizza;
  MyPizza := TPizza.Create;
  MyPizzaOven := TPizzaOven.Create(MyPizza);

This code is better than creating the TPizza class inside the constructor of TPizzaOven, but we still have the problem of the TPizza class and the TPizzaOven class being coupled together via the uses clause – TPizzaOven needs to know about the TPizza class and how it is declared. 

Even if we re-declare TPizza as an interface – IPizza – we still have to know how to create an instance of TPizza for the IPizza interface, and we aren’t all that much more decoupled than we were before – TPizzaOven still has to know about the specific declaration of TPizza. In fact, the code above really wouldn’t change at all if the MyPizza variable were an IPizza instead of a TPizza,right?

But what if there were a way to get an interface implementation without having to know anything about the specific implementation of that interface?   Now that would really decouple things and truly separate the interface from the functionality. If only there were a framework written in Delphi that would let you do this.  If only……!

The Spring Container

Okay, I was joshing – there is such a thing:  The Delphi Spring Container does exactly that.  A Dependency Injection container is a class that can hold references to interfaces and classes that implement them.  You can register specific implementations of interfaces in the container.  If you need an implementation of an interface, you ask the container, and it provides a reference to that implementation via the given interface.   When you need an implemented interface, you reference only the container, and thus there is no direct connection between the class needing the implementation and the implementation itself.  Pretty sweet, huh?

So how does this work?  The first thing you’ll likely want to do is to create a singleton implementation of the Spring Container.  I’ve created the following unit called uServiceLocator, which wraps up the Spring Container in a Singleton:

unit uServiceLocator;



  function ServiceLocator: TContainer;


  FContainer: TContainer;

function ServiceLocator: TContainer;
  if FContainer = nil then
    FContainer := TContainer.Create;
  Result := FContainer;


The uServiceLocator uses the Spring.DI unit from the Delphi Spring Framework where the TContainer class is declared. I have named my container "ServiceLocator" because it, well, locates services. SmileYou can use this unit anywhere you need to register classes and interfaces, as well as anywhere you need to use those registered interfaces.

TContainer is a powerful class that leverages both Generics and anonymous methods to let you register classes that implement given interfaces.  In later articles, I’ll delve a little deeper into the mysterious inner workings of TContainer, but for now, we’ll just look at the practicalities of how it is used.

Registering With The Container

Now, if you want to use the container, either to register classes with interfaces, or to consume a given interface, all you need to is use the uServiceLocator unit and not any unit that actually declares classes.  In fact, you can declare your classes in the implementation section of the unit and leave only an interface in the interface section.  Remember the uNormalMathService unit from last time?   Now, we can declare it as follows: 

unit uNormalMathService;


  IMathService = interface
    function Add(a, b: integer): integer;
    function Multiply(a, b: integer): integer;



  TNormalMathServiceImplemenation = class(TInterfacedObject, IMathService)
    function Add(a, b: integer): integer;
    function Multiply(a, b: integer): integer;

{ TNormalMathServiceImplemenation }

function TNormalMathServiceImplemenation .Add(a, b: integer): integer;
  Result := a + b;

function TNormalMathServiceImplemenation .Multiply(a, b: integer): integer;
  Result := a * b;

procedure RegisterNormalMathService;



First, note that the IMathService interface is the only thing available for use outside of the unit. Everything else is hidden in the implementation section.  Obviously, the “money code” here is the RegisterNormalMathService procedure. This is where the implementation of IMathService gets registered.  The procedure itself gets called in the unit’s initialization section, so the mere act of using the unit ensures that the TNormalAdditionService is registered and available for use by any other unit that uses the ServiceLocator.  The call to ServiceLocator.Build simply ensures that the TContainer is ready to answer requests for implementations of interfaces.

So what is happening in the RegisterNormalMathService call?  It’s almost self-explanatory.  The code performs pretty much as it reads: “Register the class called TNormalMathServiceImplementation, which implements the IMathService interface, under the name "Normal”.  (That’s what the last string parameter is – a named reference to the interface.  This allows you to register multiple implementations of a given interface and request them by name).

Nota Bene:  if you are going to provide multiple implementations of a given interface, you can declare that interface in a separate unit, use that new unit in the implementation section, and end up with no code at all in the interface section of your unit.  See, I told you it would work.  Winking smile

And once the service is registered, you can use it in a completely decoupled way:

unit uCalculator;



    uServiceLocator, uNormalMathService;

  TCalculator = class
    FMathService: IMathService;
    constructor Create;
    function Addition(a, b: integer): integer;
    function Multiplication(a, b: integer): integer;

constructor TCalculator.Create;
  FMathService := ServiceLocator.Resolve<IMathService>('Normal');

function TCalculator.Addition(a, b: integer): integer;
  Result := FMathService.Add(a, b);

function TCalculator.Multiplication(a, b: integer): integer;
  Result := FMathService.Multiply(a, b);


In this case, the “money code” happens in the class’s constructor, where the ServiceLocator is asked to “resolve” (i.e., provide) a working instance of IMathService, using the implementation registered under the name 'Normal'. The Container then goes and looks into its list of registered items, finds the correct implementation, creates an instance of that class, and returns it as an interfaces.  All of that happens “auto-magically” inside the inner-workings of the TContainer class.

Later on we’ll see how you can control the lifetime of the created classes, pool them, or create instances as a Singleton.  You can even have complete control over how the resulting class is created via the power of anonymous methods. 

Note that the class knows nothing about anything other than IMathService.  It does use the uNormalMathService, but the implementation of that class is completely hidden.   The only reason that uNormalMathService is in the uses clause is because that is where the IMathService interface is declared.  If you really want, you can do as the quote block above says and declare the interface in a separate unit and not even require the use of the unit that implements IMathService at all.


Thus, we have a simple example of using the Delphi Spring DI Container that completely decouples the implementation of a class from the consumer of that class.  In the above example, the TCalculator class knows nothing of nor is connected in anyway to the implementation of the IMathService interface.  All of this happens inside of the Delphi Spring container. 

So far, this is just a simple, basic look at what the Delphi Spring Container can do.  The Delphi Spring Framework can actually automatically and seamlessly create implementations for interfaces without writing any code at all.  So stay tuned for that in coming installments. 

Getting Giddy with Dependency Injection and Delphi Spring #3 – Writing Testable Code

By Nick at June 05, 2011 13:05
Filed Under: Delphi, Software Development, Unit Testing

Okay, so in Part #2 we talked about the Law of Demeter, and how you should think about it and follow it as if it were the Word of God when building classes. 

One of the main reasons to follow the Law of Demeter is to write code and code modules that are loosely coupled.  Loosely coupled modules have minimal interactions with other modules and thus have minimal affect on those other modules.   Change something in a loosely coupled module and the chances of breaking something in another module are slim.  If you have a minimal connection to another module, then you can only cause minimal bugs in that module.

And “minimal bugs” is a phrase to warm the heart of us all, no? 

But the Law of Demeter even goes farther than that.  Using the LOD principles means that you can write “testable code”.

So I think we’d all agree that  the best way to avoid bugs in your application is to never check them in to your source control system in the first place. (And you are using a source control system, aren’t you?)  And the best way to do that is to write lots and lots of unit tests.  Unit tests are the first line of defense against bugs, as they can root out problems in your code as you write them.  They can discover trouble at the very lowest level before it becomes a system level problem.  Writing unit tests is the profound and solemn duty of every software developer.  If you do “true” test-driven development, you’ll write your test first so that the bugs never even show up at all as you write your code to make your tests pass. 

But when it comes to writing unit tests, a common refrain I hear is “I can’t test my code” or “My code is too complicated to test.”  And my response to that is this:

If your code can’t be easily unit tested, you’re doing it wrong.

In fact, this is kind of getting to be our mantra around here at Gateway Ticketing.

Now there are exceptions, of course, such as code for directly manipulating your GUI, etc. But if you are writing anything other than that -- i.e. the vast majority of the code you do write -- then you should be writing code that is testable.  But I’ll make the point again – if you can’t write unit tests for your code, then you need to change the way you are writing your code.   That is, you should be writing code that is “testable”.

Code that is “testable” has a number of familiar qualities.  The most noticeable of those is – surprise! – code that adheres to the Law of Demeter.  LOD code is easy to test because the classes you write stand alone and have limited dependencies.  Code with limited dependencies is easy to test.

A common refrain is this – “My code isn’t testable because it hooks up to too many other things like a database or a scanner or some other thing that can’t be attached to the test suite”.  And my answer to this is:  change your code to remove those dependencies and write mock objects for the instances that you can’t.

Code that is hard to test has dependencies.  Creating an instance of a given class can result in the creating of a host of other classes – even classes that you don’t know about or can’t foresee.  As noted above, heavily coupled code creates these dependencies. Consider the diagram below:


Here, you have a class that you want to test, but when you create it, it creates, in turn, three other classes that then  can create yet more classes, including dependencies on external devices and other systems.  Such classes are hard to test, because testing them brings in all those dependencies. 

What we need is a way to limit and even remove those dependencies in order to make a class easily testable.  And the way you do that is to find the “seam” in your class.  The seam is the point where the dependencies are “attached” to the class to be tested.  Once you find that “seam”, you can reduce and/or eliminate those dependencies.  In the diagram below, the Class Under Test is made more testable by creating classes that don’t create dependencies – a better designed class that itself uses the LOD, a “stub” class that does nothing (say, a logging class that actually doesn’t log anything) or a Mock class that merely pretends to be the external dependency without actually being the external dependency. 


Creating classes for which you can find this “seam” and substitute classes that don’t create the dependencies is key to creating a “testable” class.  Remember, it is hard to introduce bugs into systems that are made of up easy-to-test classes.  So, we should write easy to test classes, right?

The critical thing to remember here is that the class need not completely avoid the dependency – at some point your code is going to have to connect up and talk to that Oscillation Over-thruster – but rather your classes should be able to limit those dependencies as much as possible, and where they can’t, they should be easily able to “fake” having the dependency so the class can be tested without the real dependency.

And just how will that be done? You’ll have to tune in for the next episode!

A Note on Delphi Open Source Licensing

By Nick at May 12, 2011 14:29
Filed Under: Delphi, Software Development, TechBiz

I love open source code.  I love the notion of sharing and working together for the betterment of a community. I love the free stuff that I can use because of the generosity of open source developers. 

Open source development often can be bogged down by licensing decisions.  I don’t know how many bits have been spilled arguing over the exact meaning the Lesser GNU Public License (LGPL), or whether the GNU Public License (GPL) is one step away from a socialist worker’s paradise or not, but surely it’s a lot of bits. 

Well, I’m going to spill a few more.

I totally get the GPL – I respect it, and I laud the folks that do work on GPL-based projects.  They are really giving away for free (as in speech) their work to others.  Linux exists because of the GPL. I get why the license exists. I understand the whole “Free Beer/Free Speech” thing.   Some amazing, awesome things exist because of the GPL.  It’s all good.


The GPL is completely incompatible with commercial software.  Totally, utterly, and completely incompatible.  If you use GPL source code in your commercial application, you are obligated to release your entire application as a GPL Open Source project.  Everything.  Obviously, if you sell your software, you very likely don’t want to do that.  (I recognize that there are folks that will, and more power to them…..).

Now, Delphi is a development tool used by a whole lot of businesses – businesses that are likely not to want to make their source code available under the GPL.  And so open source projects that are aimed at Delphi developers make a very limiting decision if they release their code under the GPL.  A Delphi library of code with the GPL attached to it will severely limit the number of Delphi  users that can or will use that library. 

Many of the popular open source libraries for Delphi use a much less restrictive license.  All the Turbopower code was released under the Mozilla Public License (MPL) which is much less restrictive, only requiring you to share any changes you make to the MPL project itself.  Others use the Apache License which is very permissive.  But some do use the GPL.

Now, I’m going to give some advice to those folks who publish Delphi source code under the GPL:  Issue it under an alternative license – one that businesses can handle.  I’d recommend MPL at the most strict end of the spectrum.  We are going to start using the Delphi Spring Framework, and that is licensed under the very friendly Apache license.  I’d love to use the Emballo framework as well – particularly for the Mock object classes, but it is licensed under the GPL, and so we really can’t touch it. A project like the Emballo project is also available for use under the LGPL and worth considering.

The GPL is great – it works well in the Linux world and where other open source development tools reign supreme.  But for more commercial-based eco-systems like Delphi, a business-friendly license is much more in order. 

Flotsam and Jetsam #32

By Nick at May 12, 2011 13:28
Filed Under: Flotsam and Jetsam, Software Development
  • “We put our faith in Apple and they screwed us”  Just another reason why Apple always seems to rub me the wrong way.  Don’t get me wrong -- I think Apple should be able to do what they want when it comes to this type of thing – but I don’t have to like it.
  • I confess to being guilty of this in my blog, but no more, I promise.
  • Have you had this problem? You are working on a website and local testing/debugging is a hassle because you have to move from page to page filling in valid information, and it takes huge amounts of time and you cringe when you have to do it?  Our team here at Gateway has started to use iMacro.  It’s a FireFox that lets you record events on a given website and run them with the click of a button.  This is saving our guys tons and tons of time.  Highly recommended.
  • And yet another way that you can support the fine work we do here at – you can join DropBox as my referral.  It’s completely free for the first 2GB. Yes, I am well aware that this appeal is utterly shameless.  In addition, I give the DropBox folks full marks for marketing – they basically have a zero-dollar advertising budget.

Getting Giddy with Dependency Injection and Delphi Spring #2 - The Law of Demeter

By Nick at May 11, 2011 09:07
Filed Under: Delphi, Software Development


Okay, I keep digging into the Delphi Spring Framework and I keep finding cool stuff you can do, so I can hardly wait to write all these articles.  Seriously, this is a mind-expanding experience.

First, though, I need to talk about some general topics.  There are a few things that need to be accepted and understood before Dependency Injection can really sink in.  (And again, I want to point  out that I’m deeply indebted to Misko Hevery of Google for a lot of this material.)

The Law of Demeter (LoD)

First topic -- the Law of Demeter.   What exactly is the Law of Demeter?  The strict definition goes like this:

Law Of Demeter

A method of an object may only call methods of:

  1. The object itself.
  2. An argument of the method.
  3. Any object created within the method.
  4. Any direct properties/fields of the object.

That’s a bit formal, so here’s a “real world” example:

Let’s say you go into a store.  You buy a bunch of stuff, and the total is $25.  When you go to pay, what do you do?  If you are believer in the Law of Demeter, then you pull out your wallet and give the $25 to the clerk – just the money, nothing more.

But no, you are a scofflaw and fear not the deep coupling of your wallet to other people and thus you think the Law of Demeter is for weaker men, so you pull out your wallet and hand the whole thing over to the clerk and let her decide what to do for the payment. 

Lady at Cash Register

Sure, you intended to pay with cash, but instead the clerk takes your wallet, uses a credit card to pay for the stuff, drops your library card on the floor, runs your BuyMore loyalty card through a degaussing machine, and draws a moustache on the picture of your wife.  You paid for the stuff, but wow, what a mess!

That’s why you should follow the Law of Demeter in a nutshell.  It’s basic premise is that you should only hand over (and on the other side, only ask for) exactly what you need to hand over (or ask for).  Things should be linked together with as thin a string as possible.  The Venn diagram illustrating the connections between classes should have as small an overlap as can be managed.  In this example, you might not even want the clerk to know you have a wallet, right?

Or in another example, you wouldn’t give the paperboy your wallet or let him search around your house for spare change.

A Coding Example

So for instance, in code, you may have a Transaction class that needs a form of payment to be completed.  And hey, look! The Customer class has different Forms of Payment, so you pass a Customer to the Transaction.  Sure, at first all is well, because you are very careful and all you do is grab the Form of Payment from the customer and use it.  What could possibly go wrong?


But a few months pass, and that (cough, cough) “less experienced” developer comes along and says “Hey look! Here’s a Customer object!  I think I’ll change his address here instead of over there!” and all heck breaks loose.   Pretty soon, you are fixing a bug in the Transaction class and Customer data changes.  You fix a Customer bug and access violations start flying when you try to commit transactions to the database.  The next thing you know, changing a Customer address is sending major cash bonuses to your office cleaning service, and before you know it, there is no end to the havoc reeked by that little Customer object innocently sitting in the Transaction class.

The right thing to do, of course, is to simply pass the Form of Payment itself, or better yet, forget the Form of Payment and pass in just the money itself in some form.  The idea is that your classes should ask for a little as possible, and refuse to accept more than they need.    If you have code like this --


-- that is, code that seems to drill down deep into a class hierarchy -- then you probably deserve a ticket from the cops for breaking the Law of Demeter.  You’ve gone searching down a rabbit hole for something that you should have just asked for to start with.

The classic quote is “Only talk to your friends, and never talk to strangers”. “Mind your own business” comes to mind as well. 

Or let’s put it in even starker terms:  Pretend that every class you write is a pristine clean room with no germs, dirt, or any other yucky stuff in it – and that you plan on keeping it that way.  Are you going to let some delivery guy who just tramped through a horse barn while sneezing because of the ebola virus just walk  into your room and hand you a package? Heck no!  You are going to make him shower, scrub, de-sanitize, purify, and otherwise delouse himself before entering.  Heck, you should probably make this guy put on some sort of bio-hazard suit on before you let him in.  Or even better still, don’t let him in at all, and only let him pass in whatever he’s trying to give you via some secure slot in the door. 

That’s how you should be treating any outsider class that want’s to sneak in to the current class.

Law of Demeter in Delphi

Delphi and the Law of Demeter can be good friends.  Here are some pointers to help out in your Delphi code:

  • Limit the number of units in your uses clauses.  If you have a long list of items in your uses clause, it is a strong indication that things are tightly linked together.
  • Limit the scope of your uses clauses.  If you can put an item in the uses clause of the implementation, do so. 
  • Use strict private and strict protected.  This will limit you from the temptation to make classes “friends” of each other in the same unit.
  • As noted above, anytime you have a chain of “dotted” properties in a single line, you should examine this for violations of LoD.
  • Anytime you are creating a lot of temporary object, this might indicate un-necessary dependencies.
  • Check your constructors – if they are creating a lot of things or taking a lot of other classes as parameters, then the same thing applies:  the possibility of too much coupling.

Note that these aren’t iron-clad rules, but rather suggestions of examination and consideration. It need not become “a Dot Counting Exercise.”  The idea is to reduce coupling and thus limit the damage any one modification can have on the system as a whole.


Following the Law of Demeter is a key to creating clean, easier to maintain code.  Once you get that down, you’ll also find that you are writing code that is easy to test.  Next time, we’ll take a look at why it’s important to write testable code. 

Getting Giddy with Dependency Injection and Delphi Spring #1

By Nick at May 09, 2011 14:13
Filed Under: Delphi, Software Development

I remember way back in the 90’s when I finally had “the light bulb” go on about object oriented programming.  You know “the light-bulb” I’m talking about  -- that moment when suddenly you get it and it all becomes clear and it all makes sense and you have this thrilling sense of understanding and one-ness with your code and the new concept.  It’s really fun.

For me and OOP it came in the middle of reading what is still my all-time favorite Pascal book, Borland PASCAL 7 Insider by Paul Cilwa.  I can still remember where I was sitting when suddenly it all came together in my brain.  It was very exciting.

And I was feeling that way again this week when I started doing Dependency Injection with the Delphi Spring Framework.  It really came to a head when I realized that I can create useful and powerful units that have no code in their interface sections. 

That’s right:  no code in the interface section. No uses clause, no code, no nothing.  Seriously – a unit that looks like this:

unit DoWhatever;


  // a whole bunch of cool code here and nowhere else


Yeah, you heard me – nothing.  And yeah, the cool code mentioned above works and is totally accessible.  That fact alone should give you pause – and give a clue into the power and coolness of what I’m talking about.  And yes, I’m still giddy about all this.

So, how does this happen you ask?  Well, it’s going to take a little while to explain – maybe even a few blog posts – so if you want to see this cool thing that’s got me all goose-pimply, you’ll have some to do some reading.

At the start, I want to say that I’m well aware that Java guys in particular have been doing this kind of thing for while, and that .net guys have been  as well.  That’s great. I know Delphi is a bit late to the party here, and I am too, but that doesn’t make it any less cool and it doesn’t make me any less giddy.  Winking smile

Okay, first, I’ll give you a few things to do.  To get the basic idea of where we’re going with all this,  I recommend that you read the seminal article by the inestimable Martin Fowler about Dependency Injection.  Understanding what Dependency Injection is  is key to all this cool stuff.  I’ll try to explain what Dependency Injection is in the first post, and then move on to the code itself.

Second, you’ll need at least Delphi 2010 and preferrably Delphi XE to do all this.  This stuff requires Parameterized Types (Generics) and you can only get that language feature from Delphi 2010 and above.

Third, you should go and download the Delphi Spring Framework from Google Code.   I recommend that you pull it using Subversion instead of grabbing the zip files as then you’ll be able to keep up more easily on this always improving project.  Get the code and start poking around, particularly in the Spring.DI.* units and the tests that go with it.  The TContainer class is really the heart of things, and so give that a close look.

And if you want some cool videos to watch that talk about a number general principles of how you can use dependency injection to make your code better, I’d recommend these three by Misko Hevery of Google:

And that ought to get you started thinking about some of the things you should be thinking about when doing Dependency Injection.

Next time I’ll give some samples of code and why this is all important.  And yes, I’ll likely be using a lot of the same material that Misko did.  Smile

A Big Thank You

By Nick at April 15, 2011 04:59
Filed Under: Delphi, Software Development, Tech Stuff

I’d like to pass on a big thank you to Marco Cantu, Cary Jensen, and Cary’s lovely wife Loy Anderson for their wonderful hospitality while I was at Delphi Developer Days in Baltimore earlier this week.  It was an honor to be asked to be a guest speaker at the event, and I hope that my talk on unit testing with Delphi was worthy of the conference.  Cary also graciously gave me a signed copy of his excellent new book, Delphi in Depth: ClientDataSets

I should add that the conference was very valuable.  Cary and Marco do a great job and there were a lot of good examples and code, as well as a very nice manual with tons of great articles in it.  I heartily recommend attending next year if you are so inclined.

The First Thing You Should Do

By Nick at March 28, 2011 12:47
Filed Under: Delphi, Software Development

We’ve all done it:  File|New|VCL Forms Application.  Then we drop a button and a memo, double click on the button, and write some code that prints out to the TMemo. You start out just “testing something out”, but then you end up working on a routine, or maybe even a class or a collection of classes.   Your “tests” are runs of the app, pushes of the button, and then looking at the output in the TMemo on your form.


Sometimes you were just trying something out, but sometimes the result actually ended up being useful. 

At some point, though, you probably realized that this was a bit “amateurish” – not what “realy developers” do.   Pretty soon you discovered that all the cool kids did their horsing around in Console Applications, using WriteLn to output “SUCCESS” or “FAIL” or other data, depending on how things went for testing.  This worked out well – you could even set up a basic test harness to track the output by diverting the output somewhere it can be tracked.

Console applications are sexy and lean and mean.  You were cool.   You would eventually work what you were testing out up into a class and writing a bunch of sample code to make things work.   You probably ended up with a separate unit that had a class in it and a console application that called into that unit.  Way cooler that  your app with the button and the TMemo.

Okay, so that is all well and good.  But I’m going to argue that there is even a more sophisticated thing that we should be doing when we need to build something new – something that is designed specifically for proving that something works:  DUnit.  That’s what the really cool kids are doing. 

If you are creating something new, and there is even the slightest chance that it will end up being real and used in production, the first thing that you should be doing is not a simple form or a console application, but a DUnit based application.  This way, you can easily write tests to define how the thing you are writing should behave.  You  almost certainly end up writing a class (and you do put your functionality in classes right?).  You can then play around with that class, add tests, and see how things work.  You’ll get that beautiful green bar sliding across the DUnit Runner app, and you can continue to work up your class, add tests, and make changes with confidence as you work on stuff. Eventually you’ll end up with a tested class that you have confidence in.

It’s the ultimate way to “test something out”.  (Yes, I’m trying to sneak in the back door to get you to do Test Driven Development.)

DUnit ships with Delphi, and Delphi provides a nice wizard for creating a new DUnit application.  So there’s really nothing stopping you from doing DUnit first.

What is the Next Layer?

By Nick at January 18, 2011 22:44
Filed Under: Delphi, Software Development, TechBiz

The software of today is really made up of a rather long series of layers, with each layer reducing the complexity and increasing the capabilities of software developers.

The first developers literally programmed in ones and zeros.  They had nothing more than that – pure binary. Heck, in the beginning, the notion of “programming” didn’t even really involve software, but rather the manipulation of hardware – actually flipping switches to physically alter the bit settings on the device. 

But soon enough, along came an assembler, which is basically a layer of abstraction over binary code.  Then Grace Murray Hopper invented the notion of a compiler, and this brought about human readable languages. (Some argue that assembly is human readable – I guess I mean “readable my mere mortals”). 

But of course, every language has to have an operating system to code against.  Once we had that idea down – that of writing a human-readable language against the operating system (OS) - we wrote Application Programming Interfaces (APIs) to make calling into the OS easier.  Instead of coding against interrupts in DOS, we had a neat, fairly easy to use thing like the Windows API. 

But naturally, we weren’t happy there.  We needed another layer!  So along came things like the VCL and MFC.  They were layers on top of the OS’s Windows API making it easier to write Windows programs.  (Of course, if MFC makes it easier, I’m not sure what word to use to describe what the VCL does for Windows programming.  Winking smile)

But that wasn’t good enough for us, now, was it.  We needed yet another layer.  So along came things like Java as a cross-platform layer, and for Windows, we now have .Net.  At its base level, .Net is another level of abstraction on top of the Windows API.

So (crudely put) we have .Net on top of the Win32 API on top of the OS on top of Assembler on top of binary code on top of physical switches.  Layer after layer. As a result, we have managed to tame the immense complexity of the computers that we have today.  Without all these layers, we’d never be able to write the software that we use today.

So the question that pops into my mind is this:  What is the layer that we are going to put over things like .Net and the VCL?

I myself have no idea, despite having thought about it quite a bit.  I’m guessing that it will be something that we haven’t even really conceived of yet – or something that only people way smarter than you and I are thinking about today.

Nevertheless, I bet you have an idea.  What is it?

Even More Changes to HTMLWriter

By Nick at January 09, 2011 05:19
Filed Under: Delphi, Software Development, Unit Testing

Okay, so if you are actually using THTMLWriter, I’m sorry – but I made another pretty major change to it, one that will require you to again make changes to any existing code that you have.  Such are the perils of using pre-1.0 software I suppose.

These changes are made at the suggestion of a number of you fine people, and I’m grateful for your wisdom and for taking the time to critique my work and make such good suggestions. 

Interface Only Access

If you have an interface you want people to use, then you should provide a way for them to use it.  In fact, the really cool thing to do is to make it so that it is the only way to do it.  One iron-clad rule of interfaces is that you should never mix interfaces and instances of the classes that implement them.  The interface is the important thing, not how the interface is implemented. 

An interface is a “promise” of a specific service, and a consumer of an interface shouldn’t care about the implementation details of an interface.  Indeed, that is one of the main advantages of interfaces – that you can “switch out” what you use to actually implement the interface.  If one of you guys things my implementation sucks and want to create a new one, you can simply create a class that implements IHTMLWriter and use that instead without changing any of the code that you have using IHTMLWriter.

So What Did I Do This Time?

Okay, so here’s what I did.

  • I created three standalone functions that return a reference to the IHTMLWriter interface.  They correspond to the three constructors that are included in the THTMLWriterclass.  This is the only way to “get at” the IHTMLWriter interface. 
  • I “hid” the entire THTMLWriterclass in the implementation section of the uHTMLWriter.pas unit.  Now, you can’t even get at the class even if you wanted to.  You must deal exclusively with the interface. 
  • I put the two interfaces I created – IHTMLWriter and ILoadSave -- in their own units.  This way, they aren’t coupled together and can be used separately if desired. 
  • I put all the /// comments in the interface unit instead of on the class. 
  • I had to make changes to the tests to support the new way of grabbing an interface reference.  I made the names of the functions similar enough to the code you current have that it will just be a matter of deleting a few characters.  Of course, all the tests still pass.

What’s Left?

I have a few more things to implement – mostly support for some less common tags that go in specific places inside a <table> tag.  After I do that, I think then I’ll declare THTMLWriter to be an official 1.0 release.

Update on THTMLWriter

By Nick at January 06, 2011 03:56
Filed Under: Software Development, Delphi, Tech Stuff, Unit Testing

I’ve made a fairly significant change to THTMLWriter.  (Even if you aren’t a use of THTMLWriter, please keep reading, there’s a valuable lesson at the end.)

What Did I Do?

I created an interface – IHTMLWriter – which simply lists the public interface of the class – and then had THTMLWriter implement that interface.  Not a big deal.  The big deal is that now the Fluent Interface is done with the IHTMLWriter interface instead of the class itself.  This shouldn’t be a big deal if you are using the class – you merely need to change the variable declaration to IHTMLWriter, and remove any code that destroys/frees the class you may have created. 

Why did I do this?  Well, I have to confess that it was partly because I could.  But I also think that in general, interfaces are better to deal with, particularly with the fluent interface.  I’ve noticed that interfaces appear to be the typical way that such things are implemented.  In addition, an interface limits the scope available to the consumer of a class.  If  you can only use a class via the interface, I as the developer can decouple the implementation from the interface – something that is always good. Plus, if one of you fine people feels like there is a better way to crank out HTML, now you can do it, too, using the same interface. 

The Valuable Lesson

Here’s the part that you all need to read:  I was able to make this rather large change with a lot of confidence because I had a pretty extensive set of unit tests to back me up. 

The initial change – creating the IHTMLWriter interface and changing the class to implement and use it – broke everything.  No test would pass, and the test program did nothing but raise access violations.  So, of course, I went to work and fixed things up.  I had to change a little architecture, alter the way a few things were done, and generally fix things up. 

All of my debugging was done on the test project.  It provided a perfect, simple reproduction of the bugs.  The unit tests enabled me to easily step through simple examples and find the places where the bugs were and where things weren’t working right.  And eventually the tests all “turned green”. 


And let me tell you, turning green is sweet!  First, it feels really good. I kept running the tests and watching that little green bar slide across because it felt great.  Why did it feel great?  Because I knew that my changes were complete and  because I had confidence that things were all working as they were supposed to.   The only way that was possible was because of the existence of the unit tests.  Without them, I’d never really ever be sure that things were back to normal and working.

Time Well Spent

So the unit tests allowed me to forge ahead with confidence, provided me with a useful and powerful vehicle for testing and debugging my changes, ensured that I would know when I was done, and enabled me to prove that things were working as they should – all while making a fairly substantial change to a fairly complex code library. 

And some people say they don’t have the time to write unit tests.  I say you don’t have the time not to.

The Developer Solutions Conference

By Nick at January 03, 2011 21:57
Filed Under: Delphi, Software Development, TechBiz

Hey, I want to give a shout out to the folks at RemObjects and Developer Experts and their upcoming conference focused on Delphi – the Developer Solutions Conference. It’s taking place February 8 –10 at the MGM Grand in Las Vegas. Now, I can only assume that the vast majority of you are always looking for an excuse to go to Vegas, and now you a have one. 

Sadly, I won’t be able to attend, as the conference is falling right around the time of a major release for us.  I really would like to be there.  I always love hanging around with Delphi Geeks, and so I hate missing this opportunity. 

More information:

If you are looking for a stimulating conference and even better, a reason to go to Vegas, why, you should register and go!

Announcing THTMLWriter

By Nick at November 22, 2010 00:44
Filed Under: Delphi, Software Development, Tech Stuff

I have started an open source project on GoogleCode called THTMLWriter.

THTMLWriter is a Delphi-based class library that enables you to create HTML code and HTML documents. It uses the fluent interface to make creating HTML text easy and natural.  You can create HTML Documents or HTML “chunks” by  using any tag as a base.

THTMLWriter is all class based.  I started out trying to do some fancy things with interfaces, but it just got too complicated, and so I opted to go with the “simplest thing that will work” option, and now you can write code that looks like this:


Temp := THTMLWriter.CreateDocument;
     TempHTML := Temp
                        .AddAttribute('this', 'that')
                        .AddStyle('font: italic')
                      .AddBoldText(' Shadooby')


The project more or less produces XHTML code at the 4.01 level – I’ve tried to be XHTML-compatible, but I confess I haven’t been fanatical about it.  That is one of the things I want to in the future.  In addition, I want to update the project to support HTML5.  I’m still thinking about how to do that.

The project is pretty complete – you should be able to construct most HTML constructs.  I’ve provided a lot of overrides and default parameters for many of the “normal” attributes on a given tag.   I’ll continue to update the project with improvements and refinements.  I’ve used HTML & XHTML Pocket Reference from O’Reilly as my guide. I haven’t quite implemented everything, but it’s definitely at the point the that it is ready for you fine  people.

The project includes a full set of DUnit tests to give you confidence that the code actually does what it is supposed to. 

I have added a lot of XMLDoc comments to the code, but it’s far from complete. I’ve used the Documentation Insight plugin from DevJET software – the guys who do the Delphi Spring Framework.  (I can’t recommend this plugin enough – an outstanding contribution to the Delphi community, above and beyond the amazing Delphi Spring Framework.)

You can get the code from Google code using Mercurial.  We are planning on migrating our codebase here at Gateway Ticketing to Mercurial after the first of the year, and this project was my learning curve for using Mercurial.  Now that I’ve been using Mercurial – a distributed source control system – I wonder how we as developers ever managed to use anything but a DVCS.  It is that good and that powerful.  I heartily recommend looking at migrating to a DVCS.  It’s so much more flexible and more powerful than a server based solution such as Subversion

I’d be very happy to add anyone to the project who is interested in contributing.  I’ll also be happy to integrate submitted patches as well.  This have been a fun project to keep my toe in the water of coding – being a manager now means I don’t get to code as much as I want --but living alone in Pennsylvania while my amazing wife moves our house out here has given me a lot of free time to code.

Enjoy and let me know what you think.

Setting up Hudson to compile Delphi Projects

By Nick at November 05, 2010 12:37
Filed Under: Software Development, Tech Stuff

Just like you should be using Source Control (even if you are a one man operation), you should be doing continuous integration.  We currently use, but we are giving Hudson a look here at Gateway Ticketing, and it seems likely that we’ll end up switching and using it.  So naturally, I decided to play around a bit with Hudson. We used Hudson quite extensively at Embarcadero, but I had never really given it a whirl myself.

This is the Hudson Dude whose picture shows up in the Hudson interface. 


He’s quite dapper, no?

Hudson is Java-based, but don’t let that scare you.  You need not know a lick of Java to use it effectively.  It is very, very easy to download, install, and get up and running.  I found this blog post helpful in that regard.  I was up an running in minutes.

Hudson has a very nice browser interface for configuration.  It also has a very large and growing collection of community of plug-ins.  Hudson also makes it really easy to install plug-ins by providing support right in the interface.  Add them isn’t much more than selecting them in a list an clicking install.

Plugins are important, because you are going to need them in order to do a Delphi build.  The first one you’ll want to install is the MSBuild plug-in.  This will allow you to choose MSBuild as a build environment.


All of the popular source control systems have plug-ins. I’ve been using Mercurial on my local machine, and so I chose that plug-in as well. 

I also discovered, after a series of trial and errors that the setenv plug-in is pretty much required as well.  As you may know, to do command line builds of Delphi projects, you need to set a number of environment variables. This is usually done via the rsvars.bat file.  Well, Hudson doesn’t know about that at all, and I didn’t have much luck running it as a batch file before doing the build.  Hudson seems to isolate the environment for each individual action.  The setenv plug-in lets you set global and local environment variables for Hudson.  Since I’ll be doing a lot of Delphi builds, I selected “Manage Hudson” and took the items from rsvars.bat and set them up as Global Properties:screen1

Doing that is critical, as that sets everything up so that Hudson can find the files needed by every Delphi project to define the build targets.  There are a couple of StackOverflow questions about this very topic that recommend passing a few parameters, but I found that if you set up setenv to incorporate what rsvars.bat does, you don’t need to pass any parameters on the MSBuild command line beyond the *.dproj or *.groupproj filename. 

In addition, you need to tell Hudson about MSBuild specifically – that’s easily done in the global configuration as well. Basically you give each installation a name and the full path to the MSBuild.exe for that .net version.  You might want to set up different MSBuild installations for  the .NET 2.0 and .NET 4.0 versions, for instance.


Once all that is set up, it’s really a matter of setting pretty self-explanatory properties of Hudson.

  1. Select “New Job”. 
  2. From here, I just chose “Build a free-style software project” to do a simple build of a Delphi project group.
  3. Give your job a name and click Ok.
  4. From there, you can pretty much figure things out.   I did the following.
    1. Pointed Hudson to the Mercurial repository I wanted it to pull from, including the branch I wanted.  The settings for Subversion and other SCM systems may have different settings.
    2. I chose to poll Mercurial for changes.  The “code” for setting that up is a bit tricky, but I found pressing the help button gave a pretty good rundown and some examples.  I just set it to poll every minute.  Not a big deal on my local machine, and it makes it easier to see how things are working while testing it out. screen4
    3. The final thing to do was to actually tell Hudson what to build.  That was easy – I have a project group called


      and I simply added that as the MSBuild build file after telling Hudson which version of MSBuild to use.

And that is pretty much it. From there, you can tell Hudson to build for you on demand, or you can just leave it to run, and it will build everytime it sees a change in your source.  Again, the “tricky” part was getting and using that setenv plug-in.  That simplified everything. 

UPDATE: Christer Fahlgren has also written a very nice blog post about running Hudson on Delphi projects.

My Book

A Pithy Quote for You

"Everybody is a genius. But if you judge a fish by its ability to climb a tree, it will live its whole life believing that it is stupid."    –  Albert Einstein

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.