Amazon.com Widgets September 2011

Flotsam and Jetsam #45

By Nick at September 29, 2011 05: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 28, 2011 15: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. 

Introduction

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 04:54
Filed Under: Delphi, Software Development

Introduction

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;
begin
  FOrderValidator := TOrderValidator.Create;
  FOrderEntry := TOrderEntry.Create;
end;

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;
var
  Order: TOrder;
  OrderProcessor: IOrderProcessor;

  OrderValidator: IOrderValidator;
  OrderEntry: IOrderEntry;
begin
  GlobalContainer.Build;
  Order := TOrder.Create;
  try
    OrderValidator := ServiceLocator.GetService<IOrderValidator>;
    OrderEntry := ServiceLocator.GetService<IOrderEntry>;
    OrderProcessor := TOrderProcessor.Create(OrderValidator, OrderEntry);
    if OrderProcessor.ProcessOrder(Order) then
    begin
      WriteLn('Order successfully processed....');
    end;
  finally
    Order.Free;
  end;
end;

 

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:

type
  TOrderProcessor = class(TInterfacedObject, IOrderProcessor)
  private
    [Injection]
    FOrderValidator: IOrderValidator;
    FOrderEntry: IOrderEntry;
  public
    function ProcessOrder(aOrder: TOrder): Boolean;
  end;

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;
var
  OrderIsValid: Boolean;
begin
  Result := False;
  OrderIsValid := FOrderValidator.ValidateOrder(aOrder);
  if OrderIsValid then
  begin
    Result := FOrderEntry.EnterOrderIntoDatabase(aOrder);
  end;

  {$IFDEF CONSOLEAPP}
    WriteLn('Order has been processed....');
  {$ENDIF}
end;

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:

initialization
  GlobalContainer.RegisterComponent<TOrderProcessor>.Implements<IOrderProcessor>.InjectField('FOrderEntry');

 

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?

Conclusion

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 14: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 10: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 08: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 09, 2011 16: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 03: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 00: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 people that values its privileges above its principles soon loses both."    –  Dwight D. Eisenhower

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.