Amazon.com Widgets Delphi

TVirtualInterface: Next Steps

By Nick at June 13, 2012 21:48
Filed Under: Delphi, Software Development

Okay, so my last article was pretty fun – you got a look at TVirtualInterface and how you can use it to implement any interface.  Now, I want to be clear – the code in that article was demo code.  That is, it was purely for illustrative purposes.  I can’t think of any reason why you’d actually, in the real world, implement an interface that way. But after reading it, you should be able to see how TVirtualInterface works and how you can get it to do what you want. 

Now, in that article I promised you that my next blog post on the topic would be an example of using TVirtualInterface in a more useful manner.  But I guess I lied, because this blog post is about how you can create a slightly better version of TVirtualInterface.

So a while back, I wrote a post about getting you to “think generically” and how generics (or as I prefer to think of them, parameterized types) are useful in more ways than just collections and lists.   Well, I got to looking at TVirtualInterface and I thought, “You know, here’s a class that actually requires type information about a given type, and in order for it to do anything useful, you have to give it a type in the constructor, so hmmm…….”.  And you can guess where I went from there. 

So, consider the following class declaration:

type

  TVirtualInterfaceEx<T: IInvokable> = class(TVirtualInterface)
  protected
    procedure DoInvoke(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue);
    procedure DoInvokeImpl(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue); virtual; abstract;
  public
    constructor Create;
  end;

This is a pretty simple descendent for TVirtualInterface.  The most obvious thing is that it takes a parameterized type T which is constrained to be an interface descending from IInvokable.  That enables you to explicitly declare what interface TVirtualInterfaceEx is going to implement.  You should notice, too that TVirtualInterfaceEx is an abstract class, as the DoInvokeImpl method is abstract.

So, once you have the parameterized type, you know everything you need to implement the interface.  As you know from the previous article, the thing you need to do is to provide an implementation of DoInvoke.  So TVirtualInterfaceEx employs the technique I’ve described before whereby you implement the interface in the base class and provide a “real” implementation in a separate method invoked by the base class.  So, the implementation looks like this:

constructor TVirtualInterfaceEx<T>.Create;
begin
  inherited Create(TypeInfo(T), DoInvoke);
end;

procedure TVirtualInterfaceEx<T>.DoInvoke(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue);
begin
  DoInvokeImpl(Method, Args, Result);
end;

The constructor is pretty simple – it is parameter-less and  calls a sibling constructor, passing in the TypeIinfo for your interface and the DoInvoke method which is of type TVirtualInterfaceInvokeEvent.  The code for DoInvoke method simply calls the DoInvokeImpl method, which, because it is abstract, descendent classes must override.

Thus, to use this class, all you need to do is to descend from it and provide an interface as a parameterized type and an implementation for DoInvokeImpl.   So, if we wanted to implement the IActuallyUseful interface from the previous example, all we need to do is:

  TActuallyUsefulEx = class(TVirtualInterfaceEx<IActuallyUseful>)
  protected
    procedure DoInvokeImpl(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue); override;
  end;

implementing DoInvokeImpl with the same code that was in the DoInvoke event of the TActuallyUseful class. 

By the way, I should mention that the code for these demos on TVirtualInterface, including a sneak peek at the code for the next article, is available as part of my demo code project on BitBucket.

This isn’t anything really fancy, but I liked it because it simplified the process of creating virtual interface implementations and provided another example of a good use for parameterized types.  I also like what I mentioned previously, that it clearly declares what interface it is implementing.

Anyway, I thought it was a cool little wrapper/descendent for the TVirtualInterface class.  And I promise that the next blog post on this stuff will show an example of using it in a truly dynamic way.

TVirtualInterface: Interfaces without an Implementing Class

By Nick at June 10, 2012 05:37
Filed Under: Delphi, Software Development

I would be really disappointed if we spent an hour discussing software development and I didn’t at least once say to you "Program against interfaces, not against implementations".  It’s sort of a mantra for me – a way of life if you will.  It’s a bedrock principle of development as far as I’m concerned. Programing against interfaces and not against implementations is the only way to truly decouple your code.  And if you don’t believe that decoupling your code is important, I’d like you to stop reading right now, get a small ball-peen hammer, and keep hitting yourself in the forehead until you change your mind.

So if you’ve made it this far, you’ll know that implementing interfaces is needed to use them.  You have to put some code behind an interface to make it do anything.  Normally, this is done with an implementing class:

type
  ISprocketProcessor = interface
    procedure ProcessSprockets;
  end;

  TSprocketProcessor = class(TInterfacedObject, ISprocketProcessor)
    procedure ProcessSprockets;
  end;

But what if you could implement an interface without having a specific class?  What if there were a way to implement any interface with a single module of code? What if you could decide at runtime how to implement an interface?  Would I even be asking these questions and writing this if those things weren’t possible?

So, yes, obviously it is.  Delphi XE2 introduces a very cool new class called TVirtualInterface. Its purpose is to allow you to descend from it and respond to any interface dynamically.  If you think about that for a second you’ll realize that this is pretty powerful. For instance, it’s the thing that lets the awesome Delphi Mocks Framework provide a mock implementation of any interface that you pass to it.

Generally, when you implement an interface, you provide a class that implements it in a specific way – i.e. that implementation becomes static at runtime. There are ways – typically via Dependency Injection – that allow you to choose an implementation, but even then you are limited to a specific set of implementations.   TVirtualInterface allows you to dynamically -- i.e. at runtime – determine how an interface will be implemented.  The examples in this article will show a fixed way to implement TVirtualInterface so you can get the basics of how to use TVirtualInterface.  In a future article, we’ll look at more dynamic ways to use this sweet class.

Here’s the public interface for TVirtualInterface:

  { TVirtualInterface: Creates an implementation of an interface at runtime.
    All methods in the Interface are marshaled through a generic stub function
    that raises the OnInvoke event.}
  TVirtualInterface = class(TInterfacedObject, IInterface)
 ...
  public
    function QueryInterface(const IID: TGUID; out Obj): HResult; virtual; stdcall;
    { Create an instance of TVirtualInterface that implements the methods of
      an interface.  PIID is the PTypeInfo for the Interface that is to be
      implemented. The Interface must have TypeInfo ($M+). Either inherit from
      IInvokable, or enable TypeInfo for the interface. Because this is an
      TInterfacedObject, it is reference counted and it should not be Freed directly.
      }
    constructor Create(PIID: PTypeInfo); overload;
    constructor Create(PIID: PTypeInfo; InvokeEvent: TVirtualInterfaceInvokeEvent); overload;
    destructor Destroy; override;
    { OnInvoke: Event raised when a method of the implemented interface is called.
      Assign a OnInvoke handler to perform some action on invoked methods.}
    property OnInvoke: TVirtualInterfaceInvokeEvent read FOnInvoke write FOnInvoke;
  end;

First, you should notice that TVirtualInterface descends from TInterfacedObject and implements IInterface.  The three methods of IInterface are implemented to allow the class to be properly reference counted like any other interface-implementing class.  Second, the interface that you want to implement with it needs to have TypeInfo enabled for it.  The easiest way to make that happen is to descend your interface from IInvokable.  Otherwise, you’ll need to use the {$M+} switch for your interface. Notice, too, that the comment above the class declaration says what I said early – using TVirtualInterface will let you, well, do anything you want with an interface at runtime.  Cool. 

So, in order to actually make TVirtualInterface do something, you need to create a descendent class and provide two things:  a constructor and an implementation of the DoEvent method.

Here’s an TVirtualInterface descendent that is as simple an example as I could think of:

type
  TSimplestVirtualInterface = class(TVirtualInterface)
    constructor Create(PIID: PTypeInfo);
    procedure DoInvoke(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue);
  end;

constructor TSimplestVirtualInterface.Create(PIID: PTypeInfo);
begin
  inherited Create(PIID, DoInvoke);
end;

procedure TSimplestVirtualInterface.DoInvoke(Method: TRttiMethod;
  const Args: TArray<TValue>; out Result: TValue);
begin
  WriteLn('You called a method on an interface');
end;

The only thing this will do is to write out to the console – no matter what.  You can pretend it implements any interface, and no matter what you call on that interface, it will merely write to the console. 

The constructor takes a single parameter, PIID, which is is the TypeInfo for the interface you want to “implement”.  (That’s why the interface in question must have the {M+} switch – usually via IInvokable.)  Inside the constructor, a call to a different constructor is made.  The PIID parameter is passed in, as is a reference to DoInvoke, which is a method that matches the type TVirtualInterfaceInvokeEvent.  Thus, the constructor is basically saying “Here is the type of information for the interface I’m implementing, and the method you should run whenever a method is called on that interface.”

In our case, the DoInvoke method only does one thing no matter what – writes to the console.

So, for instance, say you declare an interface:

type
  IGoStop = interface(IInvokable)
  ['{3B2171B0-D1C3-4A8C-B09E-ACAC4D625E57}']
    procedure Go;
    procedure Stop(aInteger: integer);
  end;

And then you run the following code in a console application:

   GoStop := TSimplestVirtualInterface.Create(TypeInfo(IGoStop)) as IGoStop;
   GoStop.Go;
   GoStop.Stop(42);

the console output will look like this:

image

 

You see the output twice because the code called two methods.  It doesn’t matter what you call – that output will happen no matter what.  It doesn’t matter what interface you pass in or what method you call, the result will be the same.

But of course that isn’t useful – to be of any use, you need to be able to know what is getting called, what is getting passed in, and respond accordingly.

Well, you can do that, because if you look at the signature of the DoInvoke method, you’ll note that when it gets called by the TVirtualInterface.OnInvoke event, it gets passed the RTTI for the method that was called, an array of TValue that contain the interface itself and all the arguments that the method was passed, as well as an out parameter of type TValue that allows you to return a value if the method being called is a function. 

So how about we simply use the DoInvoke event to report out what all that information that it receives.

procedure TReportingVirtualInterface.DoInvoke(Method: TRttiMethod;
  const Args: TArray<TValue>; out Result: TValue);
var
  Arg: TValue;
  ArgType, ArgName: string;
  TempKind: TTypeKind;
begin
  Write('You called the ', Method.Name, ' method ');
  if Length(Args) > 1 then
  begin
    Writeln('and it has ', Length(Args) - 1,' parameters:');
    for Arg in Args do
    begin
      TempKind := Arg.Kind;
      if TempKind <> tkInterface then
      begin
        ArgName := Arg.ToString;
        ArgType := Arg.TypeInfo.Name;
        Writeln(ArgName, ' which is of the type ', ArgType);
      end;
    end;
  end else
  begin
    Writeln(' and it has no parameters.');
  end;
end;

This code simply looks over and reports out about the Method and Args parameters that get passed in when the interface is invoked.  The very first item in the array is always type information about the interface itself, and the rest are the parameters, in order, as they were passed in.  Here, the code simply reports out their values and types, but of course, you can process them as you please. 

Again, that is interesting information, but it’s just a step towards understanding how TVirtualInferface works.  Let’s create something that actually does what we want it to.

Here’s a basic interface:

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

Then, below is the DoInvoke method for a TActuallyUseful class that will actually do what the interface purports to do:

procedure TActuallyUseful.DoInvoke(Method: TRttiMethod;
  const Args: TArray<TValue>; out Result: TValue);
begin
  if UpperCase(Method.Name) = 'SAYHELLO' then
  begin
    WriteLn('Hello World!');
  end else
  begin
    if UpperCase(Method.Name) = 'REVERSESTRING' then
    begin
      Result := ReverseString(Args[1].AsString)
    end else
    begin
      if UpperCase(Method.Name) = 'MULTIPLY' then
      begin
          Result := Args[1].AsInteger * Args[2].AsInteger;
      end else
      begin
        raise Exception.Create('Bad Parameter name was passed in to the DoInvoke method');
      end;
    end;
  end;
end;

This code should be fairly self-explanatory.  It simply checks for the name of the method that was called, and then executes code using the parameter information passed in the Args parameter.  If the call is a function, the Result parameter is used to return a value.   

You should  remember that the initial item in the Args array (that is, the one at the “zero-eth” position) is the interface type itself.  The code also makes assumptions about the number and types of the parameters.  Since the code can only be invoked by the methods declared on IActuallyUseful interface, the code can make safe assumptions about the types and order of the parameters.

Now all of this code above is fairly straight-forward – we are basically simulating an implementing class in our examples.  Nothing is truly dynamic.  The code here merely shows simple examples of how TVirtualInterface works in a fairly static way. You should now be able to see how you could dynamically implement an interface using a TVirtualInterface descendent.

Coding against interfaces is critical for writing good, clean code.  TVirtualInterface is just another powerful tool in your toolbox for doing just that.

Fun Code of the Week #4

By Nick at June 08, 2012 06:14
Filed Under: Delphi, Fun Code

Adapted from my answer on StackOverflow:

function RemoveChars(const aString: string; aCharsToRemove: TSysCharSet): string;
var
  C: Char;
begin
  Result := '';
  for C in aString do
  begin
    if not CharInSet(C, aCharsToRemove) then
    begin
      Result := Result + C;
    end;
  end;
end;

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. 

Fun Code of the Week #3

By Nick at May 01, 2012 08:44
Filed Under: Fun Code, Delphi
procedure ShowHourGlass(Proc: TProc);
begin
  Screen.Cursor := crHourGlass;
  try
    Proc;
  finally
    Screen.Cursor := crDefault;
  end;
end;

Tweet Expansion: Butt Time and Brain Time

By Nick at April 29, 2012 08:53
Filed Under: Delphi, Leadership, Software Development, Tweet Expansion

A while back I tweeted the following:

In software development, we often measure Butt Time, when what we need from developers is Brain Time -- which is much harder to measure.

Some tweets call for further explanation and expansion, and so I’ve added a new category called Tweet Expansion to cover posts that do just that.

Here at Gateway Ticketing, we have an interesting development and business model.  At our core, we are an ISV.  We sell a software package that we build to customers.  But, we also will customize our software to meet customer specifications.  That makes us sort of a VAR to our own product.  Thus, we do both enhancements based on customer requests and our own internal product development projects to make our product more valuable in the marketplace. 

This distinction – between internal projects and projects driven by specific customer requirements – makes for some challenging project management.  But we have a solid team here at Gateway, and we make it all work.  But because we do work that amounts to us being consultants, we end up having to closely track our developer time.  We do that for a number of business reasons, the main one, of course, is profitability.  You need to track your time to ensure that you are actually making money on a given endeavor.

Now I know that no one really likes to track their time.  It’s a pain.  It’s challenging to be accurate.  It’s hard to get time properly categorized.  But it is also invaluable for making those important business decisions. 

But there is a bigger problem with measuring time.  The only thing you can really measure is “Butt Time”.  Butt Time is the actual amount of time someone has their butt in a chair while working on an issue.  You need Butt Time to get any work done, of course.

But Butt Time isn’t really what you want from your developers.  Butt Time isn’t at all equivalent to productive development time.  Butt Time includes reading email, answering questions and generally handling any number of interruptions, meetings, and other distractions.  And those distractions, however minor, break a developer’s concentration.

And when you get right down to it, development is all about concentration.  With a coding project of any size at all, doing development requires your complete focus and concentration.  You need to build up complex data structures and patterns in your mind in order to really be productive.  Doing so takes time --  I’ve heard it described as building a house of cards in your mind.  Building that house of cards can take upwards of fifteen minutes depending upon the project.  But here’s the bummer:  It only takes a second for that house of cards to come tumbling down.  One distraction can make your fifteen minute investment disappear. 

And of course, time spent in “The Zone” – with that house of cards constructed and true, highly productive work getting done – is what we all are seeking.  We’ve all probably had that awesome experience of getting into that zone for hours at a time and wondering where the time went.  We know how cool that is – and how precious.  That’s what we want to measure – Brain Time.

But that’s a really hard thing to do.  Getting accurate, meaningful Butt Time measurements is difficult enough.  But how in the world can you actually measure Brain Time?

I’ll argue that you really can’t.  In the end, Butt Time is only a poor proxy for Brain Time.  What we need to do is to try to increase the Butt Time to Brain Time ratio by providing an environment where Brain Time is maximized as a percentage of total Butt Time.

There are ways to do that – ensuring that your developers have an office with a door that they can close is an important first step.  The book Peopleware is really the Bible for this, and Joel Spolsky has talked a lot about it as well.  Uninterrupted quite time is the key.  Leaving developers alone is the key to maximizing Brain Time.

Seriously – you need to get and read Peopleware if you have anything at all to do with leading developers.  This is the definitive book on managing software developers.  Be sure to get the Second Edition.  The physical book is, I believe, out of print, causing the price to be pretty high,  but I was delighted to notice that you can now order it on the Kindle

Another thing we need to do is to respect – indeed, celebrate – those developers that are quiet and don’t say much.  We have a not small number of developers here at Gateway that, well, don’t say much at all.  They come to work, write great code, and go home.  They don’t have a lot to say.  But sadly, we don’t always respect this.  I’m as guilty of anyone of too often saying super-clever things like “Stop being so boisterous, Meredith” or “Did you say six words today?”, instead of recognizing that Meredith is maximizing her Brain Time and, by being quiet, not breaking other team members’ concentration.  Being quiet is a very valuable virtue in a software developer – both because they themselves are being productive and they aren’t breaking other’s concentration -- and we should give honor and respect to that.

Butt Time is easy to come by and fairly easy to measure.  Brain Time, however, is a precious and hard to measure commodity that needs to be nurtured and respected.

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)

Flotsam and Jetsam #58

By Nick at March 24, 2012 11:59
Filed Under: Delphi, Flotsam and Jetsam
  • The annual RAD Studio survey is out. (UPDATE:  Apparently the link I gave was unique to me, so I've removed it.) I strongly recommend you take it if you are a Delphi/C++Builder/Prism kind of guy.  I can assure you from first hand experience that the results of this survey are very valuable and are used by Embarcadero to make decisions.  So please fill it out and let Embarcadero know what you think.
  • Awesome Quote by Nick of the Week: “The real cool part of it is that proper unit testing is a "virtuous circle". The more you write unit tests, the more you see how to write testable code. The more you write testable code, the more you tend to remove dependencies. The more you remove dependencies, the more decoupled your code is. The more decoupled your code is, the easier it is to test, and thus you write more unit tests, and start it all over again.”   I wrote that in a conversation about unit testing in the Delphi newsgroups.
  • Awesome Follow-up Quote by Dalija Prasnikar of the Week: After someone claims that unit testing can become “wheel-spinning”:  "Exactly opposite. It is quite hard to start the process rolling at the beginning. But once you get going it gets easier and easier, and you write new code faster and with less bugs and when you do write bugs, you find them in matter of seconds instead hours. And you end up with code that is easy to maintain and change. What more could you want?"
  • Sure enough, the denizens of Wikipedia have determined that this blog is “not notable”.   “Notability” is the magic word for Wikipedians, though often I think the definition that they use for it “Stuff I’m not interested in” or “a word I can use to control my little fifedom of the web’.  I will note, though, that my entry has appeared to prompt a complete reworking of the disambiguation page for “Flotsam and Jetsam”, so I’ve got that going for me, which is nice.  I can understand the need for Wikipedia to maintain a level of neutrality and objectivity, but I do think that it can get out of hand, with small-minded people enjoying their power a bit too much.  In any event, I do love Wikipedia, and use it probably more than any other site on the web.  One could even make the argument that it is mankind’s greatest achievement.  Perhaps I will in a future blog post.  Winking smile

Authoring Generics: A Simple First Step

By Nick at March 19, 2012 15:39
Filed Under: Delphi, Software Development

Consumer or Producer?

By now I suspect that most of you have heard of generics.  Perhaps you have started using them via the Generics.Collections unit, where you can find TList<T>TStack<T>, etc.  The Delphi Spring Framework contains an even more sophisticated set of collections and interfaces to those collections, including the very powerful IEnumerable<T>

These are all very useful classes, and our code is made much simpler, easier to maintain, and more type-safe because of them.  But using them merely makes us consumers of generics.  If we want to truly take advantage of generics, we need to become producers of generic classes.  It’s a big step to see the benefit of generic collections, but the truly big step is to start seeing opportunities for the use of generics in your own code.

A Contrived, Simple Example

This past weekend, some of my team members and I attended the C-Sharpen event here in Philly.  It was a valuable day, made particularly so by the presentations given by Steve Bohlen.  He gave an excellent presentation on the topic I discussed above – how we need to start thinking as producers of generics and not merely consumers.  In that presentation, he gave a simple example of how generics are powerful and can make your code simpler, more effective, and more powerful.  So, I’m going to show that example here.  It’s a bit contrived, but very illustrative of how to think about generics.

First, consider the following code:

type

  TOrderItem = class
    ID: integer;
  end;

  TOrder = class
    ID: integer;
  end;

  TCustomer = class
    ID: TGUID;
  end;

Now this code is very simple – a set of classes that might represent a simple order entry system.  But right away, something should occur to you.  All three have something in common – they are entities in your system. Down the road, you may want to act upon all the entities in your system, so you might create a superclass like so:

type

  TEntity = class  
  end;

  TOrderItem = class(TEntity)
    ID: integer;
  end;

  TOrder = class(TEntity)
    ID: integer;
  end;

  TCustomer = class(TEntity)
    ID: TGUID;
  end;

But you might be frustrated because you want your TEntity class to have an ID field that is in use by all descendants, but that pesky TCustomer class can’t oblige – it needs a GUID for its ID tag instead of an integer like the other classes.

Instead of fretting about the different types of ID tags, how about just create one that doesn’t care what type it is?  Well, this is where the power of generics comes in.   How about you give the TEntity class a parameterized type – a generic – as  it’s ID, and then just tell all the classes what type their ID tag will be?

type

  TEntity<T> = class
    ID: T; 
  end;

  TOrderItem = class(TEntity<integer>)
  end;

  TOrder = class(TEntity<integer>)
  end; 

  TCustomer = class(TEntity<TGUID>)
  end;

Now, given the above, your entities can all have ID’s, but you don’t have to have the same type for all of them.  If a TEntity descendant needs an ID of a different type, you can just descend from TEntity and pass the correct ID type in the class declaration.  

Again, the example is quite contrived, but I think it does a nice job of showing how you can starting “thinking generically” and not just accept a rigid type structure. 

In addition, it illustrates why the more formal name for generics is “parameterized types”.  The type in the brackets is passed in to the type declaration, and then used within the class, just as method parameters are passed in to functions and procedures. 

A simple, contrived example, sure.  But hopefully it illustrates how generics can be used to turn you from a consumer of generic classes to making them a common tool in your code.

 

Update:

As a number of commenters have pointed out, my original example was sub-optimal.  Rather than post a "correction" post, I've taken the liberty of updating and improving the original article.

Flotsam and Jetsam #57

By Nick at March 16, 2012 09:23
Filed Under: Flotsam and Jetsam, Delphi

How Not to Code: Passing function results directly as parameters

By Nick at March 11, 2012 12:27
Filed Under: Delphi, How Not To Code

I think I’ll start a new series, and a new blog category, called “How Not To Code”.  In it, I’ll try to highlight those little things that we’ve tended to do over the years that, well, are tempting for expediency, but probably not something we should be doing.  There are a lot of “Here’s the right way to do things”, so this series will concentrate on the “what not to do”.  That will inevitably lead, of course, to a discussion of “What to do”, but that’s ultimately the point, I suppose.

Today’s topic is “Don’t directly passing function results as parameters to other functions and procedures”. 

For instance, consider the following code:

type
  TData = record
    a, b: integer;
  end;

  TMoreData = record
    c, d: string
  end;

function GetSomeData(aInteger: integer; aString: string): TData;
function GetMoreData(aBoolean: Boolean; aInteger: integer): TMoreData;

procedure ProcessData(aData: TData; aMoreData: TMoreData);

Then, imagine that you wanted to call ProcessData with the result of  calls to GetSomeData  and GetMoreData.   It would be mighty tempting to simply call:

ProcessData(GetSomeData(aIntVariable, 'ocelot'), GetMoreData(True, AnotherIntVariable));

After all, think of all the typing you’ll save!

You should avoid that temptation, because this way of doing things presents a few problems:

  • It’s really hard to read.
    • A line of code that does more than one thing requires more brain power to read that does code where each line does one thing.  In this case, you have to convince your brain to parse all those parentheses.  Before you can figure out what the code is really doing, you have to parse two function calls inside of a procedure call.  Using your brain to parse unnecessarily complex semantics is a waste of effort.
    • You can’t be sure by merely reading the code what the types of the parameters are that are being passed to ProcessData.  This means that you have to look up the parameter types to gain full understanding.  If the variables were declared locally, then it would be easy to see their types.
  • It’s really hard to debug
    • There are no intermediate results to check in the debugger.
    • Stepping into the code requires that you step into the calls to GetSomeData and GetMoreData, when that might be something that you don’t want to have to do.

Instead of trying to compress everything into a single line of code, you probably would do something like this, instead:

var
  TempData: TData;
  TempMoreData: TMoreData;
begin
  TempData := GetSomeData(aIntVariable, 'ocelot');
  TempMoreData := GetMoreData(True, AnotherIntVariable);
  ProcessData(TempData, TempMoreData);
end;

The above code solves the aforementioned problems – it is easier to parse in your head and you can easily see the data values in the debugger before they are passed to ProcessData

Some good heuristics that fall out of this:

  • If you have to stare at the code for a moment just to parse it in your head before you even figure out what is going on, then you have a problem.
  • If you have a hard time figuring out where to put a breakpoint to get at the debugging information that you really want, then you have a problem.
  • If you feel the need to create intermediate variables to improve your ability to debug code, then you probably should have put the intermediate variables there in the first place. 
  • All sorts of bad things happen when you try to be clever and save a few keystrokes by taking a code shortcut.  Remember, the future maintainer is the person you should be writing code for, not the compiler.
  • A line of code should do one thing and one thing only – if the explanation of what a single line of code does needs the word “and” to describe it, then it probably ought to be two lines of code.

Lesson for the Day:  Always pass variables, never direct function calls, as parameters to another procedure or function. 

On Why I Think Twitter is Awesome

By Nick at March 04, 2012 11:57
Filed Under: TechBiz, General, Tech Stuff, Software Development, Delphi

I have this friend who totally doesn’t get Twitter.  He doesn’t get it so much that it actually kind of makes him angry that anyone does get – and like – Twitter.  To him, it is a total waste of time in every way. He can’t imagine why anyone would spend any time at all having anything to do with Twitter.  And that’s fine – to each his own. But I do find it amusing that someone would feel that way about a service used and enjoyed by millions of people. 

I’m a Twitter lover.  I find it entertaining, amusing, interesting, and good for my brain.  I really enjoy reading it, and I really enjoy posting tweets.  I get good news, good development information, and a good laugh when I read twitter.  I get to express my self in short bursts that  help me formulate my thoughts.  What’s not to like?

The common impression is that Twitter is for “letting you know what your friends are doing” – or at least that is how it was originally marketed.  The common misconception is that Twitter is just a bunch of people posting “Now I’m eating lunch.  Yum!”, and perhaps it was that in the very beginning.  But in the spirit of “Let a thousand flowers bloom”, Twitter became a lot more than that.  Twitter is a forum for expressing not only what you are doing, but what you are thinking, what you are watching, what you are reading, and anything things that you are up to.  It is many things.  It is a means of conducting a conversation across the world.  It is a means of sharing information with like minded people .  It can help you track your customers are thinking.  It can be a source of entertainment.  It can ensure you are up to date on the latest news, and it can even help foment a real live revolutions.  Not bad for a site that posts things  140 characters at a time.

Short and Sweet

Here’s the main reason why I like Twitter:  It forces us to express ourselves in short, concise sentences.  140 characters isn’t a lot, but it’s not nothing.  It is sort of real-world application of Strunk & White’s exhortation of “Use fewer words”.   It’s really quite amazing the amount of humor, wisdom, and pith people can cram into that little chunk of text.  Anyone who cruises around the internets knows that, while it allows people to publish openly without the barrier of a publishing house, folks – this blog included – don’t get the benefit of an editor.  Twitter is the one place where you can know that if you read it, you’ll get things in short, concise, crisp chunks.  (And I should add that I pride myself on never using ‘4’ and ‘2’ and other similar shortcuts….)

I find that pleasing as a reader, and valuable as a writer. If I can express my thought in 140 characters, then I know that I’ve really distilled it to the essence of the thought.  For instance, it took a while for me to get Hodges Law down to 140 characters but I did.  (And I also now have the added advantage of it being in a single place that I refer to my awesome idea – as well as showing that I was the first to think of it.  Winking smile  )

The other big reason I like Twitter is that it is an “easy read”.  If I have a few minutes to kill, I can pull out my Kindle and flip through the latest on my Twitter feed. I’ve knocked out more than a few pages of Twitter feeds at the Doctor’s office.  It also is perfect for solving that First World Problem of being bored while, ahem, “indisposed”.

Third reason?  It’s a wealth of information about Delphi and software development.  Many great developers tweet, and point to articles and blog posts that teach and explain about development.  Want to know what the latest Delphi articles are?  Follow DelphiFeeds.   You can’t say it is impossible to know what is going on with Embarcadero – they have a Twitter feed that updates with just about everything going on with the company.  You can tailor your feed to bring you whatever you are interested in.  I’m interested in Software Development, the NBA, specifically the Timberwolves, certain American Idol contestants, and generally funny stuff.  That’s exactly what my feed brings me. 

HashTags

Another feature that is both fun and powerful are hashtags.  As far as I know, the power and coolness of hashtags was actually an invention of the Twitter community and not an original part of the “spec” for Twitter.  According to this article – which is a great history and summary of hashtags -- the idea actually came from a guy named Chris Messina, and his idea has become part of the power of Twitter.  Hashtags are used to create groups or topics.  Sometimes they are fleeting – like a hashtag for the Superbowl – or sometimes they are ongoing, with people constantly adding to them, like the “#overheardathome” tag.  Want to see what others are saying while American Idol is on?  There’s a hashtag for that.  They have even made a difference in world events.  The valiant folks fighting for freedom in the Arab Spring used twitter hashtags to inform the world and each other about important, world-changing events.  Businesses are event starting to include hashtags in their advertisements (and of course, folks aren’t always respectful of those tags…..)  There’s even a website dedicated to tracking the use of hashtags.  From the humble beginnings of an idea from a single users, hashtags have made twitter into a useful and powerful communications medium.

Comedy

It may have started out as a site to tell your friends that you are eating lunch, but Twitter has become a great place for some quick-witted comedy and entertainment.  Heck, I tweet a lot about technology and programming, but I try hard to make a witty, funny comment every once and a while.   Some people’s sense of humor is just made for Twitter.  One of my favorites is Josh Hara.  If you are looking for a series of laugh-out-loud funny, but off-color tweets, look no further than Pauly Peligroso.    There are tons of lists of (allegedly) funny people on Twitter.  I should add that in my experience, the people that are “supposed” to be funny – that is, comedians whose names you know – aren’t really that funny. But hands down, bar none, the funniest feed on Twitter is Sh*tmydadsays.   In any event, Twitter can definitely make you LOL.  (I only use “LOL” when I, well, actually do laugh out loud. You should follow the same rule.)

Parody and History Sites

Another feature that dovetails on the straight comedy sites are some of the excellent parody sites.  There’s a whole slew of Star Wars characters on TwitterLord Voldemort of Harry Potter fame is enormously popular, on topic, and very funny.  He and Severus Snape often exchange barbs.  (Actually, there are quite a few folks tweeting as Severus Snape on Twitter….)  You can keep track of Batman, Drunk Superman, Aquaman  (Warning: he’s a little….”salty”), Spiderman, Drunk Hulk, and just (presumably sober Hulk. (Apparently there are many facets to Hulk’s personality). Want some history? You can follow Henry VIII, Calvin Coolidge,   You can follow the history of the Byzantine Empire, the first 1000 days of the JFK administration, and real-time events of World War II.  And that is just scratching the surface.  Believe me.  There is no end to the inanity, craziness, and imaginativeness of the folks on Twitter. 

In The End

Yes, Twitter would be boring if it were nothing more than people telling you what they were doing.  It may have been that at one point, but it’s become way more than that.  Shoot, a recent cover of Sports Illustrated had a hashtag for the cover article about Jeremy Lin. In the end, Twitter can me what you want it to be.  You can follow technologists, pop stars, actors, authors, characters from books and movies, business, news sites, newspapers, bloggers, family members, humorists, athletes, historical characters, and more.  You can keep up with technology, world events, politics, all manner of news and events, what your favorite authors/actors/singers are up to.  It’s really a huge, fascinating party that you can control to your heart’s content. 

Why anyone wouldn’t be interested in that, I have no idea.

I don’t want to hear another frackin' negative word about Embarcadero Marketing.

By Nick at February 26, 2012 09:19
Filed Under: Delphi, TechBiz

Not one more word.

For many years, it has been very fashionable to say how “[Borland|CodeGear|Embarcadero] sucks at marketing”.  You could very easily establish your bona fides by bashing Delphi marketing.  Everyone knows that Borland always sucked at it, and all the cool kids say so, right?

Well, I think those days are over.

What is Marketing, Anyway?

First of all, I’m guessing that about 99% of the people saying this didn’t understand the difference between “marketing” and “advertising”.  They aren’t the same, just so you know.  They overlap, but they aren’t synonymous.  The Wikipedia page for marketing starts out with "Marketing is defined by the AMA as ‘the activity, set of institutions, and processes for creating, communicating, delivering, and exchanging offerings that have value for customers, clients, partners, and society at large.’"  My personal definition is “whatever you do to make people aware that your product is for sale and what the reasons are that they should buy it”. 

Sales and marketing are related, but very different.  In general, marketing’s job is to create leads for sales to act upon. 

I think that the root of much of the complaining over the years has been the result of a lack of advertising.  People who don’t see advertising think that there’s no marketing going on.  Marketing is much more than just running ads.  Marketing activities include, but are very much not limited to, advertising. In fact, some of the most effective marketing is that which requires zero advertising.

For instance, Dropbox has a brilliant marketing strategy that has been amazingly successful and requires exactly zero budget for marketing or advertising. What do they do? They get people like me to try to get people like you to sign up. The more people sign up, the more potential paying customers they have. They give away 2GB of space (which probably costs them something like $0.000001….) and then induce those folks to do their marketing for them. They have been enormously successful doing this. They spend zero money on advertising, but they have a fantastic marketing plan that makes millions of people aware of what they have to sell. Awesome.

Delphi Marketing in the Past

I’ll concede that the marketing of Delphi has been historically “limited” or “hard to find” . I’ll not concede that it has been “bad” or “terrible”. The marketing itself has been good – there just hasn’t been enough of it.  Marketing success is largely a function of budget, and over the years, and the budget for marketing Delphi has not always been huge. As noted above, there isn’t a direct relationship between marketing and money, but certainly money is a big boost.  Limited budgets have made it harder to market Delphi, but that doesn’t mean that the marketing that was done was done poorly.

Despite limited budgets, here has always been marketing going on around Delphi.  Every new release resulted in many activities, a “world tour”, webinars, etc.  And here’s a key point to remember:  if you are an existing customer, then marketing to you is fairly easy. You already know the products and benefits.   To a large degree, efforts spent on marketing that you see is wasted effort.  The perfect marketing plan would be visible only to non-customers and invisible to existing customers.  And here’s the second thing to remember -- if you know that Delphi is on version XE2, and even the basics of the current feature set, then you have been successfully marketed to, whether you want to admit it or not! That’s always been the case – if you knew about the latest release and it’s features, you were successfully marketed to. 

Delphi Marketing Today

However, over the last few years, things have been getting better.  And over the last year or so, things have gotten, well, really good.  In that time, I’ve seen a marked and obvious increase in marketing activity and an rise in the quality of things done for Delphi and Embarcadero products in general.  Clearly someone has decided to spend some money and make it a point of emphasis. 

I now see the following on a regular basis:

  • First, the overall outbound communication in general has steadily picked up.  I now see people who for years didn’t hear a peep from the Delphi marketing team now complaining that they are getting too many emails.  Some are even upset that their sales representative has called them.  Yeah, that’s terrible!  I myself had a very nice chat with our sales person last week --  they were pleasant, knowledgeable, and helpful.  We probably won’t be upgrading our licenses until next year, but they were happy to know that, and interested in hearing my feedback on a wide variety of things, including the product, the marketing efforts, and other things of concern.  I appreciate a vendor that takes the time to hear me out.
  • A steady stream of webinars on a wide range  of topics.  It seems that at least once a month, they are conducting a webinar of some sort, on topics ranging from Delphi to database design and enterprise architectures.  I get very professionally done emails, I sign up, they remind me about the event, and they follow up with emails after.  If I miss it, they send an email saying “Sorry we missed you, here’s the replay”.  As a result, you see their products in action, you learn the new features, and you are steadily reminded that the product is there.  Excellent work.
  • When they aren’t doing webinars, they are letting me know about White Papers that well known Delphi community members have written.  There a lot of them available, and a steady stream of new ones coming online.  Nice.
  • I haven’t seen them recently, but for the last few years, Embarcadero has had a full page advertisement in every issue of SDTimes.  I’ve also seen banner ads on the SDTimes website. 
  • And while on the subject of ads, I see Delphi banner ads all over the place.  They clearly have paid Google for the adwords, and since Google knows I’m a Delphi user, I see ads for Delphi and RAD Studio all over the web.  Nice.
  • They also appear to have bought keywords on StackOverflow.  Try this – log out of StackOverflow and go the Delphi tag page and see what you get on the right side.  (If you don’t any reputation at StackOverflow, you don’t have to log out – they stop showing ads after a certain reputation score).
  • For a long time, the Borland/CodeGear/Embarcadero website was….less than helpful.  However, now, it is really well done.  Checkout the Delphi page.  It’s visually appealing with a  good highlight of the product. Easy to find links take you to the Product Edition page, a page showing cool third-party stuff, and free resources out on the web, among other information  And of course the page has a clear “call to action”, either buy or download a trial.  This is a very nicely done web page.
  • And if the webinars were not enough, the Developer Relations team did an excellent (and well attended, I might add…) series of live seminars all over the world.  These were well advertised and well run.  They included user group events during week nights, and for the first time. some day long events on Saturday.  In talking with the DevRel folks, I know that these were particularly successful.  I had the honor of being the guest speaker at two of them, in Washington, DC and in Newark, NJ.  Over the last year, the team has also put on a CodeRage event, the 24 Hours of Delphi, and a Delphi Birthday Party.  The hits just keep on rolling.
  • The marketing department even has a blog – The Delphi Insider – run my by friend Tim Del Chiaro.  If you want to  know everything that is going on, that is a good place to start. And of course, there are a number of active (an inactive, sadly) blogs on the Embarcadero servers.

The folks marketing Delphi are doing some really good work, and we should appreciate and recognize it.  Embarcadero has clearly stepped up its game, and we should all give credit where credit is due.

Flotsam and Jetsam #56

By Nick at February 24, 2012 17:24
Filed Under: Delphi, Flotsam and Jetsam, Personal

On the Proper Design of Exception Hierarchies

By Nick at February 19, 2012 13:13
Filed Under: Delphi

Introduction

Exceptions are all over the place in Delphi.  Introduced way back in Delphi 1.0, they totally changed the way that folks looked at error handling.  Previously, we’d do things like:

ErrorCode := DoSomething;
if ErrorCode > 0 then 
begin
  DoNormalStuff;
end else
begin
  UhOh;
end;

We had to constantly interrupt the flow of our code in order to make sure that all is well.  Exceptions changed all that by letting you put all the error handling at the end, in a try…except block – out of the way of the flow of your code -- where you could handle things separately, leaving you to worry about how things should go, and not how they might go wrong.

Way back for Borcon 2004, I wrote a paper on exception handling called “Exception Handling for Fun and Profit”.  You can read that and get a good idea on the proper way to handle exceptions.  It is eight years old, but it’s still all good advice.

What I want to talk about here, though, is the best way to write your own exception classes and exception class hierarchies.  The Runtime Library gives you a number of Exception types, and it uses most of them.    You are, of course, free to use any of those exceptions declared in SysUtils.pas and elsewhere, and of course you can simply create an exception from the base class Exception. But most often when writing your own library code, the standard exception classes are not enough.  So I’m going to try to give you some ideas on how you can and why you might create your own exception classes.

A note before I start: Exception hierarchies should be part of library code; that is, code you write for use by other applications. As noted in my aforementioned article on exceptions, application developers should trap exceptions, and library code writers should raise exceptions. Exception hierarchies are part of developing library code, so this article really only pertains to that side of the fence.

The Basics

The first thing I’ll tell you is that you should never raise a plain exception:

raise Exception.Create(‘An error occurred’);

I can’t think of any reason for ever doing that.  It provides no useful information about the type of exception and why the exception being raised, leaving consumers of your code with little helpful information.

So, as you’ve probably noticed,  I like to say “You should never do <this>”.  And of course, when I do that, it’s incumbent on me to say what you should do instead.  So here goes.

First, you should always raise a specific exception for a specific exceptional situation.  If it’s a “normal” exception, use on of the standard Exception classes that are part of the RTL.  For instance, if you are dealing with streams, and you have an error, you might raise an EStreamError

Most often, though, you want your exception to be as precise and exact as possible.  This way, it will be easier to pinpoint exactly what went wrong when the exception is captured and displayed.  And in order to do that, you should create your own exception hierarchy.  If an existing exception type isn’t perfect for the situation, then don’t be afraid to define one that is.

And when you do that, the hierarchy you create should be flat and wide.  Flat and wide exception hierarchies allow for the simple organization of similarly purposed exceptions.   Here’s what I mean by that.

Flat and Wide

I’ll use my class library THTMLWriter as an example.  It it, there is a unit called HTMLWriterUtils.pas that contains the following code:

type
  EHTMLWriterException = class(Exception);
    EEmptyTagHTMLWriterException = class(EHTMLWriterException); // Tested
    EOpenTagRequiredHTMLWriterException = class(EHTMLWriterException); //Tested
    EHeadTagRequiredHTMLException = class(EHTMLWriterException); // Tested
    ETryingToCloseClosedTag = class(EHTMLWriterException); // Tested
    ENotInListTagException = class(EHTMLWriterException); // Tested
    ENotInTableTagException = class(EHTMLWriterException); // Tested
    ENotInCommentTagException = class(EHTMLWriterException); // Tested
    ENotInFieldsetTagException = class(EHTMLWriterException); // Tested
    ENoClosingTagHTMLWriterException = class(EHTMLWriterException);
    ENotInFrameSetHTMLException = class(EHTMLWriterException); // Tested
    ENotInMapTagHTMLException = class(EHTMLWriterException); // Tested
    ENotInFormTagHTMLException = class(EHTMLWriterException); // Tested
    ENotInObjectTagException = class(EHTMLWriterException); // Tested
    EClosingDocumentWithOpenTagsHTMLException = class(EHTMLWriterException); // Tested.
    ETableTagNotOpenHTMLWriterException = class(EHTMLWriterException); // Tested
    EParamNameRequiredHTMLWriterException = class(EHTMLWriterException); // Tested
    ETagIsDeprecatedHTMLWriterException = class(EHTMLWriterException); // Tested
    ENotInSelectTextHTMLWriterException = class(EHTMLWriterException); // Tested
    ECaptionMustBeFirstHTMLWriterException = class(EHTMLWriterException); // Tested
    EBadTagAfterTableContentHTMLWriter = class(EHTMLWriterException); // Tested
    ENotInDefinitionListHTMLError = class(EHTMLWriterException); // Tested
    ECannotNestDefinitionListsHTMLWriterException = class(EHTMLWriterException); // Tested
    ECannotAddDefItemWithoutDefTermHTMLWriterException = class(EHTMLWriterException); //Tested

This is an example of a “flat and wide” exception hierarchy.  The hierarchy is “flat” because there are only two levels of inheritance – the base class and a large number of descendants.  A class diagram of these classes would be “flat” because there isn’t much distance from the top to the bottom of the inheritance.  It’s “wide” because there are a lot of sibling classes on the second level of inheritance.  The class diagram would take a lot of horizontal space if it were laid out on paper.

How does this all work?  First, I declared a base type, EHTMLWriterException.  All the exceptions raised in the THTMLWriter library will be a descendant of this type.  As a result, you can easily check the type of an exception, and if the type is EHTMLWriterException, then you know what library raised the exception.  When you are using the THTMLWriter library, you can easily trap all the exceptions raised by the library within your exception handling code by simply calling:

try
  //code that raises an exception in THTMLWriter....
except
  on E: EHTMLWriterException do
    //you know that the exception came from THTMLWriter
end;

Second, I declare a large number of very specific descendants that are raised in very specific situations.  Their names are very descriptive, and they are usually raised only in one place – the exact place that the error occurred.  This makes locating the cause of the exception much easier.   Precisely named exceptions can be easily searched for in code.

An Example

For instance, here’s an example of some code calling a very specific exception:

function THTMLWriter.OpenParam(aName: string; aValue: string = cEmptyString): IHTMLWriter;
begin
  CheckInObjectTag;
  if TStringDecorator.StringIsEmpty(aName) then
  begin
    raise EParamNameRequiredHTMLWriterException.Create(strParamNameRequired);
  end;
  Result := AddTag(cParam)[cName, aName];
  if TStringDecorator.StringIsNotEmpty(aValue) then
  begin
    Result := Result[cValue, aValue];
  end;
end;

Here you can see that the code raises an exception named EParamNameRequiredHTMLWriterException.  The class name alone tells you that it is an error from the THTMLWriter library, and that it was raised because a parameter name was required but not found when the call was made.  Just the exception’s class name has a lot of information.  In addition, you’ll note that when I raise these specific exceptions, I include a very specific, detailed error string explaining what happened.  In my view, you can’t have enough information in an error message. 

Thus, if you end up raising this exception, you’ll get this:

image

Given all that, if you can’t figure out exactly what the problem is and exactly where it occurred, well, then I’m not sure you are in the right business.  Winking smile

Lots and Lots of Exception Types

Since it is fine – and even desirable – for exception hierarchies to be wide, you shouldn’t be shy about declaring many exception classes as direct descendants of your one main exception class.  You’ll note above that even in a small library of code like THTMLWriter, I’ve declared 23 exception types.  I see nothing wrong with having a large, very specific set of exceptions that you can raise throughout your code library.  As I said before, if your exception type is only raised once, that’s fine – it’s very easy to find the location of an exception that is only raised in one place. 

Conclusion

So there it is – make your exception class hierarchies flat and wide, use good exception messages when raising them, and you’ll enable the consumers of your code to easily see where problems are arising and to quickly deal with them when they do.

My Book

A Pithy Quote for You

"Luck is what happens when preparation meets opportunity."    –  Seneca

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.