Amazon.com Widgets June 2011

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;

{$APPTYPE CONSOLE}

uses
  SysUtils;


type

  ITestInterface = interface
    procedure DoThisPrivateThing;
    procedure DoThisPublicThing;
  end;

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

{ TTestClass }

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

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

var
   Test: ITestInterface;

begin
  try
    Test := TTestClass.Create;
    Test.DoThisPrivateThing;
    Test.DoThisPublicThing;
    Readln;
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
end.

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.

Introduction

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:

var
  MyPizzaOven: TPizzaOven;
  MyPizza: TPizza;
begin
  MyPizza := TPizza.Create;
  MyPizzaOven := TPizzaOven.Create(MyPizza);
end;

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;

interface

uses
        Spring.DI
      ;

  function ServiceLocator: TContainer;

implementation

var
  FContainer: TContainer;

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


end.

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;

interface

type
  IMathService = interface
    ['{BFC7867C-6098-4744-9774-35E0A8FE1A1D}']
    function Add(a, b: integer): integer;
    function Multiply(a, b: integer): integer;
  end;

implementation

uses
  uServiceLocator;
type

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

{ TNormalMathServiceImplemenation }

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

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

procedure RegisterNormalMathService;
begin
  ServiceLocator.RegisterComponent<TNormalMathServiceImplemenation>.Implements<IMathService>('Normal');
  ServiceLocator.Build;
end;

initialization
  RegisterNormalMathService;

end.

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;

interface


implementation

uses
    uServiceLocator, uNormalMathService;

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

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

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


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

end.

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.

Conclusion

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:

image

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. 

image

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!

My Book

A Pithy Quote for You

"We all want progress, but if you're on the wrong road, progress means doing an about-turn and walking back to the right road; in that case, the man who turns back soonest is the most progressive."    –  C. S. Lewis

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