Amazon.com Widgets Unit Testing

The Delphi Unit Test Project

By Nick at August 17, 2013 07:02
Filed Under: Delphi, Unit Testing, Software Development

In a previous post, I humbly suggested that Embarcadero publish their unit tests for Delphi.  I still think it is a good idea, but I understand if they don’t do it.  They do have a lot to do.

So I thought – after suggestions from folks that read the post, including Kenneth Cochran – that it would be a good idea to just go ahead and start our own community project.  So I did.

The Delphi Unit Tests Project

This is a pretty straight-forward project – it is merely a set of unit tests for Delphi’s RTL.  You can find out the basics on the home page of the wiki, where you’ll also find further information about writing tests, etc.  It’s a wiki, so it will continue to be expanded. I’m kind of weird in that I actually enjoy writing unit tests, so I’ve been adding tests over the last week or so.

This is a community project based on Mercurial.  That means that anyone can fork it, add tests, and then submit a pull request.  We’ve already had four or five submissions, and I’m really appreciative.  It’s quite easy to contribute, and you can write tests for anything you like.  Any submitted tests must pass, of course.

We are also using the new Delphi unit testing framework, DUnitX.  It is still a bit rough around the edges, but hopefully this will be an impetus to get it fully up to speed.  I’ve volunteered to write the GUI runner, but there are some architectural issues that need to be taken care of.  Right now, you can output to NUnit xml and the console.  DUnitX is attribute based and really easy to use.

Things I’d  like to eventually get done:

  • I’d like to get at least one test for everything we can in the RTL.
  • I’d like to figure out a way to have tests written for QualityCentral reports.  The tests could “pass”, proving the bug exists, and then when they “fail”, that could show that the bug has been fixed. 
  • I’d love to see our tests eventually get integrated into the Embarcadero internal build.  That would be really cool.

In any event, come join the cause and write a test.  Even one single test would be fine!

In Which I Argue That Embarcadero Should Open Source Their Unit Tests

By Nick at July 27, 2013 04:27
Filed Under: Software Development, Delphi, Unit Testing

All good developers write unit tests.  The Delphi team is no different.  The team has a suite of unit tests for the RTL and a very, very large set of tests for the compiler.  The tests for the RTL are, to a large degree, DUnit based.  The compiler tests are a bit different, as they date back well before DUnit even existed.  They are a set of console applications that write out PASS or FAIL to the standard output depending on whether the test passed or failed. I believe that this suite of tests also tests a lot of the lower level RTL.   I know the QA team doesn’t like to test the RTL using a tool that depends heavily on the RTL itself.

So anyway, this suite of tests exists.  They get run constantly as part of a continuous integration process at Embarcadero.  And the suite gets expanded as time goes by.  When I managed the R&D team, I even contributed to the test suite myself.

But given that you can’t ever have enough unit tests, and that like all companies, Embarcadero has limited resources, the test suite doesn’t expand fast enough.  (Actually, I suppose no test suite expands fast enough, right?)

So I have a plan:  Embarcadero should open source their unit test suite and accept inputs from the community. 

Here’s why I think they should do that.

  • It will enable the community to expand the suite of tests -- As I noted above, every unit test suite is too small and doesn’t cover enough of the possibilities.  Embarcadero can continue to expand their test suite by themselves, or they can harness the power of the community to write tests.  The current public code repositories allow for forking and pull requests, and it would be dead simple for me or anyone to fork the project, add tests, and then issue a pull request.  This will allow people to write tests for their favorite parts of the RTL, and as will be discussed below, allow them to report bugs by writing tests that should pass but fail.  Many hands make for light work.
  • It will help build customer confidence in the quality of the Delphi RTL –A public facing, expanding suite of tests with community participation will build confidence in the quality of the product.  If people know and see that the RTL and the compiler are bathed in a complete, growing suite of tests, they’ll feel better about the product.  If they see how thorough and complete the suite is, they’ll know that the product they use is solid.
  • It will help people learn the proper way to use the product – One of the things that unit tests can do is to provide a sort of “documentation” for the things being tested.  They can illustrate the proper way to use the RTL code, and show customers the things that can be done that they might not have known about.  A nice suite of tests for a new RTL unit or class will help customers see how to use the class and what it is supposed to do.
  • It will encourage the team at Embarcadero to write more tests – When Lee Ioccoca took over a failing Chrysler in the late 1970s, one of the first things he did was throw down the gauntlet in front of the company: He would give all buyers a 10 year, 100,000 mile warrantee for the car.  That was an impetus to the entire company to improve quality.  Publishing the compiler and RTL test suites will have the same effect on the team at Embarcadero.  If the tests are public, then the team will feel the pressure (the good kind) to ensure that any new code has tests.  The community won’t want to see a new RTL unit without any tests (Will we, guys, right?)
  • It will enable people to report bugs in a better and more useful way – The easiest kind of bug to fix is one with a failing unit test.  If things got really rolling, customers could write unit tests that reveal bugs, Embarcadero could fix the bugs, and then the test would be a true regression test.  That would be awesome.  Customers could even use the tests to suggest fixes.  Having all the tests would enable them and Embarcadero to be more confident in a suggested fix.

I could think of some objections that they might have.  Here are some of those objections, along with reasons why those objections should be ignored. 

  • “The code isn’t ready for public consumption” – No one cares.  Seriously.  Anyone in the community that complains about the quality of the tests or lack of coverage can get to work and fix things.  No complaining if you aren’t helping.  The tests are probably better than most, and even if they are bad, they’ll get fixed. 
  • “It’s too much work for us” – No it isn’t. “We don’t have the time.” Yes you do.  It shouldn’t take more than an hour to gather the tests and post them on BitBucket or GitHub.  (Please, not SourceForge.  And by the way, whatever you do – for the love of Baby Elvis  -- don’t post it in Subversion. Only Git or Mercurial will allow for the community involvement you want and need.).  Plus, that small investment will enable an army of developers to submit pull requests with new tests.  Those tests can be quickly reviewed and accepted.  It will take less time to accept tests than it will to write them.  Shoot, you could even enlist trusted community members to help out.  I can think of at least one Embarcadero MVP (cough, me, cough) that would be willing to help be a gatekeeper.
  • “This is internal, private stuff that we shouldn’t be sharing”.  No, this is exactly the kind of stuff you should be sharing.  There are no trade secrets here.  The tests are useless without the products.  There is nothing to be lost by doing this, and much to be gained.  This is the kind of thing that a modern, forward-looking company would do.  Be a leader.  Be brave and bold!

I thought long and hard for reasons why Embarcadero shouldn’t open source their tests, and I couldn’t think of any.  Seriously, I can’t think of a downside here.

So how about it, guys?

Service Locator is Indeed an Anti-pattern

By Nick at June 06, 2013 00:20
Filed Under: Delphi, Patterns, Software Development, Unit Testing

As you know, I love Dependency Injection.  I wrote a whole series of articles on it using the Spring for Delphi framework, and in my previous position instituted its pervasive use in the large project there. I’m scheming to integrate it into the legacy app I work on now.  I bought and read the definitive book on the subject:

But there was always one thing that bugged me -- In Mark Seemann's book and in this article (Service Locator is an Anti-pattern) he argues against the use of a ServiceLocator – that is, a class that grabs instances out of the DI Container and hands them to you for your use.  I never really agreed, as I didn’t see any other way to do it – of course you needed to grab instances out of the container via a Service Locator pattern.  How else would you do it? I mean, you can do Constructor Injection and all, but at some point you need to grab an instance of something, right?  I had read his stuff, read the comments and arguments on the topic, but was never really persuaded.  But then again, maybe I was missing something.  The question of “how” always held me back.

Well, I was working on some demo code for my book, and out of the blue, all of a sudden, it hits me:  Seemann is right.  The ServiceLocator is an anti-pattern, mainly because it is pretty much unneeded. 

Here’s what happened. 

First thing: if you go to my demo code on BitBucket, you’ll see a Dependency Injection demo there that uses the ServiceLocator to grab instances of registered classes.  It’s cool – you can understand the basics of DI by looking at it.  You can properly decouple the code and end up with nothing but a unit of interfaces in your uses clause.  Nice.  I even did a CodeRage presentation using this basic code.  That code illustrates how you can use a DI Container and the ServiceLocator to create loosely coupled code.  No worries.  However, you’ll notice that the calls to the ServiceLocator kind of become replacements for calls to Create

Only you can do the same thing with no ServiceLocator calls. 

Second:  The Delphi Spring Container has a set of methods that I confess I never quite understood:

 

    function InjectConstructor(const parameterTypes: array of PTypeInfo): TRegistration<T>; overload;
    function InjectProperty(const propertyName: string): TRegistration<T>; overload;
    function InjectMethod(const methodName: string): TRegistration<T>; overload;
    function InjectMethod(const methodName: string; const parameterTypes: array of PTypeInfo): TRegistration<T>; overload;
    function InjectField(const fieldName: string): TRegistration<T>; overload;

 

These methods allow you to inject (duh) different items into your classes and automatically instantiate them as a result.  I knew they were there, I knew that they were useful, but I never understood completely why they were in there.  You could pretty much get along without them because you had the ServiceLocator to grab anything you need.  

I was reading Mark Seemann’s book again, and reading about how you should be using constructor injection everywhere, and how you need to push the creation of your component graph all the way back to the composite root. In Delphi, that means all the way back to the first line of the DPR file.  And if you do that, you could end up with this monster constructor that requires every single class your application needs.  And it was this notion that made me think “The ServiceLocator is necessary to get rid of that huge constructor.”

So I confess I never quite got it. 

But yesterday, I’m working on sample code for my book, and of course, I have to show how the above methods work.  I’m working up demos (I’ll show a simple one below that illustrates the whole thing) and it hits me:  The key to the whole notion of a ServiceLocator being an anti-pattern lies in what these five methods can do. 

And basically what they can do is this:  They can cause the creation of every single class needed for your application during the registration process.  They can completely eliminate the need for you to ever call the ServiceLocator (with one exception, discussed below) because if you can call the ServiceLocator, you can use these methods to register the connection between what you need the ServiceLocator for and the registration process.

Put another way, every call to the ServiceLocator can be replaced by a registration call.  You don’t need the ServiceLocator because the registration process alone is enough.

So I think a simple example is in order.  I’ll try to keep it short and sweet. 

Consider the following unit of code:

unit uNoServiceLocatorDemo;

interface

uses
      Spring.Container
    , Spring.Services
    , Spring.Collections
    ;

type
  IWeapon = interface
  ['{0F63DF32-F65F-4708-958E-E1931814EC33}']
    procedure Weild;
  end;

  IFighter = interface
  ['{0C926753-A70D-40E3-8C35-85CA2C4B18CA}']
    procedure Fight;
  end;

  TBattleField = class
  private
    FFighter: IFighter;
  public
    procedure AddFighter(aFighter: IFighter);
    procedure Battle;
  end;

  TSword = class(TInterfacedObject, IWeapon)
    procedure Weild;
  end;

  TKnight = class(TInterfacedObject, IFighter)
  private
    FWeapon: IWeapon;
 public
    constructor Create(aWeapon: IWeapon);
    procedure Fight;
  end;

implementation

{ TBattleField }

procedure TBattleField.AddFighter(aFighter: IFighter);
begin
  FFighter := aFighter;
end;

procedure TBattleField.Battle;
begin
  WriteLn('The Battle is on!');
  FFighter.Fight;
end;

{ TKnight }

constructor TKnight.Create(aWeapon: IWeapon);
begin
  inherited Create;
  FWeapon := aWeapon;
end;

procedure TKnight.Fight;
begin
  WriteLn('The knight swings into action!');
  FWeapon.Weild;
end;

{ TSword }

procedure TSword.Weild;
begin
  WriteLn('"Swoosh" goes the sword!');
end;

initialization

  GlobalContainer.RegisterType<TSword>.Implements<IWeapon>('sword');
  GlobalContainer.RegisterType<TKnight>.Implements<IFighter>('knight');


end.

 

Here we have some classes that are all nicely decoupled.  Our registrations are neatly named.  The classes use constructor injection to ask for their dependencies, and the TKnight and the TSword are nicely registered, just waiting to be grabbed and used in a decoupled way using the ServiceLocator.  All is great.  And then in order to actually have our cast of characters do anything, you might do something like this:

 

procedure FightBattle;
var
  Battlefield: TBattleField;
  TempKnight: IFighter;
  TempSword: IWeapon;
begin
  Battlefield := TBattleField.Create;
  try
    TempKnight := ServiceLocator.GetService<IFighter>;
    TempSword := ServiceLocator.GetService<IWeapon>;
    TempKnight.Weapon := TempSword;
    Battlefield.AddFighter(TempKnight);
    Battlefield.Battle;
  finally
    Battlefield.Free;
  end;
end;

 

You need a knight and a sword?  Well, just call the ServiceLocator, grab the sword, arm the knight, add him to the battle, and off it goes.  You get this:

image

 

It all works, and it is all decoupled.  But you are still using the ServiceLocator

The argument against the ServiceLocator is pretty simple: It’s a singleton, singletons are global variables, and global variables are bad. (That’s a gross oversimplification – read the article and the comments for a better discussion….) Plus, if you don’t need it, why use it?

Well, you don’t need it.  Watch.

First thing to note is that Seeman says you should have one call to the ServiceLocator at the very root of your application.  You get one shot.  We’ll see that one shot below.

Second, let’s change how we register our classes and interfaces: 

 

 GlobalContainer.RegisterType<TBattleField>.InjectMethod('AddFighter', ['knight']);

  GlobalContainer.RegisterType<TSword>.Implements<IWeapon>('sword');
  GlobalContainer.RegisterType<TKnight>.Implements<IFighter>('knight').InjectConstructor(['sword']);

 

Some things to note:

  • We only changed the way things were registered.  We didn’t change the class structure or relationships at all.
  • We are now registering TBattlefield.  We need to do that for two reasons.  First, in our very simple example, it is the “root” of the application.  It is the place where everything starts in relation to our object graph.  To get an instance of TBattlefield, we make our one allowable call to ServiceLocator.  Second, we need to inject a method, as discussed next.
  • Into TBattleField we have injected a method, specifically the AddFighter method.  Here’s what the call to InjectMethod does -- it says “When the container creates an instance of TBattlefield, look up the AddFighter method and pass to it as its parameter an instance of the interface named ‘knight’”  Thus, when the container creates an instance of TBattleField for you, the AddFighter method will be automatically called, and a valid weapon will be passed to it.  There goes one call to the ServiceLocator
  • The second call to ServiceLocator is eliminated by the call to InjectConstructor.  This registration now means “When you ask for an IFighter, create an instance of TKnight, and when you do, pass the constructor an IWeapon from the registered type named ‘sword’”  Again, there goes the other call to ServiceLocator

Thus we’ve used the container to “wire up” all the dependencies and ensure that they are properly created before the main class or any other class is even asked for.  The call to GlobalContainer.Build in the DPR file will ensure this takes place. 

Finally, we run everything with the much simpler and cleaner:

 

procedure FightBattle;
var
  Battlefield: TBattleField;
begin
  Battlefield := ServiceLocator.GetService<TBattlefield>;
  try
    Battlefield.Battle;
  finally
    Battlefield.Free;
  end;
end;

 

And there’s our one call to ServiceLocator at the very root of our application (FightBattle gets called in the DPR file as this is a console application). 

You can do the same thing with constructors – you can call InjectConstructor, passing the names of registrations for each of the parameters in the constructor.  And if need be, for both InjectConstructor and InjectMethod, you can add in non-registered parameters such as integers and strings, etc.

Bottom line:  Use the injection methods and the container to connect up your classes and inject dependencies, not the ServiceLocator. 

And I haven’t even yet mentioned how you can replace the InjectXXXXXX calls with attributes. 

Okay, now I feel better since I agree with Mark Seemann over at http://blog.pleoh.dk.  Being in disagreement with a smart guy like that isn’t a comfortable place to be. 

Stuff I’ve Been Reading #1

By Nick at September 08, 2012 07:33
Filed Under: Software Development, Unit Testing, General, Book Review, Stuff I've Been Reading

I’m Writing a Book

By Nick at September 03, 2012 08:09
Filed Under: Delphi, General, Software Development, Unit Testing

I’ve decided that my first official act as an Embarcadero MVP will be to write a book.

Here’s some details:

  • You can see the outline and a brief discussion here.
  • I’m writing it on LeanPub.  LeanPub is very cool.  They make it very easy for a guy like me to write a book – that is, a guy who doesn’t really know anything about the process of actually producing a book, as opposed to the content in the book.
    • LeanPub outputs to PDF, MOBI, and ePub formats. 
    • Eventually I’ll probably put the book on Lulu or some other on-demand publisher to allow folks to get physical copies if that is what they prefer.
    • You can view the outline on the LeanPub page
    • The book will contain a lot of content from my blog, but of course I’ll enhance and improve that material.  And there will, of course, be a lot of new material.
    • Many of the topics will include the Delphi Spring Framework, DUnit, ,and other cool new frameworks. 
  • I’ve actually been working on the book for a while, but once I saw LeanPub, I knew that I had to make the move official.
  • You can sign up to find out when the book gets published.  You can also tell me how much you are willing to pay for the book. 
  • LeanPub lets you very easily update and enhance the content.  So I’ll probably publish well before I’m done and then update as I go along.
    • This will allow early buyers (who will likely pay a lower price) to provide feedback.  Sort of like a “beta test” program.
    • It will also let me correct mistakes
    • And of course all purchasers will always have access to the latest and greatest version.
  • I’ll naturally incorporate feedback as much as I can.  Your help will make the book better for everyone.
  • I don’t know yet what I’ll charge and when.  That’s another cool feature of LeanPub – I can experiment with the pricing.  A lot of books on LeanPub have a variable, choose-your-own price models.

So I’m pretty excited.  LeanPub really was the catalyst to finally move ahead and make my idea public. 

So give the book a look, sign up to receive updates, and please feel free to provide feedback – I’m interested in what the community has to say.  As long as you are polite and professional, of course.  Winking smile

Cool New Tool: Delphi Code Coverage

By Nick at August 18, 2012 10:27
Filed Under: Delphi, Software Development, Unit Testing

Code Coverage is an interesting topic – Wikipedia defines it as “the degree to which the source code of a program has been tested.”  The idea is that you want to measure what percentage of the lines of code in your application are executed when you run your test suite.  The “perfect” test suite would execute every single line of code in your codebase.  Being able to definitively measure that goes a long way towards validating your testing suite and giving you confidence that your tests are thorough and testing everything that needs to be tested.

So I was really happy to run across the Delphi Code Coverage tool. I was intrigued and interested, so I downloaded it and gave it a look. And I really liked it.  I decided to run it through its paces by checking the code coverage of the unit tests for my THTMLWriter project. It didn’t take me long to figure out how to use it.   It’s written by Christer Fahlgren.  He blogged about it back in 2010.  It has a couple of other committers, and it’s been an active project throughout out 2012

The project includes this note: “The 1.0 release was made possible through the generous support of DevFactory.” I thought that was cool, and so I encourage you to go to their website and check out their services.

Some things to note off the bat:

So what did I do?  Well, first I pulled the source to make sure I had it.  Then, I went ahead and downloaded the RC7 build, which has one file in it:  codecoverage.exe.  I took that file and put it in a folder along my path so I can call it wherever I need it.

Then, I read the nice simple documentation.  I was just testing it out, so I ran everything manually via the IDE just to see how it all worked.  Eventually, you’d want to integrate this into your continuous integration. So here is a quick rundown of what I did and what I found. 

First, I opened up the project options for my THTMLWriter unit test application and told the Linker to create a MAP file for the project when I build it. The tools uses the MAP file to trace all the code paths that the application under test uses.

Next, I looked for the appropriate command  line switches. 

  • I used it –e switch to name the executable that would run. 
  • I used the –m switch to name the *.map file.
  • I used the –u switch to tell the tool what code unit I wanted analyzed.  Note that the switch wants the unit name, not the file name.  You can list as many units as you want after this switch.  Alternatively, you can use the –uf switch to point to a text file that has a list of unit names (one per line) to be examined.  In my case, I’m interested in the code coverage for the uHTMLWriter.pas unit.
  • I used the –html switch to indicate that I wanted the output to be an HTML file.  This would make it easier for me to look at the results in this “by hand” method of running things. 

The resulting command line was as follows:

codecoverage -e HTMLWriterTestAppTests.exe -m HTMLWriterTestAppTests.map -u uHTMLWriter -html

Note that the above command line assumes that the current directory of your command prompt is the directory where the files in question are located.  I actually put the command line in a small batch file in the same directory.

So then I executed the command.  The tool popped up the GUI Runner for DUnit, I pressed the Run button, the tests ran, and when they were done, the tool finished up and produced some output in the form of an HTML file.  (It also provided a FastMM dialog at the end of its run, which took a few seconds to appear).

image

As noted, the result was two HTML files -- one summary file:

image

and a file that shows me the coverage for the uHTMLWriter unit.  That has a header in it that tells me that I have 98% code coverage.  Not bad!

image

But the real fun part is that the file contains a complete listing of the unit, color-coded to indicate which lines were executed (in green) and which weren’t (in purple). So 2% of my code isn’t covered?  So I scanned the file and came across this:

image

Looks like I never wrote a unit test for the OpenLabel method that takes a string parameter.  (I have one for the parameter-less OpenLabel).  Okay, so I went back, wrote a unit test for that one, and re-ran the code coverage tool, and now I have code coverage for that method:

image

 

Nice!  The tool also pointed out that I don’t test that a number of exceptions get properly raised, so I’ll get working on those, too.  I’d like to be able to run the report and have it return 100% for my coverage. 

Overall, this is a nice and powerful tool to help you make sure that your unit tests really are running every line of code in whatever you are unit testing.  It’s another great contribution to the Delphi community.  Thanks, Christer.

TVirtualInterface: A Truly Dynamic and Even Useful Example

By Nick at June 30, 2012 08:25
Filed Under: Delphi, Software Development, Unit Testing

Introduction

This is the third article in a series about using TVirtualInterface.  The two previous articles are TVirtualInterface: Interfaces without an Implementing Class and TVirtualInterface: Next Steps.

Okay, enough with the not-all-that-useful examples.  I mean, the previous articles were illustrative, but not really “real-world useful”.

The true usefulness of TVirtualInterface occurs when you use it to create code where you have no idea what interface the user of your code is going to try to implement.  All the examples so far have shown only implementing classes where you do know which interface is being used.  The exception so far is the TReportingVirtualInterface example which reports information on any interface you pass to it.  Since we have proven that you can use TVirtualInterface to do something useful, let’s take it a step further.

A practical use of TVirtualInterface is to create a mocking library for unit testing.  I’ve mentioned numerous times the Delphi Mocks Framework by Vince Parrett of FinalBuilder fame.  Another excellent implementation of a mocking framework (as well as a bunch of other very innovative and interesting stuff) is by Stefan Glienke as part of his Delphi Sorcery framework.  Both of these use TVirtualInterface to provide a mock implementation for any interface (though the Delphi Sorcery code implements its own version of TVirtualInterface that works with Delphi XE – very cool).  Both, of course, allow you to pass them any interface, and they’ll happily mock your interface for unit testing purposes.  So why not do an example here of a very simple mocking object that you can actually use if you want?

ISimpleStub

A while back I wrote an article called The Vocabulary of Unit Testing.  In it I described the distinction between a stub and a mock.  I defined a “stub” as “a fake that has no effect on the passing or failing of the test, and that exists purely to allow the test to run.”  So, how about we build a universal stub – a class that can pretend to be any interface you want, and not do anything at all.  That can’t be that tough, can it?

Well, we already have a class that can implement an interface, but we need to find a way for that class to actually be the interface.  If you want a stub, the stub has to actually be the interface type you are trying to stub out, right?

First, since we always code against abstractions, let’s declare an interface:

  ISimpleStub<T> = interface
  ['{6AA7C2F0-E62F-497B-9A77-04D6F369A288}']
    function InterfaceToCall: T;
  end;

And then let’s implement it with a descendent of TVirtualInterfaceEx<T>:

  TSimpleStub<T: IInvokable> = class(TVirtualInterfaceEx<T>, ISimpleStub<T>)
  protected
    procedure DoInvokeImpl(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue); override;
  public
    function InterfaceToCall: T;
  end;

Because TSimpleStub<T> descends from TVirtualInterfaceEx<T>, it can implement any interface you pass to it.  It thus overrides DoInvokeImpl from  TVirtualInterfaceEx<T> as well as implementing InterfaceToCall from ISimpleStub<T>.

First, let’s look at DoInvokeImpl:

procedure TSimpleStub<T>.DoInvokeImpl(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue);
begin
  // Since this is a pure stub, don't do anything!
end;

Not much to see here  – it doesn’t do anything.  And for a stub, that is fine.  That’s exactly what stubs are supposed to do – nothing.  We don’t care what happens when the methods get called, you just need to actually be able to call them.

That’s where the InterfaceToCall function comes in.  The class knows about the type of interface being stubbed because we are passing that type in as a parameterized type.  The class itself knows how to implement that interface.  There has to be a way to get an actual reference to that implemented interface, right?  This is where the InterfaceToCall method comes in:

function TSimpleStub<T>.InterfaceToCall: T;
var
  pInfo : PTypeInfo;
begin
  pInfo := TypeInfo(T);
  if QueryInterface(GetTypeData(pInfo).Guid, Result) <> 0 then
  begin
    raise Exception.CreateFmt('Sorry, TSimpleStub<T> is unable to cast %s to its interface ', [string(pInfo.Name)]);
  end;
end;

Since TSimpleStub<T> knows the type that T is, you can call QueryInterface on the type information about T itself to get a reference to the interface in question.  And of course, once you have that, you can pass that reference anywhere you need to stub out the interface – normally as part of unit testing.

So now, you can safely call methods on the stubbed interface.  For instance, given this interface:

IActuallyUseful = interface(IInvokable)
  ['{16F01BF0-961F-4461-AEBE-B1ACB8D3F0F4}']
  procedure SayHello;
  function ReverseString(aString: string): string;
  function Multiply(x, y: integer): integer;
end;

Writeln('Implementing a TSimpleStub');
SimpleStub := TSimpleStub<IActuallyUseful>.Create;
WriteLn('Nothing should appear between this and the next statement');
SimpleStub.InterfaceToCall.SayHello;
SimpleStub.InterfaceToCall.Multiply(4, 4);
SimpleStub.InterfaceToCall.ReverseString('blah');
WriteLn('Nothing should appear between this and the above statement');
WriteLn;

Nothing happens when you call the interface methods, but that’s by design:  stubs should do nothing.  What you can do is call them as part of your unit testing:

begin
  ...
  MyClassUnderTest := TSprocketThatTakesAnIWhatever.Create(SimpleStub.InterfaceToCall)
  ...
end;

TSimpleMock

Okay, so there’s a useful, dynamic way to use TVirtualInterfaceTSimpleStub<T> will work great for a stub that you expect absolutely nothing from.  But sometimes you need a fake interface that does something more than just existing, and when that is the case, you are creating a mock.  In my unit testing definitions article, I defined a mock as “a fake that keeps track of the behavior of the Class Under Test and passes or fails the test based on that behavior.”  Thus, a mock needs to do more than exist like a stub –  it needs to behave in a way that you can define.   So how about we take TSimpleMock<T> and make it do a basic mocking function – responding in a specific way to a specific input.

One of the most common things that a mock interface does is to respond with “this” when passed “that”.  How about we create a simple mock class that lets you define a specific response to a method call?

First, of course, is an interface to code against:

 

  ISimpleMock<T> = interface(ISimpleStub<T>)
  ['{9619542B-A53B-4C0C-B915-45ED140E6479}']
    procedure AddExpectation(aCallName: string; aReturnValue: TValue);
  end;

The interface augments (“inherits from” is not quite right with interfaces) ISimpleStub<T> and adds the AddExpectation method.  This is the method that we’ll use to tell the mock out to respond when and interface method gets called. 

Here’s the implementing class:

  TSimpleMock<T: IInvokable> = class(TSimpleStub<T>, ISimpleMock<T>)
  private
    FActions: TDictionary<string, TValue>;
  protected
    procedure DoInvokeImpl(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue); override;
  public
    constructor Create;
    destructor Destroy; override;
    procedure AddExpectation(aCallName: string; aReturnValue: TValue);
  end;

The first thing to notice is that TSimpleMock<T> inherits  from TSimpleStub<T>, thus enabling it to “be” any interface it wants as our stub was. And of course it also implements the  AddExpection method.  It takes as parameters the name of the method on the interface that you can call, as well as a return value for when that method gets called.  In this way you can define the behavior of the mock class however you want.

This very simple mocking example assumes that you are going to be mocking only function calls as methods on an interface. Within the confines of our simple example, it doesn’t make sense to mock procedures – they basically don’t do anything as far as the simple example is concerned.  Real mock frameworks are able to keep track of whether a procedure is called, how many times it does get called, and other things associated with procedures.  This simple example also doesn’t care what parameters you pass in, it will merely return a value whenever the named method is called.   Remember, this is a simple – but useful in specific situations -- example.  Winking smile 

The implementation of TSimpleMock<T> is pretty, well, simple.  Internally, it uses a TDictionary<TKey, TValue> to keep track of the method calls and the resulting responses that are added via the AddExpectation call.  Here is the implementation of AddExpectation :

procedure TSimpleMock<T>.AddExpectation(const aCallName: string; aReturnValue: TValue);
begin
  FActions.Add(aCallName, aReturnValue);
end;

When you add an expectation, the class keeps track of it.  When you then call that method on the interface, it is able to retrieve the expected return value from the dictionary and return it:

procedure TSimpleMock<T>.DoInvokeImpl(Method: TRttiMethod; const Args: TArray<TValue>; out Result: TValue);
begin
  Result := FActions[Method.Name];
end;

(The obvious shortcoming here is no error handling – you’ll get an exception if you try to call a method on the interface that doesn’t  have an expectation entry.  Another shortcoming is that the parameters passed mean nothing – a real mocking framework would be able to provide specific responses for specific parameter inputs.    I’ll leave correcting this problem as an exercise to the reader.  Smile )

So now, when we exercise this class, it will actually return stuff that you tell it to:

This code:

WriteLn('IActuallyUseful with ISimpleMock');
SimpleMock := TSimpleMock<IActuallyUseful>.Create;
SimpleMock.AddExpectation('Multiply', 99);
SimpleMock.AddExpectation('ReverseString', 'This is actually working');
WriteLn(SimpleMock.InterfaceToCall.Multiply(6, 7));
WriteLn(SimpleMock.InterfaceToCall.ReverseString('This does not matter'));
WriteLn;

has the following output:

image

Note that the responses are not what you think they would be based on the parameters (you think that 6 times 7 would return 42…), but what you told them to be in the AddExpectation call.

Now, you can use ISimpleMock<T> to provide specific feedback for a given method call.  Maybe you have an interface method which returns a Boolean value that you want to test. You can use ISimpleMock<IBooleanMethod> to test what happens when the method returns True as well as when that method returns False

Conclusion

Okay, so there you have it:  A useful implementation of TVirtualInterface.  Though the above examples are really simple, they can actually be used in real world testing – particularly the ISimpleStub<T> implementation. Stubbing is common in unit testing, and even though it is a very basic implementation, it can be used to stub out any interface.

None of this is useful if you know what interface you need and how you are going to implement it.  But there are cases when you don’t know what interface you will need for a particular problem, and you need to be able to flex to whatever interface the situation calls for.  Mocking and stubbing are perfect examples.  That’s a powerful and useful thing to be able to do.  Hopefully this little series has helped you see that.

The Vocabulary of Unit Testing

By Nick at May 03, 2012 14:20
Filed Under: Delphi, Software Development, Unit Testing

I talk a lot about unit testing.  And why shouldn’t I?  Unit testing is the key to writing clean, maintainable code.  If you concentrate on writing code that is easily testable, you can’t help but end up with decoupled, clean, high-quality code that is easy to maintain.  What’s not to like?

But sometimes, there are questions over the definition of terms when it comes to unit testing.  For instance, what, exactly, is a “unit”?  What does “mocking” mean?  How do I know whether I actually am doing unit testing?  In this article, I try to clear up some of those definitions.

What is a “Unit”?

The first question that comes up when discussing unit testing is, well, what is a unit?  You can’t do unit testing without knowing what a unit is.

When it comes to unit testing, I view a “unit” as any discreet  module of code that can be tested in isolation.  It can be something as simple as a stand-alone routine (think StringReplace or IncMonth), but normally it will be a single class and its methods.  A class is the basic, discrete code entity of modern languages. In Delphi, classes (and records which are conceptually very similar) are the base building blocks of your code.  They are the data structures that, when used together, form a system. 

In the world of unit testing, that class is generally referred to as the “Class Under Test (CUT)” or the “System Under Test”.  You’ll see those terms used extensively – to the point where it is strongly recommended that you use CUT as the variable name for your classes being tested.

Definition:  A unit is any code entity that can be tested in isolation, usually a class. 

Am I Actually Doing Unit Testing?

So when you are doing unit testing, you are generally testing classes. (And for the sake of the discussion, that will be the assumption hereafter…)  But the key thing to note is that when unit testing a class, you are unit testing the given class and only the given class.   Unit testing is always done in isolation – that is, the class under test needs to be completely isolated from any other classes or any other systems.  If you are testing a class and you need some external entity, then you are no longer unit testing.  A class is only “testable” when it’s dependencies can be and are “faked'”, and thus tested without any of its real external dependencies.  So if you are running what you think is a unit test, and that test needs to access a database, a file system, or any other external system, then you have stopped doing unit testing and you’ve started doing integration testing. 

One thing I want to be clear about:  There’s no shame in doing integration testing.  Integration testing is really important and should be done.  Unit testing frameworks are often a very good way to do integration testing.  I don’t want to leave folks with the impression that because integration is not unit testing, you shouldn’t be doing it – quite the contrary.   Nevertheless, it is an important distinction.  The point here is to recognize what unit tests are and to strive to write them when it is intended to write them. By all means, write integration tests, but don’t write then in lieu of unit testing. 

Think of it this way:  Every unit test framework – DUnit included – creates a test executable.  If you can’t take that test executable and run it successfully on your mother’s computer in a directory that is read only, then you aren’t unit testing anymore. 

Definition: Unit testing is the act of testing a single class in isolation, completely apart from any of it’s actual dependencies.

Definition: Integration testing is the act of testing a single class along with one or more of its actual external dependencies.

What is an Isolation Framework?

Commonly, developers have used the term “mocking framework” to describe code that provides faking services to allow classes to be tested in isolation.  However, as we’ll see below, a “mock” is actually a specific kind of fake class, along with stubs.  Thus, it is probably more accurate to use the term “Isolation Framework” instead of “Mocking Framework”.  A good isolation framework will allow for the easy creation of both types of fakes – mocks and stubs. 

Fakes allow you to test a class in isolation by providing implementations of dependencies without requiring the real dependencies. 

Definition: An isolation framework is a collection of code that enables the easy creation of fakes. 

Definition: A Fake Class is any class that provides functionality sufficient to pretend that it is a dependency needed by a class under test.  There are two kind of fakes – stubs and mocks.

If you really want to learn about this stuff in depth, I strongly recommend you read The Art of Unit Testing: With Examples in .Net by Roy Osherove.  For you Delphi guys, don’t be scared off by the C# examples -- this book is a great treatise on unit testing, and gives plenty of descriptions, proper techniques, and definitions of unit testing in far more detail than I’ve done here.  Or, you can listen to Roy talk to Scott Hanselman on the Hanselminutes podcast.  I openly confess that this blog post is a faint echo of the great stuff that is included in both the book and the podcast.  If you really want to get your geek on, get a hold of a copy of xUnit Test Patterns: Refactoring Test Code by Gerard Meszaros.  This heavy tome is a tour de force of unit testing, outlining a complete taxonomy of tests and testing patters.  It’s not for the faint of heart, but if you read that book, you’ll know everything there is to know and then some. 

Stubs

A stub is a class that does the absolute minimum to appear to be an actual dependency for the Class Under Test.  It provides no functionality required by the test, except to appear to implement a given interface or descend from a given base class.  When the CUT calls it, a stub usually does nothing.  Stubs are completely peripheral to testing the CUT, and exist purely to enable the CUT to run.  A typical example is a stub that provides logging services.  The CUT may need an implementation of, say, ILogger in order to execute, but none of the tests care about the logging.  In fact, you specifically don’t want the CUT logging anything.  Thus, the stub pretends to be the logging service by implementing the interface, but that implementation actually does nothing.  It’s implementing methods might literally be empty.  Furthermore, while a stub might return data for the purpose of keeping the CUT happy and running, it can never take any action that will fail a test.  If it does, then it ceases to be a stub, and it becomes a “mock”.

Definition: A stub is a fake that has no effect on the passing or failing of the test, and that exists purely to allow the test to run.

Mocks

Mocks are a bit more complicated.  Mocks do what stubs do in that they provide a fake implementation of a dependency needed by the CUT.  However, they go beyond being a mere stub by recording the interaction between itself and the CUT.  A mock keeps a record of all the interactions with the CUT and reports back, passing the test if the CUT behaved correctly, and failing the test if it did not.  Thus, it is actually the Mock, and not the CUT itself, the determines if a test passes or fails.

Here is an example – say you have a class TWidgetProcessor.  It has two dependencies, an ILogger and an IVerifier.  In order to test TWidgetProcessor, you need to fake both of those dependencies.  However, in order to really test TWidgetProcessor, you’ll want to do two tests – one where you stub ILogger and test the interaction with IVerifier, and another where you stub IVerifier and test the interaction with ILogger.  Both require fakes, but in each case, you’ll provide a stub class for one and a mock class for the other. 

Let’s look a bit closer at the first scenario – where we stub out ILogger and use a mock for IVerifier.  The stub we’ve discussed – you either write an empty implementation of ILogger, or you use an isolation framework to implement the interface to do nothing.  However, the fake for IVerifier becomes a bit more interesting – it needs a mock class.  Say the process of verifying a widget takes two steps – first the processor needs to see if the widget is in the system, and then, if it is, the processor needs to check if the widget is properly configured.  Thus, if you are testing the TWidgetProcessor, you need to run a test that checks whether TWidgetProcessor makes the second call if it gets True back from the first call.  This test will require the mock class to do two things:  first, it needs to return True from the first call, and then it needs to keep track of whether or not the resulting configuration call actually gets made.  Then, it becomes the job of the mock class to provide the pass/fail information – if the second call is made after the first call returns True, then the test passes; if not, the test fails.  This is what makes this fake class a mock:  The mock itself contains the information that needs to be checked for the pass/fail criteria.

Definition: A mock is a fake that keeps track of the behavior of the Class Under Test and passes or fails the test based on that behavior.

Most isolation frameworks include the ability to do extensive and sophisticated tracking of exactly what happens inside a mock class. For instance, mocks can not only tell if a given method was called, it can track the number of times given methods are called, and the parameters that are passed to those calls.  They can determine and decide if something is called that isn’t supposed to be, or if something isn’t called that is supposed to be.  As part of the test setup, you can tell the mock exactly what to expect, and to fail if that exact sequence of events and parameters are not executed as expected.  Stubs are fairly easy and straightforward, but mocks can get rather sophisticated.

I’ve written about the Delphi Mocks framework in a previous post.  It takes advantage of some cool new RTL features in Delphi XE2.  It’s also a very generous and awesome gift to the Delphi community from Vince Parrett, who makes the very awesome FinalBuilder. If you have XE2 and are doing unit testing, you should get Delphi Mocks and use it.  If you don’t have XE2 and are doing unit testing, you should upgrade so you can start using this very valuable isolation framework.

But again, the whole point here is to test your classes in isolation; you want your CUT to be able to perform its duties without any outside, real, external dependencies.

Thus, a final definition:  Unit testing is the testing of a single code entity when isolated completely from its dependencies. 

Using Anonymous Methods for Inversion of Control

By Nick at March 31, 2012 08:26
Filed Under: Delphi, Software Development, Unit Testing

Introduction

I’ve written an entire series of articles about Dependency Injection and the Inversion of Control.  I’ve exhorted you to decouple your code and to ask for your dependencies instead of creating them yourself.  I hope you’ve listened.

Now I’m going to discuss another way you can invert the control of your code – by using anonymous methods.

Anonymous methods were one of two major language features added in Delphi 2009 – the other being generics.  Generics are probably easier to understand and use as they have a great use case with collections.  Anonymous methods are a little harder to understand because their use and their purpose are not as easily seen.   I hope that you’ll start seeing their advantage after reading this post.

Basic Idea

The basic idea is pretty simple – anonymous methods allow you to pass code, i.e. functionality, like any other variable.  Thus, you can ask for  functionality via an anonymous method just like you can ask for a dependency via an interface.  Because you can assign code to a variable – or even pass code directly into a method – you can easily invert the control of your class by passing in code to your class instead of embedding it in the class itself.

One of the principles of Inversion of Control is “Don’t call us, we’ll call you”.  That is, if a class needs something, the class itself should ask for (call) the functionality, rather then doing that functionality itself.  If a class needs to, say, record the processing of widgets as it happens, it should ask for a widget recording class and record things using the dependency that is passed in.  A class should not create it’s own instance of a widget recording class and then use it.

Given that example, it’s not difficult to see how one could pass recording functionality into a class as an anonymous method. 

Doing it the “Normal” Way

Let’s use the above discussion in a code example.  As noted, perhaps your class needs to record the processing of widgets.  Typically, you might do something like this in order to use good dependency injection techniques:

type
  IWidgetRecorder = interface
    procedure RecordWidgets(aNumberOfWidgets: integer);
  end;

Then, you’d pass an instance of that interface into your class:

var
  MyWidgetRecorder: IWidgetRecorder;

...

MyWidgetRecorder := TWidgetRecorder.Create;
MyWidgetProcessor = TWidgetProcessor.Create(MyWidgetRecorder);

You’d store the widget recording interface and use it in your class as needed.  And that’s an excellent thing to do – your class is decoupled completely from the recorder, and you are using constructor injection to ask for your dependency. 

Again, this is a great technique, and probably preferable most of the time.  I don’t want to leave the impression that what I discuss below is always a replacement for good, sound use of interfaces. However, it may not always be what you want to do.

IOC with Anonymous Methods

As noted above, you can use anonymous methods to invert the control of your class.  Perhaps declaring an interface and instantiating a class to implement it is too heavy.  Perhaps the dependency is really simple and straightforward.  In those cases, using a simple anonymous method to inject your dependency might be a better solution for decoupling your code.

For instance, you can declare an anonymous method type:

type
  TWidgetRecorderProc = reference to procedure(const aCount: integer);

This will allow you to declare code that takes an integer – presumably the count of widgets being recorded – and does whatever you need it to without bothering the class that uses it.

From there, you can use this type in your classes:

type
  TWidgetProcessor = class
  private
    FWidgetRecorder: TWidgetRecorderProc;
  public
    constructor Create(aWidgetRecorder: TWidgetRecorderProc);
    procedure ProcessWidgets(aNumberToProcess: integer);
    property WidgetRecorder: TWidgetRecorderProc read FWidgetRecorder write FWidgetRecorder;
  end;

This simple class declaration takes an anonymous method as a parameter to its constructor, and then exposes that function as a property. That’s a bit of a commitment – you may not always want to do widget recording.  If you wanted, you could not pass the anonymous method in the constructor and simply assign it to the property as desired. In any event, the widget recording functionality is implemented externally, and your class merely depends on the anonymous method type. 

Then, you can implement the class as follows:

{ TWidgetProcessor }

constructor TWidgetProcessor.Create(aWidgetRecorder: TWidgetRecorderProc);
begin
  inherited Create;
  FWidgetRecorder := aWidgetRecorder;
end;

procedure TWidgetProcessor.ProcessWidgets(aNumberToProcess: integer);
begin
  WriteLn('Processing ', aNumberToProcess, ' widgets.');
  WidgetRecorder(aNumberToProcess);
end;

Now, you have a class that can record widgets any way you want to – to the console, to a file, to email, a database -- whatever.  And you don’t have to know anything about the implementation of how the widgets are recorded. You just have a variable that refers to the code, which you can easily call in your code. 

Using Your New Widget Recording Tool

So, now we have a TWidgetProcessor that can record widgets with an anonymous method.  Cool – but how?  Well, you simply declare an anonymous method and pass it in.  Here’s an example which just writes out to the console:

procedure ProcessSomeWidgetsAndRecordToConsole;
var
  WidgetProcessor: TWidgetProcessor;
  RecorderProc: TWidgetRecorderProc;
begin
  RecorderProc := procedure(const aCount: integer)
                  begin
                    Writeln('The Widget Recorder recorded ', aCount, ' widgets');
                  end;


  WidgetProcessor := TWidgetProcessor.Create(RecorderProc);
  try
    WidgetProcessor.ProcessWidgets(Random(100));
  finally
    WidgetProcessor.Free;
  end;
end;

All this code does is declare an anonymous method that matches the declaration of TWidgetRecorderProc and writes the information out to the console.  That’s pretty simple.  But what if you wanted to write it out to a file?  Easily done without changing the TWidgetProcessor class at all.

procedure ProcessSomeWidgetsAndRecordToFile;
var
  WidgetProcessor: TWidgetProcessor;
  RecorderProc: TWidgetRecorderProc;
const
  cFilename = 'WidgetRecord.txt';
begin
  RecorderProc := procedure(const aCount: integer)
                  var
                    SL: TStringList;
                    S: string;
                  begin
                    SL := TStringList.Create;
                    try
                      if TFile.Exists(cFilename) then
                      begin
                        SL.LoadFromFile(cFilename);
                      end;
                      S := Format('%s: %d widgets processed', [DateTimeToStr(Now), aCount]);
                      SL.Add(S);
                      SL.SaveToFile(cFilename);
                    finally
                      SL.Free;
                    end;
                  end;

  WidgetProcessor := TWidgetProcessor.Create(RecorderProc);
  try
    WidgetProcessor.ProcessWidgets(Random(100));
  finally
    WidgetProcessor.Free;
  end;
end;

Of course, you could write a similar anonymous method to record the information to a database, send an email, or any combination thereof. 

And just as importantly, if you want to test The TWidgetProcessor class, you might want to do so by passing in a TWidgetRecorderProc that does absolutely nothing:

  RecorderProc := procedure(const aCount: integer)
                  begin
                     // Do nothing, as this is a stub for testing purposes
                  end;

And of course if your classes are easy to test, then they are very likely well designed.  The ability to stub out functionality as above is a hallmark of well designed classes.

Conclusion

So now you have another tool in your Dependency Injection/Inversion of Control tool box.  The power here is in the ability to decouple functionality from the class that needs that functionality. Anonymous methods provide a nice way to wrap up functionality in a single variable.   Instead of injecting an implementation of an interface, with anonymous methods you can inject a specific chunk of code that will provide the functionality.  Either way, you end up with testable code that will be more maintainable in the future.

(I have included the full source for this demo, as well as other demos, available on my Demo Projects repository on BitBucket.org)

Life is Too Short To Call Create

By Nick at January 27, 2012 09:52
Filed Under: Delphi, Software Development, Unit Testing

Introduction

Okay, so the whole FreeAndNil thing has been going on for a while.  Some folks are understandably sick of it, but I’m not.  Winking smile I think it is an important discussion that actually reveals a much deeper issue – sort of like how a fight with your spouse over the toothpaste tube is usually really a fight over something deeper and more serious.

I think in this case, the “fight” (I don’t like that word for this particular case, but we’ll roll with the metaphor…) is really about the approach one takes towards memory management – specifically, how one views the role of class creation (and thus memory allocation) when writing code.  In my Dependency Injection Series (which I really need to continue…), I spoke about the notion of creating classes without constructors (other than the default one, of course).  In a sense, this post might be considered part of my DI series, because in this post I am basically making the case for using a Dependency Injection container.  In this post, I’m going to argue that for the most part, you should not call Create.  And you should design your code in such a way that you don’t need to call Create

Life Too Short?

Okay, so I was watching a terrific video by Neal Ford (a former Delphi guy, actually – ) in which he introduces the notions of and “way of thinking” behind Functional Programming.  It’s a great video, and you should watch it.  Near the end of it, Neal says something that I’ve been pondering a while:  “Life is to short to call malloc”. He doesn’t think he should have to worry about memory management anymore.   This somewhat provocative thought stream-lined with a notion I ran across as I was investigating and thinking about unit testing – the idea from Misko Hevery where he is deeply suspicious of the new operator, Java’s equivalent of .Create.  At first, this seems like a really weird notion, particularly since Delphi is a native language, and many Delphi developers appreciate the ability to control the lifetime of their objects and directly manage memory .  But I started to see the wisdom in it, and have finally come to agree with Neal – Life is too short to call .Create.  I don’t want to be spending my limited thinking and coding time worrying about memory, particularly since there are now frameworks and language features that can do this automatically.  In languages like Java and C# (among others), developers use garbage collection to manage memory.  We don’t have garbage collection in Delphi, but we do have ways of making memory management something that isn’t a huge concern. 

And hey, if you are a Delphi developer, and you want to completely control your objects lifetime manually, they hey, you can. More power to you.  But again, I’m going to show you how you can spend less time worrying about that and more time doing the things that we developers really are trying to do -- which is come up with solutions and products. 

This isn’t the first time that I’ve thought or mentioned all of this stuff:

I’m Lazy

First, I am not the sharpest knife in the drawer and I have a limited number of CPU cycles in my brain.  If I don’t have to, I don’t want to spend them doing repetitive “busy work”.  And calling the Create/Free cycle is, to a large degree, busy work.  We all do it – we carefully ensure that if we call Create, we code the try…finally block and call .Free.  If we create an instance class variable in a constructor, we immediately call .Free in the destructor.  Those are all good practices, and bravo to you for following them, but I think we’ve now gotten to the point where we don’t always have to do these kinds of tedious, wrote coding activities anymore.  If we can spend time thinking more about higher level solutions and less about lower-level intricacies, we are more productive.  (One could argue that the entire field of computer science has been nothing other than a giant march towards spending time on higher level solutions and away from tedious, low-level coding…)

Don’t Cause Dependencies

But that is more of a basic, low-level reason in itself -- the idea that you can save brain power.  There are some deeper technical and practical  reasons why you should eschew creating anything.  The first is that calling .Create creates more than just an object instance -- it creates a dependency.  If you actually create a class instance your self and use that class via a direct class reference, that is, do something like this:

procedure TMyWidget.DoSomeSprocketWork;
var
  SomeSprocket: TSprocket
begin
  SomeSprocket := TSprocket.Create
  try
    SomeSprocket.DoSprocketyStuff
  finally
    SomeSprocket.Free
  end;
end;

you are dependent on that class and that class alone.  You’ve created an unbreakable dependency on that particular implementation.  You have to include that classes unit in your uses clause.  You’ve very tightly coupled yourself to a specific means of getting something done.   If you want to change it, you actually have to go and alter the code itself.  Yikes! If you want to test it, your tests have to rely on the entire dependency chain of TSprocket, and who  knows what the heck that entails?  And I hope we can all agree that tightly coupling yourself to specific implementations is bad, right?  (If we can’t, I’m afraid that we can’t be friends anymore.  Alas.)

As I’ve been preaching for a while now, you should reference classes and functionality via interfaces.  Interfaces allow you to, at the very least, reference specific a functionality rather than a specific implementation of that functionality.  But even in you use interfaces exclusively -- that is do something like the below instead of the above --

procedure TMyWidget.DoSomeSprocketWork;
var
  SomeSprocket: ISprocket
begin
  SomeSprocket := TSprocket.Create
  SomeSprocket.DoSprocketyStuff
end;

you are still creating a dependency on that particular class. Your uses clause still has to include the unit for that class, and your code is explicitly tied to that particular implementation.  Using the interface is a step in the right direction – using an interface makes you not have to worry about memory management – but you still end up with dependency on a specific implementation.  And we agree that a dependency on a specific implementation should be avoided, right? 

So, we agree that calling Create causes a hard-coded dependency and that it is bad.  And if you think about it, anytime you call create in one class, you create a dependency.  One reason such dependencies are bad is that it makes your code hard to test.  True and proper unit testing means that each class should be able to be tested in isolation.  If ClassA is irrevocably dependent on ClassB, then you cannot test ClassA without invoking ClassB.  You can’t easily provide a mock class for ClassB either.  Thus, a call to Create can make your code hard to test. 

Following SOLID

But there’s yet another reason to avoid calling Create – the ‘S’ in the SOLID principles.  The ‘S’  stands for the “Single Responsibility Principle” which is “the notion that an object should have only a single responsibility.”  If your class has a mission and it is creating stuff to do that mission, then it actually has multiple responsibilities – doing its mission and  creating stuff.  That’s two things, not one.  Instead, let your class do it’s main mission, and leave creating stuff up to another class whose main mission it is to create stuff.   Plus,  if you have dug into the SOLID principles, you know that the ‘D’ stands for the “Dependency Inversion Principle” which is the notion that “one should depend upon abstractions [and] not depend upon concretions.”  Or, as you might have heard me say say “Program against abstractions, not against implementations”.  (And of course, it wasn’t me that said that – it was Erich Gamma of  “Gang of Four ” fame.)

And where does that leave us?  Well, right back with not calling Create, and having a class whose specific, single purpose in life is to create stuff for you.  Sound familiar?  It should, we just described either a class based on the Factory pattern, or a Dependency Injection container. 

So, in the end, the code you’d write would end up looking like:

procedure TMyWidget.DoSomeSprocketWork;
var
  SomeSprocket: ISprocket
begin
  SomeSprocket := SprocketFactory.GetSprocket;
  // Or maybe something like
  // SomeSprocket := MyDIContainer.GetImplementation<ISprocket>('Basic');
  SomeSprocket.DoSprocketyStuff
end;

That way, there is no Create call, and thus you aren’t creating any dependency other than on the interface.  You get instances of your objects from a Factory or from a Dependency Injection container  -- and either one can produce any implementation you want or ask for without creating a dependency.   Either way, it gives you control over how the interface is implemented without coupling to that implementation. You could even add a parameter to the GetSprocket call to ask for a specific kind of Sprocket implementation, and even that wouldn’t cause you to be dependent on that implementation.  

In the end, calling Create merely causes a dependency, takes brain cycles, and violates the SOLID principle.  No wonder you shouldn’t use it much!

So then the question becomes, When should you call Create? Well, I’m glad you asked. I’ll answer that in a future post.  Winking smile

Delphi Mocks: The Basics

By Nick at October 16, 2011 12:41
Filed Under: Software Development, Delphi, Unit Testing

Introduction

As you may have noticed, I’ve kind of started to become a championship caliber pain in the butt about unit testing.  I walk the halls of Gateway Ticketing saying “If your code isn’t easy to test, you are doing it wrong”.  I keep giving my Unit Testing presentation to anyone that will listen.  But I feel justified – unit testing is critical to writing clean, maintainable code.

One of the reasons people seem to frequently give for not doing unit testing is that “My code requires <some external dependency> and it’s too hard to configure for simple unit tests” or something like that.  Okay, fair enough.  I won’t point out how you should be using Dependency Injection to decouple that code and enable you to insert a mock or a stub or a different class for testing purposes.  (Okay, I lied – technically I guess I did mention that.  Sorry.)  But I get that sometimes implementing a complete, formal TMockXXXX version of your interface (and you are coding against interfaces and not implementations, right?) is not something you want to do. 

Mocks

In their simplest form, a mock object is simply an alternate implementation of a class that provides “fake” responses to method calls.  For example, you have a class TCustomer that has a method GetCustomerName, and normally, that call goes to the production database and gets the name (a simple, unlikely example, I know, but you get the idea).  So to avoid the call to the database, you just create TMockCustomer, and implement it’s call to GetCustomerName and have it return “George Jetson” every time.  This enables you to test the class that is using TCustomer without having to hit the database at all.

But that can get a bit clumsy.  What if you want to return different values based on different inputs?  What if you find a bug based on specific input or output, and you want to create a unit test for that specific case?  Then a mock class as described above gets harried, complicated, and hard to maintain.

Enter a Mocking Framework

What if we could have a framework that would allow us to implement any interface, and define easily and exactly what the inputs and outputs should be?  That would be cool.  This would enable you to easily create a mock object that can respond to method calls in defined ways in a flexible, easy to set up manner.  This is what a mocking framework does.

Obviously something this flexible needs some powerful language features.  Such a framework would have to be able to flex to dynamically implement an interface.  It would have to be able to dynamically recognize method calls and respond accordingly.  Fortunately, Delphi XE2 is up to the task.  Delphi XE2 introduces the TVirtualInterface class that lets you dynamically implement any interface at runtime.  Combine that with the new RTTI, and you have the ability to build a very powerful mocking framework.

And that is just what Vince Parrett of VSoft Technologies, author of the wonderful FinalBuilder, did.  He has built a very cool and very powerful library called Delphi Mocks and released it as open source for all of us.  Very cool – thanks, Vince.   Delphi Mocks is available on GitHub under the very developer friendly Apache 2.0 License.  Vince has written a nice “Getting Started” guide, but I wanted to write  this article to build a very simple example of a pretty simple use case for mock objects.  So let’s do that.

An Expensive Service

A typical use case for using a mock object is to replace a service that is “expensive”.  Sometimes that means expensive as in “actually costs money”, but it will more likely mean expensive in CPU cycles, database connectivity, or anything else that requires an external dependency that causes your class under test to stop being tested in isolation and start being integrated with something else.   Since a unit test should always test something atomically and leave nothing (database entries, files, charges on a credit card) lying around, any time that will happen when running a unit test, you probably should consider a stub or a mock object instead.

By “stub” I mean “a class that implements a particular interface but doesn’t really do anything”.  It’s not exactly the same as a mock object in that the interface in question will normally not return anything but merely do things external to the class.  A typical example is a logging class.  If you are running unit tests, you don’t want your logging system writing logs all over the place every time you run your tests, so you create a Logger stub class that acts like your regular logger, but which actually doesn’t do anything.  You can call it in your code, but you get nothing from it – which is what you want. 

So let’s look at a simple, but “expensive” service.  Consider the following code:

unit uCreditCardValidator;

interface

uses
      SysUtils;

type

  ICreditCardValidator = interface(IInvokable)
  ['{68553321-248C-4FD4-9881-C6B6B92B95AD}']
    function IsCreditCardValid(aCreditCardNumber: string): Boolean;
    procedure DoNotCallThisEver;
  end;

  TCreditCardValidator = class(TInterfacedObject, ICreditCardValidator)
    function IsCreditCardValid(aCreditCardNumber: string): Boolean;
    procedure DoNotCallThisEver;
  end;

implementation

uses
     Dialogs;

{ TAdder }

function TCreditCardValidator.IsCreditCardValid(aCreditCardNumber: string): Boolean;
begin
  // Let's pretend this calls a SOAP server that charges $0.25 everytim
  // you use it.

  // For Demo purposes, we'll have the card be invalid if it the number 7 in it
  Result := Pos('7', aCreditCardNumber) <= 0;

  ShowMessage('You were just charged $0.25');
end;

procedure TCreditCardValidator.DoNotCallThisEver;
begin
  // This one will charge the company $500!  We should never
  // call this!
end;

end.

This unit declares two things, an ICreditCardValidator and a class that implements it, TCreditCardValidator.  It simulates deciding a credit card is bad by saying any card number that has the number ‘7’ in it is bad.  Otherwise, any string will be acceptable. It’s a demo class, obviously, but it illustrates a class that would be used only in production, as you get charged by a credit card validating service every time you call IsCreditCardValid.    Clearly, you don’t want to be calling that whenever you run your tests.  Thus, it seems likely that any collection of unit tests that wants to use this service would likely want to use a mock class.

A Class to Use the ICreditCardValidator

Mock classes really become useful when you are testing a class that consumes an expensive service.  Thus, we’ll declare the following class, TCreditCardManager, which consumes ICreditCardValidator:

unit uCreditCardManager;

interface

uses
      uCreditCardValidator
    ;

type
  TCreditCardManager = class
  private
    FCCValidator: ICreditCardValidator;
  public
    constructor Create(aCCValidator: ICreditCardValidator);
    function CreditCardIsValid(aCCString: string): Boolean;
  end;

implementation

{ TAddingMachine }

function TCreditCardManager.CreditCardIsValid(aCCString: string): Boolean;
begin
  Result := FCCValidator.IsCreditCardValid(aCCString);
end;

constructor TCreditCardManager.Create(aCCValidator: ICreditCardValidator);
begin
  inherited Create;
  FCCValidator := aCCValidator;
end;

end.

This class is really simple – it just takes an ICreditCardValidator in it’s constructor and uses it to validate credit cards.  As a demo class it is really simple, but a more complete class would have methods to make payments against the card, etc.  But if, when testing this class, you pass it in an implementation of the ICreditCardValidator above, you’ll get charged $0.25 for every test you run.  That’s not something you’d really want to do, so this class seems like a good candidate for using a mock object to replace the implementation of ICreditCardValidator

Testing TCreditCardManager Can Be Expensive

So, the typical way to test TCreditCardManager might look like this:

procedure TestTCCValidator.TestValidateCreditCard;
var
  ReturnValue: Boolean;
  ExpensiveCCValidator: ICreditCardValidator;
  ValidCard: string;
  BadCard: string;
begin
  ExpensiveCCValidator := TCreditCardValidator.Create;
  FCCValidator := TCreditCardManager.Create(ExpensiveCCValidator);

  ValidCard := '1112221'; // Rule is that a bad card has a '7' in it
  BadCard   := '6667666'; // ..so this one is bad

  ReturnValue := FCCValidator.CreditCardIsValid(ValidCard);
  CheckTrue(ReturnValue);

  ReturnValue := FCCValidator.CreditCardIsValid(BadCard);
  CheckFalse(ReturnValue);
end;

However, if you run this in the GUI test runner for DUnit, you’ll see this:

image

 

And of course, if you keep this up, the bill you get will not make your boss happy.

Testing with a Mock

So, to avoid the wrath of your boss, you should create a mock object that behaves like you want it to but that doesn’t end up costing anything.  The first way you might do it is to create a new class that implements the ICreditCardValidator interface, but that does nothing or returns set values.  But that is kind of clunky, and hard to customize.  What you really want is what I mentioned earlier, an extensible mock that can be created an configured on the fly.  That’s where Delphi Mocks comes in.

The Delphi.Mocks.pas unit declares a type TMock which takes a parameterized type, and which then can sort of morph itself into an implementation of that interface using the cool new-to-XE2 class called TVirtualInterfaceTVirtualInterface basically allows you to implement an interface on the fly at runtime.  Thus, you can create a generic class (or record, in the case of TMock) that can appear to be any interface you want it to be. 

Thus, we can create a TMock that looks and acts like an ICreditCardValidator:

var
  CCMock: TMock<ICreditCardValidator>;
 begin
  CCMock := TMock<ICreditCardValidator>.Create;
  ...
end;

Once we have that mock, we can tell it how to behave:

  ValidCard := '1112221'; // Rule is that a bad card has a '7' in it
  BadCard   := '6667666'; // ..so this one is bad

  CCMock.Setup.WillReturn(True).When.IsCreditCardValid(ValidCard);
  CCMock.Setup.WillReturn(False).When.IsCreditCardValid(BadCard);

This code uses a nice fluent interface to be somewhat self-explanatory.  It basically sets the mock up as follows: “When I pass in the valid string, return True.  When I pass in the bad string, return False.”  This is a basic definition that will allow your TCreditCardManager class to exercise itself with both good and bad input, allowing you to test your code with both kinds of responses.  We can determine exactly what the inputs and outputs are and ensure that the mock displays the correct behavior and follows the business rules set out in the “real” implementation.  Notice, too, that the When call, through the delightful magic of generics, is actually an implementation of the ICreditCardValidator interface, and thus is able to execute a real method call to the method from that interface.  You even get support from Code Completion in the IDE. 

Now, you can create the Credit Card Manager, pass it your mock object, and run tests with your mock input and output:

  FCCValidator := TCreditCardManager.Create(CCMock);

  ReturnValue := FCCValidator.CreditCardIsValid(ValidCard);
  CheckTrue(ReturnValue);

  ReturnValue := FCCValidator.CreditCardIsValid(BadCard);
  CheckFalse(ReturnValue);

This way, you can exercise the instance and test it  to your hearts content without incurring any of the expense associated with your “regular” implementation.  If you need to add additional tests, you can simply tell the mock class what the new input and outputs are, and then run the appropriate tests.

Ensuring Code Is (or Is Not) Called

When writing tests, there may be times when you want to ensure that a given method is called with a frequency that you want to specify.  Thus, you can write things like:

  CCMock.Setup.Expect.AtLeastOnce.When.IsCreditCardValid(ValidCard);

  // Ensure that the tests never call this.  It costs $500!!
  CCMock.Setup.Expect.Never.When.DoNotCallThisEver;

And then, when all the test are run, call:

CCMock.Verify;

on the mock object, and it will validate that the calls that you required were indeed called. 

So, in the above example, if I were to call:

CCMock.Instance.DoNotCallThisEver;

I would get the following dialog:

image

…which of course tells me that I called a method in my tests that should not have ever been called.

There are also methods on the call to Expect interface that ensure that a certain call is made a minimum or maximum number of times, between a specified  number of times, at least or at most a certain number of times, and as we saw, even never.  Also, you can specify that one method be called before or after other methods.  This enables you to dictate exactly how your object methods are called, and what should or should not happen when you run your tests.

Conclusion

So the Delphi Mock library is a very powerful tool for making it easy to write concise unit tests that don’t connect to “expensive” classes that could make testing difficult.  The goal of writing testable code is a worthy one, and Delphi Mocks definitely can make it easier to reach that goal.

Getting Giddy #4 Fixed

By Nick at July 10, 2011 11:52
Filed Under: Delphi, General, Software Development, Unit Testing

Okay, so I was getting all these emails about the fourth article in my “Getting Giddy” series of articles.  You guys kept saying it was missing and I kept saying “Hey, it’s right here!”.  And then finally I noticed – #4 and #5 were identical.  I must have done something stupid somewhere.  Well, I was able to track down the original article on my hard drive and restore it.  So now, the fourth article is as it should be, and all seems well with the universe.

Sorry for the confusion, and I appreciate the interest that these articles have generated.

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:

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!

Flotsam and Jetsam #20

By Nick at January 13, 2011 20:25
Filed Under: Delphi, Flotsam and Jetsam, Unit Testing
  • My Dad got me this clock for Christmas and I now have it hanging on my wall at the office here at the World-wide Headquarters of Gateway Ticketing.  It is definitely an eye catcher and a conversation starter.  I was able to figure out some of the numbers (12, 6, 7, 8, and 11), but the rest I had to get from a blog post that explains them all. 
  • I happy and honored to say that the Delphi Feed for my blog is now part of DelphiFeeds. Hopefully this will mean that these amazing pearls of wisdom will benefit a broader audience than just you fine people.
  • We here at Gateway are in the process of migrating to Mercurial for our source control (I’ve probably mentioned that before….) and we are considering using bitbucket.org to host our repository.  Thus, I’ve created a small Delphi project there called DelphiClean. It’s not much right now, but it is serving the purpose of letting me see how things work on BitBucket.  I will update it in the future, particularly with the ability to provide a custom list of extensions to be “cleaned”.
  • Now that Delphi has cool language features like Generics and Anonymous Methods, there is a lot of very cool code being written. Combine that with the ease of sharing code on places like GoogleCode, BitBucket, SourceForge, etc., and it ‘s a pretty cool time to be a developer.  The indefatigable Alex Ciobanu is a guy who is producing some amazing code.  Alex create the DeHL project, and now he’s created out of that a project called Collections.  Well worth a look.  The fun part is that Alex creates a full suite of unit tests for his code, so you can use it with confidence, and if you find a bug, you can write a failing unit test for him, and he can fix it, incorporate the now passing test, and we’ll all know if that bug appears again.  (There’s my daily pitch for unit testing….) In any event, Alex’s code is quite remarkable, and he’s a valuable member of the Delphi RTL team.  Here’s hoping some of this great code finds its way into the RTL.
  • Danny Magin posts about the Developer Solutions Conference.  I wish I could go – alas, duty calls – but you can. (I’m particularly interested in the Android development stuff.  Alas)  Plus, it’s in Vegas, baby!

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.

My Book

A Pithy Quote for You

"It is difficult to get a man to understand something, when his salary depends upon his not understanding it."    –  Upton Sinclair

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.