Widgets Software Development

Blast from the Past: Delphi may be the only choice you have

By Nick at November 22, 2012 01:08
Filed Under: Delphi, Software Development

Yet Another Blast  from the Past, this one from November 23, 2003.  This one is kind of moot now, as well, eh?

As frustrating as it is to us Delphi lovers, Delphi has always been a tough sell in corporate America -- not because Delphi isn't perfectly capable of performing any task that a corporate development team might throw at it, but mainly because many managers and decision makers aren't willing to take the perceived risk of investing in a non-Microsoft development solution. Borland has (rightly perhaps for a while in the past, but certainly not for a few years now) the reputation as being a bit on the edge financially, and so the safe, "nobody ever got fired..." decision has been to buy Microsoft. This will probably continue to be the case for some time, as Microsoft certainly will continue to be the a dominant company in the marketplace for the foreseeable future. However, I think the advent of the .Net Framework as the "platform of the future" and Microsoft's particular strategy for moving people to .Net both provide Borland and Delphi developers with a unique opportunity that actually makes Delphi the only safe development platform for a large number of projects that will be developed over the next few years.

Microsoft clearly wants us all to move to .Net, and frankly, I think we all should be happy to make that move. The .Net platform is really cool and really powerful. It provides a very capable and easily accessed framework (the Framework Class Library, or FCL) that is light-years ahead of the Win32 API. Microsoft actually seems to have finally figured out object-oriented programming. Once the actual framework becomes ubiquitous, or even the basis for the operating system itself , building, managing, and deploying applications will be much easier than it is now. I, for one, am eagerly looking forward to Delphi 8 for the .Net Framework and being able to develop applications with it.

Microsoft clearly wants you to move to the platform as well. They make it totally easy to download and install; every new operating system includes it, and they are on an all-out marketing campaign to raise awareness in the developer community in order to promote its use among software developers. The most interesting thing about all of their actions, though, is that they clearly want to force people to make the jump to .Net by pretty much cutting off existing development paths and by not providing a clear migration path for existing applications. It appears that the idea is to instill a bit of panic in their community of developers -- "Holy cow, we'd better get on this .Net bandwagon, or we are going to be left behind!"

Sadly, that is pretty much the case -- VB and C++ developers who don't migrate to .Net soon will be (are?) pretty much abandoned. Sure, there's "Managed C++", but what serious C++ developer would really want to use this neutered version of the language? VB6 developers are abandoned in the sense that VB.NET is so different from what they have done that it is pretty much a whole new language. Code written for VB6 simply won't compile in .Net. And of course, there were no existing C# projects before .Net was released. Therefore, if you are a Microsoft development shop, and you want to move to .Net, then you are pretty much talking about a complete rewrite of all of your Win32 code no matter what you were using to develop those applications. There simply is no easy migration path to .Net for your existing applications.

And that, of course, begs the question -- "What to do for a new application that needs to run on Win32 today, but that will eventually migrate to .Net sometime in the future?" This isn't an unreasonable question -- shoot, it is probably very common. There are certainly new development projects being started everyday, and .Net looms out on the horizon for all of them. It is also a question that is tough for Microsoft shops to answer. While the .Net Framework is readily available, it is certainly not ubiquitous, and there are plenty of machines out there in the corporate world, small businesses, and homes that can't even handle the .Net Framework and that won't be able to handle it for sometime yet. That means that Win32 may be the only option for new development. However, anyone starting new development today probably will want to be able to migrate that app to the .Net platform in the future. If you choose C++ or VB6 for the Win32 version, there simply is no easy way to migrate that application to .Net. Any Microsoft-based development solution for the Win32 platform today means pretty much a complete re-write for that application when it comes time to migrate it to .Net.

But hey, there is a solution -- a non-Microsoft one -- to this problem: Delphi. Delphi provides a powerful, fully-capable Win32 development platform, and with the VCL for .Net, a much, much smoother migration path for Win32 to .Net. And when you do move to .Net, Delphi 8 for the .Net Framework provides powerful tool that is a first class citizen in the .Net development world. If you are starting a new development project in Win32, and need to be able to move that project to the .Net framework some time in the future, then Delphi is your only real choice. Microsoft-only development organizations quite conspicuously have no similar choice. The VCL is cross-platform -- at least between Win32 and .Net. Applications build in Win32 using Delphi and the VCL should migrate relatively smoothly to the .Net platform today . VCL for .Net exists, and has been available to Delphi 7 owners via the Delphi for .Net Preview since last summer.

Now I am not at all claiming that the migration will be totally seamless -- you may need .Net version of third-party components, and if any of your code calls into the Win32 API directly, you'll need to update that. In addition, not all of the technologies that were in Delphi 7 will make it into Delphi 8, and certainly the presence of garbage collection in the .Net framework may affect the way your code works, but the migration is clearly not a complete rewrite as discussed above. Heck, at this year's Borland Conference, they compiled and ran in Delphi for .Net an application that was originally a demonstration application for Delphi 1 -- a 16-bit development tool! Can't get much more compatible than that.

This fact alone ought to be changing the way that developers and companies view Delphi. Delphi will drastically lower the overall total cost of a project by drastically reducing the time and effort needed to migrate a Win32 application that needs to be built today to the .Net framework tomorrow. Delphi doesn't lock you in to either Win32 or .Net and doesn't force you to move to .Net faster than you or your budget might want you to. Delaying the transition to .Net can also save money, as building applications in Win32 now for existing hardware can extend the life of that hardware rather than accelerating the hardware upgrades to run the .Net Framework.

Smart managers already know that they are stuck in a tough spot and smart Delphi developers will be quick to point out the advantages of using Delphi for new development. So if you have been looking for that silver bullet to convince your managers or your customers to use Delphi as the development tool for that upcoming project, you now have it.

Permalink|No Comments Yet|Login at the right or register with the site to add a comment.

Using LeanPub’s Markdown

By Nick at November 18, 2012 05:53
Filed Under: Delphi, Software Development, TechBiz

I’ve been doing a lot of Markdown lately.  It’s a pretty interesting notion – it’s similar in concept to HTML (a mark”up” language), but Markdown is about 443 times simpler.  Jeff Atwood is a big fan (StackOverflow uses Markdown for formatting questions and answers…) and called out Markdown’s creator, John Gruber, to be a better “parent” to Markdown back in 2009.  Recently, he has called for a standardization of the language, asking Gruber to take the lead in doing so.

Apparently, however, John Gruber, creator of Markdown, wasn’t as, ahem, “supportive” as he could have been.  At first, Jeff didn’t at first get response, but apparently then he did.  But apparently Gruber wasn’t exactly into it, or even that respectful about Jeff’s reasonable request.  I guess he’ll “think about it”.  Gruber clearly is more from Philadelphia than most people from Philadelphia, I guess.  Jeff points out that Gruber created something pretty cool, but then hasn’t exactly been the most benevolent of fathers.  And he’s not asking for anything other than a blessing on what they are doing, really.  Gruber could clearly be a bit cooler about it than he is being.

Markdown is one of those things that can easily become bastardized.  It’s specific purpose is to be human-readable and human-writable.  However, the temptation is quite great to start adding to it, making it not both of those things.  Hence Atwood’s appeal.  I hope Jeff makes something happen in this area, with or without Gruber’s support.

Anyhoo.  I’ve been using Markdown because that is what LeanPub™ uses it to create books.  As I said above, one of the main ideas of Markdown is that it should be both easy to type and easy to read un-rendered.  But that doesn’t mean that we geeks don’t want a tool to create it.   Winking smile.  The most popular editor for Windows appears to be MarkdownPad, which is a nice tool.  There is an early version of a WYSIWYG editor for Markdown called Texts – it looks promising but has a ways to go.  Some folks appear to be using Emacs (yuck!) or other editors only available on the Mac. 

However, LeanPub™ appears to be doing what Atwood is worried about – extending it just a little bit beyond what the standard is.  That’s fine -- they’ve added Tables, and different code tags using Pygment – all of which are not supported by the “normal” editors.  For instance, I’m writing a technical book with lots of code samples, and tools like MarkdownPad can only be so helpful.  As  much as Markdown is meant to be human-writable, it’s a bother to add in manually the tags for Delphi code blocks, for instance.

So pursuant to that, and because I want to make writing my book as easy as possible, I’ve built a Markdown Editor -- I'm calling it LeanTed --  that is designed specifically for LeanPub™ authors.   It implements the LeanPub™ Markdown standard, supports code tagging, and other Markdown stuff that is used by LeanPub™.

It is written in Delphi XE3, as you would expect of me.  The main editor window is a TSynMemo, and it uses the Ribbon controls that ship with Delphi. 

You can get it here.  Please be warned – this is currently a very early version and not fully featured.  I’m using it myself to write my book, but I understand all the quirks.  I’ll be refining it as I use it more, of course. 

Features that I already have on the list to be added include:

  • Implementing LeanPub’s Table support  and CrossLinking -- (The current Table stuff doesn't do anything other than display what would be added....)
  • Associate it with *.md files
  • Notice when the file has changed elsewhere
  • Timed Autosave
  • Synchronize the text and preview modes (anyone have any idea how to control the scrolling on a TWebBrowser control....?)
  • A lot of little details that I’m keeping track of in my TODO list…
  • Anything anyone thinks of that would be a good feature.

I’m releasing it as Freeware, but please feel free to donate to me for the software.  $15 would be niceSmile

In any event, please let me know what you think in the comments, and please remember that this is totally alpha-level software and that you use it entirely at your own risk.  I will, of course, be updating and improving it, incorporating feedback and suggestions. 

Measuring Developer Productivity

By Nick at November 11, 2012 03:19
Filed Under: Delphi, Leadership, Software Development


If you go to Google and search for "measuring software developer productivity" you will find a whole lot of nothing. Seriously -- nothing.

Well, okay, not exactly nothing. You'll get a ton of links. But almost all of the links you find will talk about how measuring the productivity of software developers can't be done effectively. Some people will even argue that it shouldn't be attempted at all. Some others will describe techniques to measure developer productivity, that, well, everyone else knows don't really work.

There have been many valiant attempts to measure developer productivity, but all seem to end in less than successful territory. (We all know to laugh at "Lines of Code" as a productivity measure). Virtually any objective measurement you can apply to the software development process can be "gamed" into submission.

There are just too many variables to account for everything that goes into the development process. Measuring any one of them, or even a combination of them, simply cannot begin to capture effectively everything that is involved. You can't pick a surrogate thing to measure, but because of human nature, developers will react in ways that will skew the measurement.

Many studies have been done on this topic, with little to show for it. Every software development manager who has to fill out a developer's evaluation or determine who gets bonuses has struggled with this. Many a leading expert and guru has thought about and researched this thorny topic.

Experts Agree

And not one of the experts has come up with a good idea or method to measure individual productivity. There are plenty of good and effective ideas on measuring team and project productivity, but there is a severe if not complete shortage of ways to measure individual performance and productivity.

For instance, Robert D. Austin wrote an entire book on this subject called Measuring and Managing Performance in Organizations and came to the conclusion that unless you can measure 100% of something -- that is, every aspect of it -- then there is no point in measuring at all. If you attempt to measure less than 100% of the things involved in a given activity, you will get what he refers to as "dysfunction", or what you and I might call gaming the system. And since software development is an incredibly complex and creative endeavor, it's virtually impossible to measure every aspect of it. Often it quite literally involves sitting and staring at a computer screen. How do you measure the productivity of that?

Here's Martin Fowler's conclusion in an article he entitles " CannotMeasureProductivity":

"This is somewhere I think we have to admit to our ignorance."

Neil McAllister of InfoWorld writes in an article entitled " The futility of developer productivity metrics"

"For most other companies, however, it might be best simply to forget about the idea of measuring developer productivity and rely instead on tried and true methods. That's right: A highly effective, productive developer workforce is often the result of high-quality, effective management. Unfortunately, nobody has developed a metric for that yet. Coincidence?"

Joel Spolsky writes:

"It's rather hard to measure programmer productivity; almost any metric you can come up with (lines of debugged code, function points, number of command-line arguments) is trivial to game, and it's very hard to get concrete data on large projects because it's very rare for two programmers to be told to do the same thing."

Steve McConnell, a widely regarded academic, author, and consultant says:

"So while I see the value of measuring individual performance in research settings, I think its difficult to find cases in which the effort is justified on real projects."

Like I said, it's hard to find a leading expert making the case for objective measurements, and easy to find plenty that say you shouldn't even try.

So I don't think that it's a tough leap to agree that there is no objective way to measure productivity in software developers. I know this is controversial, but it seems quite clear to me that software is more art than science, and measuring productivity in art is, well, simply not done. One does not tell Michelangelo that it took him too long to paint the Sistine Chapel because he should have been painting 1.4 square feet per day instead of 1.2. That would be preposterous.

So, What Are We to Do?

Anyone who is charged with managing and leading developers is left in a quandary. We want to be fair, but if everything is subjective, how can we be?

The fact that there is no objective measure of developer productivity doesn't mean you can't measure it. It just means that you have to measure it subjectively . And we do that, don't we. You can look around your shop and just know who the productive developers are. There are probably developers you know that simply crank out good code faster and fix bugs more efficiently than the rest. For ease of discussion, I'll give this developer the name "Jason".

And just how do you know Jason is more productive and more valuable? You just do. You can just tell. You know it when you see it. But if you stop and think about it, Jason has some characteristics that you can figure out and write down.

What I mean is that if you stop and examine Jason and his work, there are things that you can say about him that describe what he is all about. They are subjective, sure, but you can write them down and give an "objective" measure to these subjective things.

A Modest Proposal

So yeah, what I am proposing is a way to measure developer productivity and value via a subjective set of measurements. Think of it as a way to qualify the notion of "you just know that Jason is productive".

Here is the list:

  • Productivity
    • Does the developer get a reasonable amount of work done in a given period of time?
    • Is the developer's velocity on bug fixing sufficient?
  • Engagement
    • Is the developer dedicated to his/her craft?
    • Is the developer committed to delivering software on time?
    • Is the developer dedicated to company success?
  • Attention to Quality
    • To what degree does the developer's code work as designed?
    • Does the developer thoroughly test code and believe it to be correct before checking it in?
    • Do a minimal number of bugs get reported against his/her code?
    • Does the developer write unit tests for all new code?
    • Does the developer follow the Boy Scout Rule and leave a module cleaner than it was before he or she worked on it?
  • Code Base Knowledge and Management
    • To what degree does the developer understand the code base assigned to him/her?
    • Does the developer take responsibility for his/her team's code base, improving it at every opportunity?
  • Adherence to coding guidelines and techniques
    • Does developer's code routinely meet coding standards?
    • Do code reviews reveal a minimum of problems and discrepancies?
    • Does the developer use Dependency Injection to ensure decoupled code?
  • Learning and Skills
    • Is the developer constantly learning and improving his/her skills?
    • Does the developer show a passion for the craft of software development?
  • Personal Responsibility
    • Does the developer first assume that the error lies within his or her code?
    • Does the developer understand that he or she is solely responsible for their code working correctly?
    • Does the developer take pride in their code, ensuring it is clean, tested, easy to read, and easy to maintain?

Again, these seven items are all subjective measurements. All the questions require the evaluator to make subjective judgments. But a good lead/manager is presumably in their position because of their good judgment about such things, and so they should be able to make fair and accurate assessments about Jason's productivity using these "measurements".

Most of the questions ask for a yes or no answer, but all can spark a discussion with management or even the developer being evaluated. You could use these measures on a formal evaluation form. Whatever you do with them, it's probably better than the "just know it when I see it" approach you are probably taking now.


In the end, any evaluation, judgement, or other assessment of the productivity or value of a single developer will be subjective. No one has yet found an objective way to measure individual productivity in our excessively complex profession. But I am saying that it is possible to qualify and make judgments about a specific set of criteria as a small and humble step towards being able to do the thing that our industry has so far found very difficult.

My suggestion is that we accept reality and embrace the subjectivity -- and lack of objectivity -- in measuring developer performance.

How Not to Code #3: Compound ‘with’ Statements

By Nick at November 03, 2012 04:24
Filed Under: Delphi, How Not To Code, Software Development

Seriously, think about this:

  with (Sender as tStringGrid), Canvas do

I’m doing some string grid work, and ran across this code out on the web.  Wow.  It does what I want, but really?  It was code on a page with a date of like 1998, so at least we could say it was before many Delphi developers knew better. But still….. that is just awful. 

Here’s the truly hideous part – if I comment the line out,  the code still compiles!  Yikes!

Less is More for your CSS

By Nick at October 24, 2012 10:34
Filed Under: Delphi, Software Development, Tech Stuff

As you may have noticed, I made a few changes to the website here at good ol’  I added a column of boxes on the left, with the idea being to make stuff more accessible without so much scrolling.  And, well, yeah, okay, I’ve used that space to add a few more advertisements.

And while I was at it, I cleaned up a few things with the layout and the CSS.  It’s what I did with the CSS that I’d like to talk about today.

The main thing that I did was to start using the CSS pre-processor called Less.  Less allows you to do a lot of things “right” when writing CSS.  The first thing you notice when you start writing CSS is that it is a horrible violator of the DRY principle – Don’t Repeat Yourself – and Less solves a bunch of those problems.  It’s hard to write “clean CSS code”.  Less can help.  Less allows you to:

  • Create a *.less file that is then processed into your CSS file.  You can do this manually with a command line preprocessor, or you can do it on the client-side with Javascript.  Below, I’ll discuss how I pre-processed my *.less file automatically
  • Declare variables for colors and other things.  Say you have a color that you use in a number of different places.  You can declare

         @WidgetBorderColor: green;

    and then everywhere you had to type green, you could put @WidgetBorderColor instead.  Then, if you want to change from green to red, you only have to do it in one place.  That is really nice. 
  • You can also declare mixins – or chunks of CSS code that are commonly used.  For instance, if you have a bunch of places that use  

         {padding: 0px; margin: 0px}

    then you can declare

         .p0m0 {padding: 0px; margin: 0px}

    and use that as an “alias” in your *.less files

       body {
        font-family: Verdana;
        font-size: 13px;
        color: @Black;
        background: @White ;

  • You can also use parameters to pass in to your mixins if you want, an other more complex constructs, though none of it is terribly difficult.   The Less page has all the documentation in one place.  The two features above were what I used in an effort not to repeat myself in my CSS.

Once you have your less file set up, you can process it via the command line, or using a GUI compiler tool.  Because Less is written in Javascript, you can use node.js to run it on your local machine.  To do that, you can download the Node Package Manager and then install  Less by simply executing

npm install less

npm is kind of interesting – it’s an online registry, so when you issue the above command, it goes out to a public registry and finds the Less package and simply installs it – there’s nothing for you to install. I guess it is much like Nuget in that regard. 

After that, you can then execute the lessc compiler. 

So the workflow at this point is:

    1. Write CSS and Less code in a *.less file
    2. Compile the *.less file into a *.css file.  (For instance, I use a batch file with:  c:\Code\node_modules\.bin\lessc C:\NickHodges\themes\nick\style.less c:\NickHodges\themes\nick\style.css
    3. Deploy the new CSS file with my site
    4. Repeat as necessary

Step 2 is kind of a bother, though.  You have to shell out to the command line to do the compile.  Who wants to do that if you don’t have to?

Well, I sure don’t.  So I found a cool tool called WinLess which does a nice thing – it automatically compiles your Less code into CSS every time you save your *.less file.


It works great – you just point it to your *.less files, and whenever you save changes, it automatically compiles the Less code down to CSS.  That way, your CSS is always up to date, and you just have to worry about your Less code.  Maintaining the CSS file is totally painless.  So now the workflow is:

  1. Update your *.less file as desired
  2. Save
  3. Deploy your *.css file.

That’s a lot easier, eh?

Now what I really want is a tool to find patterns in your CSS and automatically turn them into Less entries.  That would rock.

CSS is powerful and cool, and you can’t create a well-designed website without it.  But as a language, it’s not really very “best coding practices friendly”.  Less makes it much more so.  If you set things up correctly, you can do your styling in Less and forget about CSS altogether.

What do you guys do with your CSS?

Flotsam and Jetsam #67

By Nick at October 20, 2012 00:12
Filed Under: Flotsam and Jetsam, Delphi, Software Development
  • For those of you who still cling to the archaic notion that “Delphi Marketing Sucks”, you should know that I can’t go anywhere on the internet without seeing an add for RAD Studio XE3.  One of the things I appreciate about Google Adsense is that it knows the kinds of ads I want to see and what I am interested.  And it has very astutely determined that I like Delphi.  And Embarcadero marketing has very astutely provided ads to let me know that RAD Studio XE3 exists and that I can buy it.   That’s what marketing is all about.
  • How have I managed to miss this page of cool stuff all these years --  Delphi Inspiration? I’m particularly intrigued by the Delphi pre-processor.
  • Cool Thing Built With Delphi of the Week: dbConstructor
  • A bunch of you have ordered Delphi XE3 from me. I am very grateful. Thanks.  It's a great release -- I'm really enjoying using all the cool new language and RTL features, and I think you should too.

My Take on TypeScript

By Nick at October 17, 2012 12:43
Filed Under: Delphi, Tech Stuff, Software Development

Microsoft has been keeping the renowned Anders Hjelsberg busy on a new language called TypeScript.  Typescript is an open-source project (using the Apache 2.0 license) that allows you to write a super-set of Javascript that allows for a stronger typing system.  You can watch Anders’ original launch presentation

I’ve said a million times that I’ve said a million times that Javascript is the new Assembler – that Javascript will become the thing that everyone compiles higher level code into.  You’ll write your web apps in a higher order language, and then compile them to Javascript for execution in the browser. 

I refuse to believe that any rational person actually likes to write Javascript, and as it is designed currently, it really isn’t a language for developing the kind of large-scale applications that people seem to be wanting to use it for.  In the deep, dark past, Assembler used to be all there was, and we created higher order solutions that compiled to assembler.  And in the same way, for a while, Javascript was all there is for the browser.  Now, however, we are beginning to see higher order languages being brought to bear to produce Javascript for us. 

If Javascript is the “new Assembler”, then the Browser becomes the “new operating system”.  The cool thing about that is that the “new OS” is ubiquitous.  Just about every computer in the world – computers running Windows, OS X, Linux, Unix, whatever – has a browser that runs Javascript.  That means your application can run on any computer.  That’s a very compelling idea.

You can actually do that today with Delphi using a very cool tool called Smart Mobile Studio.  There is also the Elevate Web Builder tool from Elevate Software.  Both have the same idea – leverage the power of Delphi to produce Javascript-based applications.  Pretty cool, really.

Anders talked to Scott Hanselman about Microsoft’s offering in the “Language to compile down to Javascript” arena in the latest episode of Hanselminutes.  Anders is always a good interview – I love a guy who thinks and speaks as clearly as he does.  (That’s why I always loved a Danny Thorpe presentation.  Danny is pretty quiet and mellow, but his talks were always so clear and well organized – every single word he said was worth listening to – that they were always excellent and enormously educational.  Anders is the same way….) He does a great job discussing the notion behind TypeScript.

Here are some of my thoughts on what Anders said and on TypeScript in general.

  • TypeScript seems to exist for two reasons – to make Javascript “tool-able” and scalable. 
    • First, the type annotations, classes, modules, and other enhancements exist to allow Visual Studio and other IDEs to do things like Code Completion (the RAD Studio term that Anders used in the podcast instead of Intellisense – I loved that.  Smile  ), refactoring, and other language-based features that modern IDE’s do.  Javascript doesn’t provide enough information to let development tools do all the things that we expect, but TypeScript does. 
    • Second, TypeScript is also a way to make Javascript scale. By providing the notion of typed classes and modules, you can create larger, well-organized TypeScript applications which then compile to Javascript.   TypeScript is a language ready to do the heavy lifting that Javascript cannot.
  • Since TypeScript is a super-set of Javascript, it follows that pure Javascript is valid TypeScript.  Anders points out that you can use your existing Javascript as is inside of TypeScript.  The idea, though, is that TypeScript becomes the language you’d use instead of Javascript because of all the tooling support, and because it can be used to build applications via modules (units, for you Delphi folks).    Typescript doesn’t have any runtime or virtual machine – it literally just compiles to Javascript. 
  • You can create an external declaration file to define the types in your *.js file, so that means that existing Javascript libraries like Node.js and jQuery.js can be “typed” and thus used in the TypeScript environment.  I think that is a pretty cool idea – and I’m sure that Microsoft will be delighted if the community follows their lead and “converts” the existing popular libraries.
  • Anders also points out that TypeScript puts a “dial” on the typing level of your code.  Pure Dynamic advocates can leave everything untyped, and the strong-typing zealots can type everything if they want, and the folks who want to type some things and not type others can do that if they want.  That’s a very interesting notion – a language with a variable level of type-safety.

Now one thing to note is that tools like Smart Mobile Studio and Elevate Web Builder offer pretty much all these features as well.  There isn’t any reason that Embarcadero couldn’t make Javascript be something that is output by the Delphi compiler.  Heck, there is even a project out there to get LLVM to produce Javascript.  TypeScript would integrate well into HTML5 Builder. Whatever higher-end language you want to use, it seems pretty clear to me that Javascript will be the thing our compilers will be producing in the not-to-distant future.

Are you going to give TypeScript a look, or are you more interested in the Delphi-to-Javascript solutions?  I’ll probably check out both.  Either way I have to use a different IDE, so I’m guessing I’ll lean towards the Delphi-based solutions.  Plus, I frickin’ hate curly braces.  Winking smile

What do you guys think?

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

Flotsam and Jetsam #62

By Nick at August 22, 2012 08:36
Filed Under: Flotsam and Jetsam, Software Development, Delphi
  • Okay, so it looks like the release of Delphi XE3 is imminent.  My friend Tim Del Chiaro (the Delphi Insider) has announce the World Tour for the release.  The official page is here.  Tim also mentions something about a new product “HTML5 Builder”.  That sounds interesting.
  • JT, the Product Manager for RAD Studio, has a blog post with more info. I’ve not dabbled much in mobile development yet, so the most interesting part was “by adding memory management features such as automatic reference counting” – that’s very intriguing.  This could add a whole new dimension to the great FreeAndNil debateWinking smile
  • I’m always looking to sell stuff on ebay – so when I put in my new ASUS RT-N16 router, I thought I’d sell the old one.  Apparently, I’m not the only one doing that, as the router that Comcast gave me is worth only about 15 dollars, if that.  They are $40 at Amazon. Oh well.  Winking smile  I was hoping it was worth a bit more.  But hey, $15 is a lot of money, right?
  • I think I’ve said at least 453 times how much I love FinalBuilder.  So I’m always happy to pass along good news about what the folks at VSoft are up to.  Their latest is a very intriguing product called Continua CI, recently released in beta.  It’s a follow on to their FinalBuilder Server product.  I say “follow on” and not “upgrade” because it looks to be something quite a bit different and improved. Robert Love has a good write-up on it as well.    We here at Gateway Ticketing currently use Jenkins in concert with FinalBuilder, but if the licensing for Continua is favorable, it might be something for us to consider.  In any event, I always recommend looking at anything at all from the fine folks at vSoft Technologies.

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 -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).


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


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!


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:


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:



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.

It's That Time Again: Gateway Ticketing Needs Delphi Developers

By Nick at July 02, 2012 07:05
Filed Under: Delphi, General, Software Development

My company, Gateway Ticketing, is hiring again. We are looking for Delphi developers. Actually, having Delphi skills is great, but we are mostly interested in smart people that know what they are doing when developing high-quality software.  We love Delphi and C#, but in the end, those are just languages and we know that it doesn’t ultimately matter what tool you know, but whether you really know how to write clean code.

Here are some reasons why you should consider working for Gateway:

  • We are a great place to work.  I love it here.  That this is a great place to work was so obvious to me that I moved my whole family clear across the country to join this team. 
  • We are serious about being serious about software development.  We aren’t messing around here.  While we have a large legacy code base, we are all about doing the right thing the right way with the right tools.  We insist on unit tests for your code.  We insist that you keep up with the latest innovations in writing code.  We insist that you view coding the same way that Rembrandt viewed painting.  
  • We love Delphi, and we live and  breathe it here.  We are doing cool things like using the Delphi Spring Framework, Dependency Injection, Unit Testing, and other fun stuff.
  • We use C# and ASP.NET for our eCommerce solution and all the cool stuff that goes along with that.
  • We are located in beautiful Boyertown, Pennsylvania.  This a great place to live and raise a family.  We are close to everything (including Philadelphia) but have that great small town feel.  I love living here, and you will too.
  • Our customers are some of the greatest and most fun places on earth.  We sell systems to the largest amusement parks, zoos, water parks, and museums all over the world.  This is a cool industry.  Who doesn’t love a good amusement park?

Okay, look – everyone says they want to hire “rock-star developers”.  Shoot, even we do it.  That’s all well and good, but the bottom line is that we are setting our standards really high.  And if doing that scares people off, well so be it.  We don’t want people who are scared off by high standards.  We want people who are looking for places with high standards.  We expect and demand your very best – anything less and you should find a job writing VB6 code. ;-) We really are creating a world-class place to build software, and we want folks like you to be a part of it.  You are up for that, right?

Relocation assistance is available.

And of course, here are the obligatory caveats.  We are definitely looking for people to live and work here in the Eastern Pennsylvania/Greater Philadelphia area.  Please note: we aren’t currently considering remote workers.  Naturally, you must be eligible to work in the United States. I'm sorry but right now we cannot sponsor H1B visas. :-(  We don’t care where you are from or who your parents were or what color your dog is or anything like that.  We are really only interested in what you can do.  And of course, we want you to know what we can do for you, too.

If that sounds like something good to you, please contact me.

TVirtualInterface: A Truly Dynamic and Even Useful Example

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


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?


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
    function InterfaceToCall: T;

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

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

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);
  // Since this is a pure stub, don't do anything!

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;
  pInfo : PTypeInfo;
  pInfo := TypeInfo(T);
  if QueryInterface(GetTypeData(pInfo).Guid, Result) <> 0 then
    raise Exception.CreateFmt('Sorry, TSimpleStub<T> is unable to cast %s to its interface ', [string(pInfo.Name)]);

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)
  procedure SayHello;
  function ReverseString(aString: string): string;
  function Multiply(x, y: integer): integer;

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

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:

  MyClassUnderTest := TSprocketThatTakesAnIWhatever.Create(SimpleStub.InterfaceToCall)


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>)
    procedure AddExpectation(aCallName: string; aReturnValue: TValue);

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>)
    FActions: TDictionary<string, TValue>;
    procedure DoInvokeImpl(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue); override;
    constructor Create;
    destructor Destroy; override;
    procedure AddExpectation(aCallName: string; aReturnValue: TValue);

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);
  FActions.Add(aCallName, aReturnValue);

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);
  Result := FActions[Method.Name];

(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'));

has the following output:


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


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.

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:


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

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;
  inherited Create(TypeInfo(T), DoInvoke);

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

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>)
    procedure DoInvokeImpl(Method: TRttiMethod;  const Args: TArray<TValue>; out Result: TValue); override;

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:

  ISprocketProcessor = interface
    procedure ProcessSprockets;

  TSprocketProcessor = class(TInterfacedObject, ISprocketProcessor)
    procedure ProcessSprockets;

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)
    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;

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:

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

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

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

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:

  IGoStop = interface(IInvokable)
    procedure Go;
    procedure Stop(aInteger: integer);

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

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

the console output will look like this:



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);
  Arg: TValue;
  ArgType, ArgName: string;
  TempKind: TTypeKind;
  Write('You called the ', Method.Name, ' method ');
  if Length(Args) > 1 then
    Writeln('and it has ', Length(Args) - 1,' parameters:');
    for Arg in Args do
      TempKind := Arg.Kind;
      if TempKind <> tkInterface then
        ArgName := Arg.ToString;
        ArgType := Arg.TypeInfo.Name;
        Writeln(ArgName, ' which is of the type ', ArgType);
  end else
    Writeln(' and it has no parameters.');

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:

  IActuallyUseful = interface
    procedure SayHello;
    function ReverseString(aString: string): string;
    function Multiply(x, y: integer): integer;

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);
  if UpperCase(Method.Name) = 'SAYHELLO' then
    WriteLn('Hello World!');
  end else
    if UpperCase(Method.Name) = 'REVERSESTRING' then
      Result := ReverseString(Args[1].AsString)
    end else
      if UpperCase(Method.Name) = 'MULTIPLY' then
          Result := Args[1].AsInteger * Args[2].AsInteger;
      end else
        raise Exception.Create('Bad Parameter name was passed in to the DoInvoke method');

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.

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.