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

A Bunch of Stuff I’d Like to See Embarcadero Do

By Nick at July 05, 2011 22:22
Filed Under: Delphi, Tech Stuff, TechBiz

There are a bunch of things that I’d like to see Embarcadero do.  I’ve listed and discussed some of them below.  I’ll probably think of more later.  Winking smile  They are in no particular order, and they are not grouped in any particular way.  They are a bit random, and range from business decisions to minor technological decisions. Where it makes sense, I’ve linked the titles to the entries on so that you can vote for the items if you see fit.

I’d like to see Embarcadero:

  1. Provide an Enterprise-level MVC web framework for Delphi.  This almost seems like a no brainer to me. Ruby on Rails has had a profound impact on web development and development in general.   In the .Net world, MVC has become the leading ASP.NET development method,winning over hearts and minds from WinForms.  The general idea of MVC is becoming the norm for much of the development world – separate those concerns!. Delphi’s new RTTI capabilities would actually make this kind of framework very, very possible and very, very cool.  And Delphi already has a very powerful and capable web infrastructure to build on:  good, old, and venerable WebBroker.  There are even existing frameworks out there that could be leveraged, including the G Framework.   There is a business opportunity here for Embarcadero, if not for an enterprising third-party Delphi developer.  A native, ISAPI based MVC framework in Delphi?  That would be very, very sweet.
  2. Stop trying to do other stuff and invest in Delphi.  This one has been one of my huge frustrations over the years.  Delphi is a profitable product, but no matter who owns or runs the show,  the profits always seem to get skimmed off to fund other “next big thing” projects of, well, questionable benefit at best.   Remember “SDO” taking the market by storm? Yeah, me neither. AppWave seems to be interesting and have a lot going for it, but I personally would rather have seen that effort invested back into Delphi.  I hate to think about where Delphi might be today if it hadn’t been used to fund other projects and instead been allowed to use it’s profits for it’s own development.  Delphi could use a year or two of un-distracted attention from its owner. 
  3. Create a Javascript/HTML development tool.  I’ve always said “As assembler is to the Intel chip, so Javascript is to the browser”.  James Governor has it right:  “Learning Javascript used to mean you weren't a "serious software developer". Today, not learning Javascript means the same thing.”  A powerful, feature rich RAD development tool for Javascript and JQuery would be really cool and a great new product for Embarcadero.  Maybe RADPHP could be steered in that direction?
  4. Make Dependency Injection part of the RTL: If you haven’t figured it out yet, I’m a big believer in Dependency Injection.  So much so, that I think that if you aren’t doing Dependency Injection, then you are doing it wrong.  Incorporating a DI Container into the Delphi RTL would be very cool.  Again, Generics, anonymous methods, and the new RTTI makes is very easy and powerful, and there are open source projects to leverage and build on (like my favorite, Delphi Spring).
  5. Do one thing at a time and do it really well:  This is the one that I wish they would do the most:  Take the product forward one step at a time. For instance, the next release should have as it’s main focus 64-bit Delphi and only 64-bit Delphi. That’s it.  Other improvements can be made, of course, but clearly that should be the “big one”, and it should be the only “big one”.  Don’t try to do two or three “big ones” in a single release. Make each release focused on a big, single step forward, executed thoroughly and solidly.  The product will be fine as long as it shows steady, sustained improvement.  Many large improvements executed all at once is not what the market wants.  Focus and deliberately move forward.

That’s all for now – I’ll probably have more as I think of them, but that ought to be food for thought for while

Changes to the Website

By Nick at July 01, 2011 19:08
Filed Under: General

As you’ve probably noticed, there have been some changes to my website here.  I thought I’d list what I did:

  • I updated the engine to BlogEngine.Net 2.5.
  • I updated the theme as well.  I wanted one where the main content isn’t fixed in width. I’ve been posting a lot of code samples, and having a fixed with for those wasn’t working like I wanted.  I also thought it was time for a “fresh look”.  I’ll be tweaking the theme going forward – I’m still not happy with all the font sizes.
  • I added a Google Plus One button to each post after the buttons from AddThis. I also made those buttons a bit more prominent.  Feel free to click those buttons if you like what you see.  Winking smile 

Of course, if you notice any problems, issues, etc., or have any feedback and/or suggestions, please let me know.

Accessing Private Stuff with Interfaces

By Nick at June 27, 2011 17:38
Filed Under: Delphi, Tech Stuff

I have to admit that the following code surprised me.  I guess it makes sense, but I wouldn’t have guessed that you can expose private functionality via an interface like this.  Interesting. 

program DoPrivateStuff;




  ITestInterface = interface
    procedure DoThisPrivateThing;
    procedure DoThisPublicThing;

  TTestClass = class(TInterfacedObject, ITestInterface)
    procedure DoThisPrivateThing;
    procedure DoThisPublicThing;

{ TTestClass }

procedure TTestClass.DoThisPublicThing;
  Writeln('Doing a public thing');

procedure TTestClass.DoThisPrivateThing;
  WriteLn('Doing a private thing');

   Test: ITestInterface;

    Test := TTestClass.Create;
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);

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

By Nick at June 26, 2011 22: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. 

Flotsam and Jetsam #37

By Nick at June 22, 2011 12:06
Filed Under: Delphi, Flotsam and Jetsam, Tech Stuff
  • Marco Cantu has published his new book on Delphi XE.  I’ve been given an advanced copy (thanks, Marco!) and as you’d expect, it is excellent.  We are going to buy some copies here at Gateway Ticketing for use in our transition to Delphi XE.  As with everything Marco does, it is highly recommended
  • There a new Facebook group for Delphi Developers that seems to have a lot of activity.  You might consider joining.  It would be good for Delphi people to congregate in a single place on Facebook to share links and information, and this might be the place. 
  • And speaking of Facebook, you can now ’Like’ Embarcadero’s AppWave on Facebook.  I’m still not clear on exactly where all this AppWave thing is going, but it does look interesting.  I wonder what affect the “appstore” in Windows 8 will have on it.  I guess one advantage that AppWave has is that it is here right now, and Windows 8 is still pretty much vaporware at this point.
  • I went to see the Green Lantern this past weekend.  Highly recommended – I have no idea what all the bad reviews were about.  Great comic book movie.  (Those reviewers know that the Green Lantern is a comic book movie, right?)  The tech angle here is that it was the first time that I had seen a movie in 3D.  My take?  I never want to see a movie – any move, I don’t care if it’s a “blockbuster” or not – in 2D again. It was a terrific experience. This is a great feature that will definitely get me in the theater more. I have been going to the theatre less and less because of Netflix, but if I can see the upcoming Harry Potter movie in 3D, I will.  Looking forward to it being the normal experience on TV.
  • David I has been at Borland, Inprise, Borland, CodeGear, and now Embarcadero for 26 years.  He’s seen it all.  Congratulations to a titan of the industry – and a great guy.  I’ve known David for many years – since I met him at a PC User group at the Naval Postgraduate School in around 1994 – and it’s been an honor to be his friend.
  • I love a good story like this:  Throw Away that Hotel Soap.  There is staggering waste in our economy (anyone buying cases of plastic bottles of water – I’m looking at you…) and this is the kind of thing I love to see.

Flotsam and Jetsam #36

By Nick at June 19, 2011 13:51
Filed Under: Flotsam and Jetsam, Delphi

What I've been reading

By Nick at June 16, 2011 17:41
Filed Under: General, Personal

Flotsam and Jetsam #35

By Nick at June 10, 2011 16:02
Filed Under: Flotsam and Jetsam, Delphi

Flotsam and Jetsam #34

By Nick at June 09, 2011 09:53
Filed Under: Delphi, Flotsam and Jetsam

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

By Nick at June 05, 2011 22: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!

Flotsam and Jetsam #33

By Nick at May 20, 2011 18:01
Filed Under: Flotsam and Jetsam

A Note on Delphi Open Source Licensing

By Nick at May 12, 2011 23: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 22: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 18: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. 

Flotsam and Jetsam #31

By Nick at May 10, 2011 17:30
Filed Under: Flotsam and Jetsam, Delphi
  • Interesting News Item of the Week:  Microsoft is buying Skype.  I’m a huge fan of Skype.  I like it best as an IM client, and as a teleconferencing system as well.  The creepy feeling you get when someone is on Skype in a conference room using a nice set of speakers takes some getting used to.  It’s a bout 342 times better than a POTS conferencing system.  Anyhoo – I’ll be curious to see if MS rewrites the currently-written-in-Delphi Windows clients and continues to support non-Windows clients as well. 
  • New Delphi Blog of the Week: Delphi Sorcery  and I’ll give him Cool Delphi Code of the Week as well. 
  • As you may have noticed, I’ve added one of those little tool bars to my posts that let’s you Like/Add/Tweet/whatever my postings.  I do this in a self-glorifying attempt to get you to broadcast my stuff more.  It was amazingly easy to do with AddThis.  I trust you all will take the hint. 
  • I thought this was pretty impressive.  How long can it be before everything is just a Javascript application running in a browser?  I’ve been saying for years that Javascript is to the browser what assembler is to the CPU.

My Book

A Pithy Quote for You

"Science is the belief in the ignorance of experts."    –  Richard P. Feynman

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