Widgets The Iron Triangle and Quality

The Iron Triangle and Quality

By Nick at August 16, 2011 11:28
Filed Under: Software Development

More from my Embarcadero Blog.....

Another great article called "The Iron Stool" by Jeff Atwood, and on a topic near and dear to my heart these days.

I talk a lot about quality when I’m on the road and visiting with customers.  I consider the quality of the product to be the #1 feature going forward.  When I talk about "quality", I’m talking about speed, performance, and stability all wrapped up into one thing.  I know that no matter what the feature set for a given release, if the perception is that the product lacks quality, it will not be as well received as it might otherwise have been.  You all have been very clear that quality is important, and we are taking that very seriously.

Jeff’s article talks about the classic "Iron Triangle"of Time, Resources, and Features and how they interact to limit what you can do on any given software project.  Increase one, and the other two are affected.  Decrease Time, and you get fewer features.  Increase Resources and you get more features.  It’s a constant tug and pull between the sides of the triangle.  You have to keep the triangle balanced.  You can’t pad up features without adding in more resources or more time.

Well, actually, you can, right?  You can add features to a project, without increasing time or resources.  But of course, when you do, something else has to give, and that something is quality.  Give people a fixed feature set, limited resources, and a set date to finish, and you’ll probably get the product — but at the cost of that quality of the thing delivered (assuming that the time constraint is limted, of course).

Jeff then point’s out a co-workers analogy that it can be compared to a three-legged stool.  It took me while to figure out what she meant, but I stewed on it a while until I realized that if you shorten one or two of the legs of the stool, the "quality" of your sitting experience will be less than perfect.  To maintain a good sitting experience, you have to keep all three legs balanced.

But I don’t agree entirely with that analogy, because if you expand time, (that is, increase the amount of time allotted to complete the features even with fixed resources), you’ll get more quality.  Increased time is the one thing that should almost always improve quality.

One of the commenters to the post pointed out that some people view Quality as the area of the triangle. Pull on the corner of any triangle, and it’s area will increase.  Push on it and it’s area will decrease.  But that breaks down because adding more features will not help quality – doing so just creates more things to break and less time used up to test for and fix bugs.  Adding resources or time to a project will increase it’s quality, as long as the resources are added a the beginning.  Time can be added, well, any time.  ;-)

Another way to think about it is to make the three sides be Time, Quality, and Features.    Much of the time, resources are relatively fixed. That is the way we operate here — we have a team of developers, the size of which changes only marginally.  Brooks Law states that you should be less inclined to increase a team’s size the farther along the project is.  Since resources should only be altered very early in a project, Resources are to a large degree not a variable entity in the equation.  Features and Time are variables that can be adjusted much more easily along the way.

So it’ isn’t entirely clear how the "Iron Triangle" analogy holds.  I do know this — spend more time on quality and you’ll get quality.  And that is what we plan on doing for the Highlander release.

Comments (5) -

8/16/2011 7:02:09 PM #


"I do know this — spend more time on quality and you’ll get quality.  And that is what we plan on doing for the Highlander release."

Ouch... checking the original, I see said release was still almost a year away, and even once it came, was missing features originally targetted for it. Sticking with Delphi .NET was surely the worst decision of the DTG/CodeGear years, notwithstanding the good ones - from the outside, it looked like a lot of effort was put into it for not much reward, either to DTG/CodeGear itself or paying customers. Still - bygones are bygones.

Chris United Kingdom |

8/18/2011 9:42:15 AM #


"and even once it came, was missing features originally targetted for it."

That is, of course, part of the quality process.  If a feature takes longer than you think (not an uncommon thing in software), then often the best thing to do do is not ship it.

Quality comes from all kinds of different, wise decisions.

nick United States |

8/20/2011 1:43:54 PM #


'If a feature takes longer than you think (not an uncommon thing in software), then often the best thing to do do is not ship it.'

For sure. If the .NET product was so difficult to nail down quality-wise though, then perhaps the whole thing should've have been put out of its misery well before it actually was. It took new owners to do the deed, didn't it...?

Chris United Kingdom |

8/20/2011 2:40:57 PM #

Michael Thuma

The models do not consider the time to market. This is why they are false for your.

At the times when the triangle was invented - time was (man days), resources (humans, computers...), Functionality (the requirements). Time to market was not considered, they were happy these days when something worked (70% of IT project failed these days). The focus on quality seems to be the correct choice, because today in most cases the project shows a result.

The position of quality on top is ok in case of the stool. But quality is not measurable so it cannot be the area of the triangle - none sense.

What does the triangle tell you. If you do today an SAP roll-out with 100 consultants that implement 3500 features and you want to have constant project cost and constant project duration then you must allow one parameter to change. Usual is today 2/3 of the features implemented but all business critical implemented. Some never come, that's faith, because the project organization exists outside the company and IT. -> One example.

These models do not fit to product development out of the box, if they ever did fit somewhere. What will you decide for in your company? Resources are obvious (limited), money too. So you can prioritize features and maybe overrule time to market (tactical ... with maybe a future impact on resources) with the higher goal 'quality first'. This is your triangle or quadrangle ...

Michael Thuma Austria |

8/20/2011 2:42:03 PM #

Michael Thuma

Sry. ... this is why they are false for your/our product development driven view.

Michael Thuma Austria |

Comments are closed

My Book

A Pithy Quote for You

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

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.

Month List

All posts by nick

Flotsam and Jetsam #48

By Nick at October 29, 2011 19:51
Filed Under: Delphi, Flotsam and Jetsam

Flotsam and Jetsam #47

By Nick at October 18, 2011 12:52
Filed Under: Delphi, Flotsam and Jetsam

Delphi Mocks: The Basics

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


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

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


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

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

Enter a Mocking Framework

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

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

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

An Expensive Service

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

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

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

unit uCreditCardValidator;




  ICreditCardValidator = interface(IInvokable)
    function IsCreditCardValid(aCreditCardNumber: string): Boolean;
    procedure DoNotCallThisEver;

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



{ TAdder }

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

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

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

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


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

A Class to Use the ICreditCardValidator

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

unit uCreditCardManager;



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


{ TAddingMachine }

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

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


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

Testing TCreditCardManager Can Be Expensive

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

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

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

  ReturnValue := FCCValidator.CreditCardIsValid(ValidCard);

  ReturnValue := FCCValidator.CreditCardIsValid(BadCard);

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



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

Testing with a Mock

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

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

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

  CCMock: TMock<ICreditCardValidator>;
  CCMock := TMock<ICreditCardValidator>.Create;

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

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


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

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

  FCCValidator := TCreditCardManager.Create(CCMock);

  ReturnValue := FCCValidator.CreditCardIsValid(ValidCard);

  ReturnValue := FCCValidator.CreditCardIsValid(BadCard);

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

Ensuring Code Is (or Is Not) Called

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


  // Ensure that the tests never call this.  It costs $500!!

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


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

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


I would get the following dialog:


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

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


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

Getting Giddy with Dependency Injection and Delphi Spring #7 – Controlling Construction

By Nick at October 08, 2011 21:47
Filed Under: Software Development, Delphi

As always, you can download the Delphi Spring Framework from GoogleCode.

By now you should be getting the idea about dependency injection – how you can use it to decouple your code and provide instances of your objects.  Hopefully you see the benefits of coding against interfaces and not implementations.  And if things are going really well, you are writing unit tests with ease because your code is easily tested. 

However, I bet by now some of you are thinking that this looks really cool and all, but there is just a touch too much “magic” going on – that there is a bit too much going on under the covers.

Well, you are right about that – there is a lot going on under the covers.  The Delphi Spring Framework does a lot of work for you, mainly by creating instances of classes using Run-time Type Information (RTTI).  It controls the creation, and can even let you manage the lifetime of those objects.

But I also bet that some of you are a bit uncomfortable with the notion of relying on all that magic.  While turning over that control will work in many cases, you don’t always want to give up control over the  creation of your objects. 

Well, you don’t have to.  The framework allows you to customize the way that your classes are created if you so desire.  Very often, if your classes are well designed – your constructors are simple, you aren’t doing much more than assigning values – you don’t need to do anything special when you construct an instance.  But sometimes you do.  Sometimes, your class needs to be passed something dynamic – a class whose state can only be known at runtime.    For instance, you may have a given customer, and that customer has invoices, and you have a class that you want to pass that customer to, but you also want to completely decouple that class.  Your customer is dynamic – you may be running a query and need to perform this operation on every customer in your database. Or maybe the customer is doing something on your website, and so your customer object is specific to that customer.  In any event, the customer data is dynamic at runtime, and so the creation of an object can’t be cookie-cutter.  It has to be unique each time you need an instance of this object that takes action on the given customer. 

The code below comes from the Samples directory of the Delphi Spring Framework.  It’s part of the Demo.Spring.DelegatedConstructor project

The Spring Framework lets you control the creation of your objects through a method on the TRegistration class – the class used to register types against interfaces.  As part of registering your class, you can pass an anonymous method of type TActivatorDelegate, which his declared as:

TActivatorDelegate<T: class> = reference to function: T;

The TRegistration class uses the fluent interface, so you can chain together a number of things that you want to attach to any given registration.  So, for instance, if you have a project involving a TUser class, and the TUser class is dynamic, then a class (such as TUpgradeUser) which needs a TUser, might be registered as follows:

    function: TUserProcessor
      Result := TUserProcessor.Create(GetCurrentUser);

The TUserProcessor class is registered as implementing the IUserUpgrader interface.  The lifetime of the resulting class is set to be “Transient” meaning that the implementing class will live “normally”; that is, it will be destroyed when the interface reference goes out of scope.  (Note that AsTransient is the default lifetime.  We’ll discuss container lifetime management in a future blog post). 

Finally, the actual creation of the TUserProcessor class is “delegated to” an anonymous method – a function in this case, as noted above – that simply returns an instance of the TUserProcessor class.  The key here, of course, is that the anonymous method can call the GetCurrentUser routine which will inject the current, dynamic TUser instance into the resulting object.  You can do anything you want in this anonymous method, including creating and setting up the resulting object in any manner you choose.  You could set properties and even call methods on the resulting, implementing object. 

If you examine the code for the project, you’ll note, of course, that it doesn’t actually do anything other than write to the console.  The GetCurrentUser call is merely a singleton returning the same instance of TUser.   The code is merely illustrative, and so the “background stuff” doesn’t really do anything.  In a real application, a call to GetCurrentUser would do just that, return an instance of TUser that represented the current, dynamic state of the user in question.   The critical part to note is that you can control the creation of the TUserProcessor to as large a degree as you want. 

Finally, when you actually call the ServiceLocator to grab an instance, the Container will call your anonymous method and return an instance constructed exactly like you want it to be constructed.

So in the end, the Spring Container gives you total control – if you want it – over the creation of your objects.  If you need to, you can have a little control over the “magic” that takes place and sprinkle your own little fairy dust on the construction process.

Fun Code of the Week #1

By Nick at October 06, 2011 20:20
Filed Under: Delphi, Fun Code
unit uIsPalindrome;


function IsPalindrome(const aString: string): Boolean;


     , {$IF CompilerVersion >= 230}System.{$IFEND}SysUtils

function CleanString(const aString: string): string;
  C: char;
  // Remove all non-alpha chars and make all lower case
  // Spaces don't matter, so let's count only letters
  Result := '';
  for C in LowerCase(aString) do
    if CharInSet(C, ['a'..'z', 'A'..'Z']) then
      Result := Result + C;

function IsPalindrome(const aString: string): Boolean;
  Stack: IStack<Char>;
  C: Char;
  NoSpaces: string;
  Temp: string;
  NoSpaces :=  CleanString(aString);

  Stack := TCollections.CreateStack<Char>;
  for C in NoSpaces do
  Temp := '';
    Temp := Temp + Stack.Pop;
  until Stack.Count = 0;
  Result := Temp = NoSpaces;


Added: I always enjoy posting code like this. Note that it is entitled "Fun Code", not "Highly optimized, perfectly written Code". ;-)

Flotsam and Jetsam #46

By Nick at October 05, 2011 22:58
Filed Under: Delphi, Flotsam and Jetsam
  • I will be speaking this year at CodeRage 6.  I’m giving two talks, one on Dependency Injection, and one on Unit Testing.  Please attend.  I think my talks in particular will be really good.  But maybe not as good as all the other stuff you can learn there
  • Are you aware of the fact that FireMonkey, RAD Studio, and Delphi all have spanking new pages on Facebook?  I wasn’t.  And they do.
  • Holy crap!  Allen Bauer is alive!
  • I’ve been trying to write some more example applications for the Delphi Spring Framework, and so I was researching the Factory Pattern to see if I could find a good illustration to build an example for (TFoo and TBar can only take you so far….) and I ran across a nice article on MSDN that describes it nicely.  It actually has a nice example of a “Computer Factory”, and I’ll likely riff of that to create a “real world” example of a physical object.  But the part that caught my notice, and caused me to write this entry was a quote at the beginning:  “When was the last time someone asked the designers of the Empire State building to add ten new floors at the bottom, put a pool on the top, and have all of this done before Monday morning?” And the answer, of course, is “never”.  Winking smile  Anyway, it just was another data point in my ongoing contention that software developers are not engineers. 
  • This is a pretty amazing and thorough tutorial on LiveBindings.  Live Bindings is one of those cool features that I need to learn about and that appears to be cool now, with the potential to get a lot cooler in the future.

Flotsam and Jetsam #45

By Nick at September 29, 2011 14:04
Filed Under: Flotsam and Jetsam, Delphi
  • One of the cooler – but unsung – features of Delphi XE2 is the fact that it includes an ODBC Driver for dbExpress.  Do folks realize this basically means that Delphi can now use all its cool Delphi goodness with just about any database backend?  Everyone has an ODBC driver, and so now you can connect anywhere you want with dbExpress and Delphi.  Like I said, a pretty good little feature.
  • I have just checked in a number of sample applications that illustrate how to use various features of the Delphi Spring Framework.  It is far from complete, and I will be adding more demos, writing articles about each demo, and trying to comment the code.  In addition, I’ll be working on fleshing out the documentation and the wiki that are part of the Google project as well as continuing my blog series.  This is really proving to be a lot of fun for me, and I’m glad to be able to make a contribution to the community. 
  • I asked this on Twitter and got a few responses and a little info.  Does anyone out there know what is up with the DUnit project?  It looks like Mark Edington of Embarcadero is a committer and has made some changes in the past few months, but it seems to me that given the new capabilities of Delphi (Generics, anonymous methods, attributes, etc), this project is screaming out for someone to take it to the next level.  Anyone interested?  How do we make that happen? This needs to happen.
  • More from the “You learn something new every day” category:  you can tag a unit with “experimental” and the compiler will issue a warning.   Example: unit Spring.Configuration experimental; will issue the warning [DCC Warning] Spring.Core.dpk(80): W1007 Unit 'Spring.Configuration' is experimental Haven’t seen that one before, I must confess.
  • Roman Kassebaum is at it again.  He’s updated the Orpheus project on SourceForge to work with Delphi XE2 and XE2/64-bit. Very cool. And while he was at it, he’s updated the PowerPDF project as well.  Thanks Roman.

Revenue Recognition and the Software Development Industry

By Nick at September 29, 2011 00:10
Filed Under: Delphi, General, Software Development, TechBiz

Before I start, I want to stress that I am not a lawyer.  I am not an accountant.  You’d be a total fool to base any business or legal decisions on anything I write here.  Consult a an attorney or a fully accredited CPA or some other person who truly knows what he’s talking about before deciding how to make any decisions whatsoever about anything having to do with money, the law, revenue, etc.  I don’t know anything, and if you listen to me, you are making a big mistake. 


Developers and other people involved in the software business have heard a lot about “Sarbannes-Oxley” (SOX) and “revenue recognition” and how it effects what Embarcadero can and cannot do with respect to updates, upsells, promotions, and all kinds of issues surrounding selling and releasing Delphi.  SOX was a significant, game-changing piece of legislation here in the US, and it affects virtually every public company in the country.  It also affects private companies that might someday want to be a public company.  It affects software companies in particular, because software is not a physical good in reality, but “acts” like one in the marketplace. 

When I was at Borland/CodeGear/Embarcadero, it took me a while to come to grips with what SOX meant and how it altered our business and what we wanted to do.  Frankly, I found it all very frustrating.  On the face of it, the rules and limitations seemed ridiculous. At first I complained bitterly about it.  It took a while, but finally I came to accept them and realize that SOX and the ensuing rules were the “field we had to play on”.  Finally, I think I actually gained enough insight into it that I was able to come to grips with the new rules and understand why things work the way they do.  As a result, I thought I’d share a bit of that with you fine people.

What is Revenue Recognition?

First, it might be obvious, but let’s be sure we know what the term “revenue recognition” means.  Revenue recognition is the process by which a business says “Yep, we actually earned that revenue”.  Note, it most decidedly does not mean “We got the cash”.  In an accrual accounting system – common to businesses of almost any size – the receipt of cash can actually go down as a liability. Think of taking an advanced payment for services: If you take half the money up front for a job, you have it in the bank, but you still owe the services. Revenue can’t be “recognized” until you do in fact deliver that good or service for the money you’ve received.  So if you are a software company, you can recognize revenue only when the software you sell is actually delivered. But software is a strange product in this regard, as we’ll see. As a result, The rules for  revenue recognition for software are somewhat cloudy and definitely untested in a court of law.

Why it Became an Issue

When it comes to software, one of the main roots of the revenue recognition rules stem from the (previously) common practice of "pumping the channel".  Near the end of the quarter, firms would "sell" lots of stuff to their channel partners.  For example, lets say that there was a software company called TrollWare.  Selling for a given business quarter started looking a little thin, so TrollWare would "sell" $1,000,000 of product to their favorite online/catalog retailer.  (And remember, this was actual, physical boxes back in the day.)  Then, they'd claim $1,000,000 of revenue on their books.  Wall Street, creditors, and anyone else interested in a company's revenue would think "Hmmm -- that's $1,000,000 in revenue more than we thought!  Buy TrollWare stock!” Obviously, this wasn’t a real sale, and could actually end up being a net cost because of the need to actually ship (and maybe even actually destroy) physical boxes of software.  This was a common practice throughout the industry, and many companies that we have all heard of did this.

Of course, most often, TrollWare would only really sell, say, $100,000 of all of that "shipped" software by the end of the month and have to buy back $900,000 of it at some point, but hey, revenue is revenue!  Clearly this is not a practice laced with clarity, openness, and integrity with respect to people looking at the viability of Trollware.

New, Tougher Rules

This kind of thing was one of many reasons that prompted passing of SOX.  The results of SOX are varied, but the results of interest to us software developers were new Generally Accepted Accounting Principles (GAAP) rules for software companies that defined revenue as truly delivering something to the customer.  Now, for a hot dog company, it's pretty clear when a box of hot dogs has been fully manufactured and when that box has left the warehouse on the way to a consumer or a business, or whomever is the "end user" of those hot dogs.  For example, if you are a rake manufacturer and sell rakes to Home Depot, you can claim the revenue when the delivery truck leaves your loading dock heading to that big orange building.  Retailers of rakes like Home Depot can claim the revenue when the rake is scanned across the Point of Sale on its way to clear someone’s lawn.  In the first case, Home Depot is the "end user" and in the second case, the guy with the leaves on his lawn is.

But then the question becomes:  What does it mean to "deliver a completed software product to the end user"?  Well, that's tricky.  There are two things here, of course.  First, when is the product really “completely produced and manufactured”.  Is a beta good enough?  What if a promised feature isn’t quite finished? How about a feature that was promised but isn’t there at all? Second --  assuming that you can define the first item -- when is that completed software product actually delivered? Who *really* is the end user?  As it turns out, it’s not quite analogous to the rake manufacturer/Home Depot relationship described above.  Because software companies were actually fairly guilty of the dubious “channel pumping” practices described above, the rules about what constitutes “final delivery” of software are fairly restrictive, and certainly different than those dictating gardening tools.

There is a lot of accounting literature about this (I’m not thrilled about the fact that I've read a lot of it.  It’s not exactly scintillating).  For instance, do a Google search on “revenue recognition software licenses”  and start reading.   The rules are pretty complicated and hard to qualify exactly. And further complicating things, no software company has yet been brave enough to test these rules in court, so they are even murkier as companies work hard to stay well away from the borders of where the rules end and a call from the US Department of Justice starts. 

Thus, software revenue can only be recognized when said software is fully and completely delivered to the end user.  For a "normal" sale like most of us think of it, revenue can be recognized when the end user has the ability to install the software -- a license is delivered and the user installs it.  (For physical software, it's still the truck leaving the loading dock to the actual end user  and not merely the reseller). 

There's a catch, though:  It has to be the complete, finished package.  As mentioned above, revenue can only be recognized when a completed product is delivered.   If you deliver a "preview" of your product or even a feature of your product, this can imply a commitment to deliver something at a later date.  If you even implicitly promise that the purchase today will result in a delivery later, then that probably means you can't recognize revenue until that implicit promise is met.  Again, I say “probably” because this is turning out to be the common interpretation of the rules in a world where no one wants to test this in court.  This is a unique problem for software because no one normally buys a “preview lawn mower” with the promise of more functionality later.

An Example

So, for example: Troll Software delivers a Trollware 1.0 in mid-February.  Their spell checker isn't really quite ready, but they need to ship because their main competitor has already shipped a version with a spell checker. Or maybe the need to get some Q1 revenue to keep from not making any money and having to to massive layoffs is a driving factor in the decision.  So they ship the product with the label "Spell Checker!!! (Preview only)”.   Then, a week into April, they deliver their fully ready Spell Checker to all existing purchasers and update their downloadable ZIP file.

They sell $1,000,000 worth of Trollware by March 31, and think "Yay! We have $1,000,000 in revenue in Q1! Wall Street will love us!"

Oops, not really:  They actually have $0 of revenue in Q1 from Trollware.  That’s right:  $0 in revenue. All of those sales become Q2 revenue, because they didn't actually complete the delivery of any Trollware versions in Q1, but instead in Q2.(This brings about the interesting situation where a company can have $1,000,000 in the bank and $0 of revenue on 31 March for Q1).

Another example:  Say you are a Trollware subscriber, and sent them $1200 a year as part of your subscription, receiving updates, improvements, and new features during the term of the subscription.  Troll Software can only recognize $100 a month for the 12 month term of the subscription.  And consider this:  What iff Troll Software wanted to move exclusively to subscription model starting the first of the year?  They might have the same number of customers buying, but now their revenue for the first month would immediately be 1/12 of what it normally is, despite having a lot of money in the bank as noted above. 

Bug fixes to existing functionality is actually excluded from this -- this is why you normally don't see new features in bug fix updates.

The same might go for "Special offers to registered users".  Say they sell a bunch of Trollware in the first half of the year.  Starting July 1, they say "Free Grammar Checker to anyone that buys Trollware 1.0!" and in the small print it says "... and if you already have Trollware 1.0, you can have the Grammar Checker, too".

Well, now, if this is the case, have you actually delivered the software to the buyers who purchased before the special offer?

That's why I said "might".  As I understand it, this particular issue isn't exactly clear and hasn't been tested in court as far as I know.  And of course, no one wants to be the test case for the SEC or the Department of Justice.  So in the end, it seems that no one is willing to risk such a deal.

Revenue is King

And of course revenue is everything in business and finance, because it represents the value that you have actually delivered to customers.  Revenue is the only real way to measure the accomplishment of a company.  And that's fair if you think about it -- that is where Enron is a great example.  They weren't actually delivering anything to end customers, but still racking up revenues like crazy.  So in the end, measuring accurately what is really, no kidding delivered to end users is what finance people are interested in knowing.

Sarbannes-Oxley was sort of the root of this.  One of its main features was to actually hold the corporate officers of public companies criminally liable for their GAAP compliance.  The threat of prison time has a tendency to focus the senses.  As a side result of SOX, the definition of revenue recognition – and more importantly the desire to strictly follow that definition -- really became an issue, and the need to know a companies real revenue was one of the main fallouts.  CEO’s wanted to be 100% sure that they were recognizing revenue correctly because, well, they don’t want to go to jail.  Now, there is a lot not to like in SOX, and I personally would like to see it repealed, but the end result being that software company CEOs became far more focused on correctly recognizing software revenue.  It's still a bit unclear, and the software industry is still very wary of all of it, because it is untested in court, and as I said, no one wants to draw the attention of the US Government on the matter. 

In the end…

Every public company that produces or sells software has to follow the rules set up by SOX.   Any business that wants to get a loan from a bank or otherwise interact in the general community of businesses needs to follow GAAP.  It's not always  fun, but that is the way it works.  These revenue recognition rules can result in companies having to do some strange things and, more importantly, not being able to do things that they might want to do and which might even make good sense.  But in the end, all organizations in the software business have to follow these rules. 

However, in the end, I have no problem with their being clear, concise rules about what "revenue" really means.  Really, I think it is hard to disagree.  Revenue is a measure of actual, delivered value, and thus a measure of the real value provided by a corporation.  That's something that is really good to know.

Getting Giddy with Dependency Injection and Delphi Spring #6 – Don’t even have a constructor

By Nick at September 24, 2011 13:54
Filed Under: Delphi, Software Development


Article Four in the series had a couple of rules to follow, one of which was “Keep Constructors Simple”.  In the last article we saw how you can use the Spring Container to hold interfaces with specific implementations so that you don’t have to create anything, but instead ask the container for an instance of an interface. 

Well, in this article, I’m going to go a step beyond even that, and show you how the Delphi Spring Framework can make it so that you don’t even need to have a constructor by automatically injecting implementation instances when they are needed without you having to do a thing. 

A Side Note

In the previous article, I had you create a unit called uServiceLocator.pas that provided a central location for registering and resolving interface implementations. Since then, the Spring codebase has changed to provide a similar functionality.  The Spring.Services unit contains a singleton function ServiceLocator that is used for getting services (and indeed the call has changed from Resolve to GetService).  The Spring.Container unit contains a similar function GlobalContainer that is used to register the interface/implementation combinations.  All items registered into GlobalContainer are available for retrieval via ServiceLocator

A Little Review

One of the common things that happen in a constructor is the creation of other needed things.  In the past few articles, we’ve talked about the need to reduce dependencies by not creating things you need but instead asking for them in your constructor.  The reason that you don’t want to do much at all in a constructor – why you want to pass stuff in to it instead of actually creating things – is to limit what happens when you do create objects.  Consider this code:

constructor TOrderProcessor.Create;
  FOrderValidator := TOrderValidator.Create;
  FOrderEntry := TOrderEntry.Create;

This code looks pretty normal – you are creating some instances of classes you need to process an order.  But there are a couple of problems here that need to be avoided:

  • You are stuck with TOrderValidator.  That’s the only class that TOrderProcessor can use.  You can’t choose to use a different class or implementation.  That’s it. Same for TOrderEntry.
  • Not only are you stuck, but you are coupled to it.  If TOrderValidator changes in ways that you don’t like, you might never know.  Because you are using the unit that it is declared in, you might get careless and start calling other stuff in that unit.  Pretty soon and before you know it, your code is hopelessly joined to those other classes in ways that  may make it difficult or impossible to disentangle.  And being tangled up with another class is bad.
  • There is no way of knowing what a TOrderValidator does, creates, or otherwise allocates.  It could be in and of itself creating thirteen other classes, allocating huge blocks of memory, accessing a database or even firing up a nuclear weapon.  Who knows?  The downstream effects of merely creating TOrderProcessor class can be pretty much something out of your control  And it could change as other parts of the code is worked on by other team members. 
  • Along those same lines, you don’t know what will be left around after you use these classes. They might write records to a production database. TOrderValidator might go off and incur a charge of $0.50 at your credit card validating company.  (Imagine your boss getting that bill after you run your unit tests with this code a couple of thousand times….)  In the end, you are tightly coupled to those classes.  That is bad.

So we could use the Spring Container to have it so that we don’t even have to call Create on the helper classes:

procedure DoOrderProcessing;
  Order: TOrder;
  OrderProcessor: IOrderProcessor;

  OrderValidator: IOrderValidator;
  OrderEntry: IOrderEntry;
  Order := TOrder.Create;
    OrderValidator := ServiceLocator.GetService<IOrderValidator>;
    OrderEntry := ServiceLocator.GetService<IOrderEntry>;
    OrderProcessor := TOrderProcessor.Create(OrderValidator, OrderEntry);
    if OrderProcessor.ProcessOrder(Order) then
      WriteLn('Order successfully processed....');


Note that we are still calling Create on the TOrderProcessor itself, but we’ll show how to tell the Container exactly how to create our class in the next article.

So in this way, we are able to completely decouple the classes from each other, and we are able to ask the container for implementations.  Thus, if we wanted to, say, implement mock objects for these interfaces, we could easily do this by simply choosing to register mock classes against those interfaces instead of “real” classes.

Never Call Create

But  if we have to have to be really careful about not doing too much stuff in a constructor, how about just not having a constructor at all?  How about if we had a way of initializing everything that needs initializing while merely relying on the default constructor from TObject?  Impossible you say?  To that I say – bah!  Let’s do it! 

I should note that often a class’s constructor will require other assignments to integers, strings, and other non-class types.  That will, of course, require a constructor, but the point here is to illustrate that you can decouple your classes so much that you don’t even have to create them.

Getting Rid of the Constructor with Field Injection

Field injection is the solution for getting rid of constructors altogether.  Field Injection is the ability to inject the implementation of a dependent class directly to a field reference without actually calling Create manually.  The Delphi Spring Framework provides two ways for doing field injection.

Consider the following class declaration:

  TOrderProcessor = class(TInterfacedObject, IOrderProcessor)
    FOrderValidator: IOrderValidator;
    FOrderEntry: IOrderEntry;
    function ProcessOrder(aOrder: TOrder): Boolean;

Note first that the class has no constructor.  It still contains references to the two internal interfaces that we saw above, but there is no formal constructor.  The second thing to note, of course, is the [Injection] attribute.  This is the key here.  This attribute tells the Spring Framework – “When you first encounter this identifier, go to the Container and grab the implementation for that interface and assign it. “ Basically, it tells Spring to do everything for you, including creating an instance of the implementing class for the interface. 

Thus, for our TOrderProcessor class, we can have no constructor, but freely use the interfaces declared as private fields:

function TOrderProcessor.ProcessOrder(aOrder: TOrder): Boolean;
  OrderIsValid: Boolean;
  Result := False;
  OrderIsValid := FOrderValidator.ValidateOrder(aOrder);
  if OrderIsValid then
    Result := FOrderEntry.EnterOrderIntoDatabase(aOrder);

    WriteLn('Order has been processed....');

The above code will run just fine, despite the fact that at no time does the code itself ever explicitly create a class for the interfaces. 

But wait, you say – what about FOrderEntry?  It doesn’t have the [Injection] attribute.  You are right.  Instead, we do field injection directly as part of the interface/class registration process.  In the initialization section of the declaring unit, the registration looks like this:



At the very end, you’ll notice that there is a call to InjectField(‘FOrderEntry"’); which tells Spring the same thing that the [Injection] attribute does.  In fact, the [Injection] attribute actually invokes the very same code to ensure that the reference is correctly assigned.  (You can see the whole unit here in BitBucket).

So there, we did it:  We created a useful class that uses two other classes and we didn’t create anything and we didn’t couple anything to anybody.  Pretty nice, huh?


Okay, so now we are able to write classes that is so decoupled from each other that they don’t even have to create instances for use!  We used Field Injection to automatically get references to objects that implement our interfaces without doing anything at all.  These classes are so decoupled that you don’t even have to include the units that implement the classes in any uses clause other than your application’s *.DPR file.  And as we said at the start, “Decoupling is good and coupling is bad”.  (If I didn’t say that, I should have, right?) 

Flotsam and Jetsam #44

By Nick at September 21, 2011 23:58
Filed Under: Flotsam and Jetsam, Delphi
  • If you haven’t figured it out, I’m all cuckoo for the Delphi Spring Framework.  Some folks were worried that the project was stagnating, though it hadn’t been that long since it had been changed.  Well, at least until yesterday, when a big set of changes were made with the idea of heading towards a 1.0 release.  There were quite a few fundamental changes, with some things formerly marked experimental moving to the “ready to go” stage, and a few new things (like the Logging units) being added and marked experimental.  And if you look really closely, you’ll even notice some small changes by yours truly.  There are some really cool things going on in this framework, and I highly recommend giving it a look.  I’ll be writing more articles here on the blog, and trying to update the documentation, FAQs, and other stuff as part of the project.  I also have some demo applications that I’ll be commenting and adding to the project.
  • I still see people trying to obfuscate their email address online. You know, doing things like “Email me at nick at nickhodges dot com” or something like that.  I personally have given up doing anything like this, figuring that spammers will eventually get any email address I have, and that it’s pointless to try to avoid it.  Spam Filters have gotten pretty good, and I only see a few spam messages a day.  And I’m not one of those guys that freaks out at the site of a single unsolicited email, preferring instead to take the 0.0023 seconds it takes to click the delete button.
  • Jacob Thurman is at it again – this time updating his very cool and powerful IDE enhancement Castalia to work with Delphi XE2.  I’ve always admired what Jacob does, and I think you should, too.  I mean, how can you not love a product that has a bullet point that says “Enhanced: Rewritten “Eliminate With” refactoring is more reliable”.  I mean, “Eliminate With”?  Is there a cooler refactoring anywhere?
  • From the “You learn something new every day” category:  I didn’t realize that Delphi doesn’t generate RTTI for enumerations that have assigned values (i.e.  type TMyEnum = (Five= 5, Six = 6);
  • One of the new features in Delphi XE2 is the ability to style your VCL apps.  The product ships with a bunch of styles, and provides a style designer that lets you build your own styles.  Well, it didn’t take long for Rodrigo to get to work and build a bunch of styles that you can use.  You can download his styles, and then put the *.VSF files in your style directory.  On my machine (I install to the default location) that directory is:  C:\Users\Public\Documents\RAD Studio\9.0\Styles\.  He’s put together a really nice looking set of styles. Thanks, Rodrigo!

Gateway Ticketing Needs Developers

By Nick at September 12, 2011 19:05
Filed Under: Delphi, General, Software Development

My company, Gateway Ticketing, is hiring. Things are going really well, and we need to expand what we are doing. We are looking for developers -- Delphi developers specifically, 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.

We also need Automated Test Engineers who want to help enhance our products  to be the highest quality software in the business.

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 are not messing around here.
  • We love Delphi, and we live and  breathe it here.  We are doing cool things like using the Delphi Spring Framework 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 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 VB 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.  We aren’t currently considering remote workers.  Naturally, you must be eligible to work in the United States We can 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.

Flotsam and Jetsam #43

By Nick at September 12, 2011 17:15
Filed Under: Flotsam and Jetsam, Delphi
  • Is your currency the Euro?  Well, now you can buy your RAD Studio from the inestimable and indefatigable Dr. Bob.  Bob has expanded his reach of dedication to the product and the customer to the entire Eurozone.
  • You guys know that I don’t think that Simon Stuart is really human.  Instead, I think he is some kind of android, sent here from the future to code something (in Delphi) that we need to save the world, and he's just biding his time writing things for us in the Delphi community.   Simon has produced a prodigious amount of cool stuff for us Delphi developers, and is a tireless community member.   It doesn’t seem like too much to ask to help him release Lua4Delphi before Christmas.  I made a modest donation.
  • We homeschool our kids, and my wife came to me showing me the stuff for the starting school year.  It presented an interesting choice:  All things being equal, should our kids spend their time learning to write cursive, or to touch type?  I voted for touch typing.  It occurred to me that I can’t remember the last time I wrote anything more than a note on a ToDo list. I almost never write letters or anything involving using a pen or a pencil for extended periods.  And even when I do, I don’t write in cursive.  But I’ll tell you what – I type A LOT.  (I’m doing it right now!)  Anyway, I guess we’ll have to put cursive writing up there with reading the newspaper.  I mean who does that anymore?  Winking smile I realize that we could do both, but that would mean giving up something else, and I see the two as similar enough that we should choose between the two. 
  • The TIOBE Index is out for September, and Delphi comes in a #13 with three down arrows.  Interestingly, though, if you put "Delphi" and "Pascal" together, they are in the Top 10.
  • Embarrassed that I Didn’t Know it was There Class of the Week: TAggregatedObject – very cool little class

Limiting Scope

By Nick at September 10, 2011 01:02
Filed Under: Software Development, Delphi

As a general rule, developers should limit the scope of variables as much as possible.   Keeping the notion of limiting scope in every way possible, from the big things (never, ever, ever use global variables)to the subtle little things a language can do (declare const parameters whenever possible) all can contribute to clean, easy to test code. 

Limiting scope has all kind of benefits.  First, limiting scope of a variable reduces the number of places that a given variable can be modified.  The reason we rightfully abhor global variables is there is no telling where or when a given variable might be changed.  A global variable hangs out there like that last donut in the break room.  You know you shouldn’t touch it, but oh my, it’s so tempting, and it’s so easy to just grab that variable and use it for whatever you need to do.  Limiting the scope of a changeable thing reduces the chances that it will be changed in a way that it shouldn’t be, or worse – in a way that you don’t even know about. 

Limiting scope is also, by definition, a main feature of object oriented programming.  Encapsulation is probably the first thing you thing of when you thing of OOP, and it’s basic purpose – it’s whole reason for existing, really – is to formalize the process of limiting scope.  They don’t call it “information hiding” for nothing.    The term “information hiding” really means “Hide the scope of your variables so much that they can’t be changed except in the exact way you let them be”.  Encapsulation enables you to ensure that data you don’t want exposed isn’t exposed.  And if it isn’t exposed, it can’t be changed.

Limiting scope also limits the ability for people to depend on code that they shouldn’t be depending on.  Loose coupling – the limiting of the dependencies with in a system – is a good thing.  Tight coupling is a bad thing.  Limiting scope makes it harder for one class to latch on to another class and create dependencies that make code hard to test and hard to maintain.  It also makes it harder for changes in one area of code to have secondary effects in other, coupled areas.  There is nothing worse than changing code in (metaphorically speaking) New York City, and having that change cause a bug in code all the way over in Los Angeles.  (This is commonly called “Action at a Distance” and is something that should be avoided like a bad burrito.)  

There are big, well known ways of limiting scope – objects, making a variable local to a method, etc. – but there are a lot of smaller, more subtle ways to limit scope as well.  I’ve tried to list a number of ways that you can limit scope in your Delphi code:

  1. No global variables.  None.  Zero.  -- This one isn’t so subtle, but it’s really, really important.  It’s really easy to make sure that you never ever declare a variable as global.  In Delphi, you can do it, but you never should.  In languages like C# and Java, you actually can’t, strictly speaking, declare a global variable – everything has to be in a class -- but you can create a field on your main class that is pretty much the same thing.  Delphi is more flexible and will let you declare a global variable.  But just because you can doesn’t mean you should.  So don’t.
  2. Don’t create anything. Instead, ask for what you need.  This topic is a big one unto itself and gets into the question of dependencies and dependency injection.   But if you try to never actually create anything in the constructor of your class and instead, pass the constructor existing instances of what it needs, you can limit the scope of a given class.  Better yet, if you use a full blown dependency injection container, you can very severely limit the scope of your classes and still benefit fully from their functionality. 
  3. Put everything you can in the implementation section of your units.  The implementation section is the friend of a Delphi developer trying to limit scope.  Things in an implementation section can’t be seen outside the unit. If you can put a unit name in the implementation uses clause, do it.  If you can declare a class definition in the implementation section, do it.   Putting something in the implementation section of  a unit ensures that it scope doesn’t expand beyond that implementation section. 
  4. If a variable can be local to a routine, do it. This goes along with “No global variables ever”, but it needs to be said. If you can declare a variable in the scope of a single method, do it. 
  5. Use constants whenever possible.   If you are never going to change the value you assign to a variable, why make it a variable at all?  Get in the habit of making something a constant, and then only making it a variable if it needs to be.  Do this even inside your methods. 
  6. If you can declare a parameter as const, do it.  A const parameter can’t be changed, and thus declaring it as such means you are limiting its scope. 
  7. If you can make a variable private, do it.  If you can’t, make it protected. If you can’t do that, make it public.  Only make something published if it has a very specific reason to be.  This one is a little trickier, because there are OOP principles to be considered.  But generally, make field variables private, and give access to them through protected members.  This way, while the data can be changed,  the actual storage device itself is not directly accessible.  In addition, you can control the ability to change the internal data through a setter method.
  8. Provide notification systems in your setters to monitor changing data.  Sometimes, you might have data that needs to be changeable, but is sensitive for some reason.  As as result, you want to perhaps monitor and maybe even prevent the changing of your internal data.  You can use something as simple as an event in the setter method, or something more robust and flexible as the Observer pattern. 
  9. Don’t reach into another class.  Or even better, don’t create classes into which someone else can reach.  This gets into the Law of Demeter, which I’ve discussed before

That’s just a list I came up with this week while working on this post and thinking about this topic.  What are other little methods and techniques that you all use to limit the scope of your variables?

How Nice of Them to put an Extra Teabag in the Box!

By Nick at September 03, 2011 12:59
Filed Under: Personal, General

Anyone who knows me knows that I am, well, pretty much of a knucklehead.  And this little story just proves it once again.

So I drink a lot of ice tea.  And absurd amount, really.  Lots and lots of it.  A gallon a day kind of a lot.  And  naturally I have one of those simple, cheap, yet hopelessly useful ice tea makers.  I then buy boxes of Luzianne Tea in the “Ice Tea Bag” size.  Each of these boxes has 24 bags in it – says so right on the box --  and I use three of these bags every time I brew up a batch of that  magic elixir.  So that is eight batches per box, with no teabags left over, right?

But no, it’s not that simple.  I always end up with *one bag left over* when I get to the last batch.  Every time!  Huh?  I stand there and ponder it -- “Is this like a ‘Baker’s Dozen’ thing going on here with my tea bags?”

And then I take this mysterious “extra” bag, grab two out of the new box, and make the next batch.  And in a week, I’m wondering again.

See, I told you I’m a knucklehead.

Flotsam and Jetsam #42

By Nick at September 03, 2011 09:02
Filed Under: Delphi, Flotsam and Jetsam
  • Interesting Delphi XE2 Item of the Week:  TComponent now implements the Observer pattern. 
  • Very Cool Video of My Friends and Former Co-Workers of the Week: FireMonkey Developers Speak I have to say that:
  • I have fleshed out my Embarcadero Blog Content page that includes links to the two main series of articles that I wrote on my Embarcadero blog.  I still have some formatting to do, but the content should be all there.  I’m trying to grab all the content I can from my old Embarcadero blog, as they need to shut it down for legal reasons (as I understand….).  If you can think of anything I did there worth keeping (that might be be  hard, I know….. Smile) let me know.
  • "It is always painless to depend on interfaces."
  • Hey, I take my position as an Admin at the Delphi UserVoice page seriously, and I’ve been a bit busy.  The XE2 release has made things a little more fun there…
    • I just marked as "Completed" over 3800 votes on Delphi's UserVoice page. Not bad for a day's work.  And not bad by Embarcadero in delivering all that asked for functionality.
    • Now, with all those votes freed up, the most requested item is Better GUI separation and abstraction.  Is that really the thing that the community wants most?
    • I closed a bunch of “laundry list” items that would be impossible to close.  They were things like “Make the IDE Better” with a list of seven things they wanted to see.  How could you ever really close that as “Done”?  I encouraged the posters to create new requests for each individual request instead.
    • I’d recommend all you fine people go there and enter your requests as well as peruse the list and cast your votes.
  • I’ve been trying to build things with my son, and  being a boy, he likes weapons and destruction.  We started with a trebuchet.  I think it will likely be a while before we work our way up to this, but hey, we can dream. 

My Book

A Pithy Quote for You

"A man's got to know his limitations"    –  Dirty Harry Callahan

Amazon Gift Cards

General Disclaimer

The views I express here are entirely my own and not necessarily those of any other rational person or organization.  However, I strongly recommend that you agree with pretty much everything I say because, well, I'm right.  Most of the time. Except when I'm not, in which case, you shouldn't agree with me.

Month List