Amazon.com Widgets Nick Hodges | A man's got to know his limitations

Flotsam and Jetsam #56

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

On the Proper Design of Exception Hierarchies

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

Introduction

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

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

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

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

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

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

The Basics

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

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

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

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

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

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

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

Flat and Wide

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

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

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

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

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

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

An Example

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

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

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

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

image

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

Lots and Lots of Exception Types

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

Conclusion

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

My Amazon Kindle So Far

By Nick at February 12, 2012 06:59
Filed Under: General, Tech Stuff, TechBiz

A while back I wrote about why I got my Amazon Kindle Fire, and in that post I promised you that I’d write about my thoughts about owning the Kindle.  And since I’d rather rub shredded fiberglass in my eyes than break a promise to you fine people, here are my thoughts on owning an Amazon Kindle

  • First, I want to say that I also am an Amazon Prime customer, so what I talk about below may include benefits of being in Amazon Prime.  Those benefits are actually quite numerous considering the $79 annual price tag.  If you are at all involved with Amazon, I’d give the Prime membership a good look.   You can save a lot of postage – and a lot of time and gas – with Amazon Prime.  “Gas, you say? How?”  Well, I’m glad you asked.  Here’s an example:  I don’t drive to the Pet Store anymore, because I just have Amazon ship me – at no charge and with no sales tax – my dog food.  And cat food .  And that is just the beginning of what Prime offers.  I’ll leave it now to say that it’s a pathetically good deal if you have even the remotest notion of buying things from Amazon, and point out some more specific things as I go along.
  • The second point to make is that at $200, the Kindle Fire is pretty much a loss leader for Amazon.  I don’t know for sure what it costs to make the Kindle Fire, but I’m guessing that Amazon is selling them at a loss or very close to it.  And the reason is that the Fire is, in Amazon’s eyes, merely an Amazon content delivery device.  They want to get this device – a Kindle – into your hands. At $200, it’s an attractive tablet that runs Android apps, had a dual core processor, a color screen and has all the advantages of a Kindle.  Sure, any tablet can run Kindle software, but as a Kindle, I  can do things like borrow a free book a month from the Kindle Owners' Lending Library (another Prime perk….) as well as watch Amazon Video (another Prime benefit…) on the device.  I can store all my Kindle content (another Prime benefit….) with unlimited space on the cloud, including magazines, books, and music. 
  • The Kindle Fire is pretty impressive hardware. It is a dual core processor, and a very nice seven inch IPS screen. I haven’t really ever thought that it was slow because of processor power. It seems plenty powerful to me.
  • Things I like to do with a tablet (and that don’t really matter that it’s a Kindle Fire….)
    • Read Twitter.  I’ve taken twitter off my phone because now I can….
    • …actually read the web article on a link from Twitter instead of putting it in Instapaper because my phone makes it too hard to read the link. 
    • Watch movies and TV in bed with a nice, crisp seven inch screen. The Fire is really easy to hold however I like.
    • Play games. The screen is big enough to actually see the cool graphics on some cool games. I’ve taken all games off my phone, and the Fire has become a nice little tool for wasting some time.
  • Things I like to do with my Kindle fire (because it is a Kindle…)

Miscellanea:

  • Nice: One thing I like is the “Lock screen” feature which locks in screen orientation.  Sometimes you want to lie on your side and still read in portrait mode even though you are holding the device in landscape mode.  I like that. I suppose that  other tablets have that – I don’t know – but I do like it’s easy access.
  • Nice: Amazon's Android AppStore gives away a paid app every day.  Mostly it is cheesy games, but every once and a while you can get a nice paid app.  While not the Android Market, you can get many of the apps you want from the Amazon AppStore, including things like NetFlix, Pandora, Evernote, etc. 
  • No Google apps, though.  I guess I’m not 100% clear while Amazon blocks Google apps. I guess they view them as a competitor. I sure would like to be able to run Google Mail and Google Calendar on it. I also prefer Google Music, but Amazon’s music is workable. It is a bummer not to have the Google/Tablet connection.
  • To add insult to injury regarding the above note, there really isn’t even a decent third-party calendar app in Amazon’s store. Alas.
  • Bummer: The device has no camera, no microphone,  and no GPS.  This is okay, because the GPS on my phone works much better when I’m driving.  The camera on my phone is as good as any they’d put on the tablet.  I pretty much have my phone with me all the time, so those missing features in the Fire aren’t a problem. 
  • Bummer:  The Kindle Fire runs Android, but it is a very customized and restricted version of Android.  As a result, the device has no Google apps, including no access to the Google Market.    However, if you want, you can root it (though if you do, you lose the ability to watch free Amazon Prime videos).  You can then sideload the Google apps.   You can sideload apps without root access, but it is a bit of a crap shoot whether any given app will work.  (Here’s a good open letter to Jeff Bezos on this topic, the general sentiment of which I support.  I don’t’ regret my Kindle purchase, but it would be a really, really awesome tool if I had the Google stuff on it.)
  • A Bit Strange: There is only one physical button on the whole device:  the power switch on the bottom.  This means no volume rockers, which Android users are kind of used to, I guess.  It hasn’t bothered me too much, but I know that it is something that bothers other users.
  • Bummer:  Amazon advertises their custom Android Silk browser as “lightening fast”, but my experience has been, uhm, different.
  • Nice to Know: I have kept my device “Kindle-ized”, but if I wanted to, there are Android ROM’s available for the Kindle Fire if I wanted to move the device to be a “pure” tablet.  But again, I’d lose the advantages in Amazon Prime of the device being a Kindle.

Final verdict:  I’m happy with my Kindle Fire – I like using and having a tablet – but I’m going to save up an buy a “real” tablet in the fall.  I’m interested in the Google Nexus Tablet – or at least in concept.  I like having a Nexus phone, and I’d like to have the same thing in a tablet.

Flotsam and Jetsam #55

By Nick at February 08, 2012 18:02
Filed Under: Flotsam and Jetsam, Delphi
  • Marco notes that Embarcadero has put out a press release announcing a 54% increase in revenue in 2011 over 2010.  This is unequivocal, clear, unassailable good news.  No amount of Chicken Little whining will take away from the fact that this is very, very good news.  (It didn’t take long for Marco’s commenters and the Nattering Nabobs of Negativity in the non-tech newsgroups to try to find a way to make this something other than great news.)  The most important thing that the EMBT Executives care about is the bottom line – and that is how it should be.  And the bottom line for Delphi apparently looks pretty darn good – good enough for them to brag about it.  When the bottom line of Delphi looks good, that is good for Delphi developers. 
  • Hey, I noticed that I’ve gone over 1000 comments here on my blog (actually it’s more like 3000  if you count spam that I’ve deleted.….).  Thanks to everyone who posts comments.  I appreciate you reading this stuff I write, especially when you go to the trouble of writing something up and adding to the conversation.  Lately some of the discussions on my technical posts have been really good – I’m grateful.
  • I am not myself able to go this year, but I’m quite happy that three of my team here at Gateway Ticketing will be attending Delphi Developer Days this April in Baltimore/Washington, DC.  I was there last year, and I can tell you that it was a really valuable experience, and I recommend that you attend this year if you can.
  • Jason Southwell’s ApeSuite for FireMonkey has a new beta out with a bunch of new features.
  • More FireMonkey components are now coming from TMS Software as well – they have a cool set of instrumentation components as well as a TableView control that will be popular for folks writing mobile apps in particular.
  • And Even More FireMonkey: As previously noted, I haven’t played with FireMonkey  much, but I have to confess, it is cool to think that this demo app – as described by Anders Ohlsson in his EDN article – is written in Delphi and will run on the Mac (and even iOS I guess…?) as well as on Windows.  Pretty slick.  And while you are at it, check this one out as well.

…Wherein I Rant Vigorously About Mobile Twitter Clients

By Nick at February 05, 2012 00:23
Filed Under: TechBiz, Tech Stuff, General, Delphi

I am now going to go on a rant about Twitter clients – mobile Twitter clients in particular (though some desktop clients are rant-worthy as well).  I am going to do this because I can’t understand why they are such a pain in the ass and work so badly, when they could so easily work so well.

Okay, first, don’t get me wrong.  I really like Twitter.  (If you want, you can follow me, I’m @nickhodges --  no surprise in that handle, eh?)  I like it because it’s a great place to keep up on news, find interesting articles, read funny stuff, and to post your thoughts in short, pithy statements of 140 characters or less.  It’s also a great time killer.  If you are waiting at the doctors office, it’s a much better way to pass the wait than looking at a two and a half year old copy of People Magazine.  It’s interesting, fun, never the same thing twice, and frankly, I’m a little addicted.  I do almost all of my twitter reading on my phone or on my wonderful Amazon Kindle

But yet reading Twitter on my mobile devices drives. me. crazy.  When it comes to mobile Twitter clients, I’m not addicted -- I’m inflamed with a rage that burns like the heat of a thousand suns.

I’ve tried just about every one out there. They all drive me insane.  And so here is  my rant:

  • A twitter client should never, ever, ever, under any circumstances, for any reason, at any time, ever, ever, EVER move my “cursor”.  EVER. And by “cursor” I mean my location in my Twitter stream.  I determine where my cursor goes, not you, you blasted twitter client that thinks you can just show me whatever you want when you want to.  If I am reading Twitter on my phone, leave off on a funny Pauly Peligroso post, go away to another app, and then I come back, you darn well better have my twitter client looking right at that same stinking Pauly Peligroso post when I come back.  I don’t care if I’ve been gone for five minutes, five hours or five years, you flipping better have your cursor right there where I Ieft it. Not anywhere else.  Where. I. left. it.  Leave a gap if you have to. I don’t care, just leave it. Don’t try to do me a favor and “catch me up”.  If I need catching up, I’ll get myself caught up. Give me an option to get caught up, fine.  But for the love of Adam Sandler, DON’T MOVE MY POSITION IN MY TWITTER STREAM.   Ever,  ever, ever, never, ever, ever. 
  • Second, if you tell me that there are “143 new tweets”, and I say “Great, some new tweets”, put me at the freaking START of the 143 new tweets, not at the current time!!!!   Why in the name of sweet baby Dick Van Dyke would I ever, ever, ever what to start at the most recent tweet out of those 143 new tweets? Why would you tell me that there are 143 new tweets and then start me out at the point where there are zero new tweets? Why do I open up the fracking client and see some tweet from three seconds ago, when I want to read the 143 new tweets?  Why do I have to manually scroll down and try to figure out where the new tweets start?  What is that, some kind of sick, twisted joke?  Really?  I have to scroll?  Seriously?   I mean this is basically a variation of the “Never move my cursor spot”, but come on, this is ridiculous.
  • Third – stop trying to shorten my shortened URL’s.  I’m smart – I can shorten my URL’s myself.  It’s nice you want to do that for me, but at least let me opt out of it.  Nothing says “wasted time and resources” as a link that is a Twitter shortened version of a bit.ly link that started out as a tinyurl.com link.  I mean, come on, I can keep my twitter posts under 140 characters myself.  I don’t want your help.  I don’t need your help.  Stop it.

Bottom line: Mobile twitter clients stink and they make me want to bash public monuments with a sledgehammer. (I’d never do that, really, but I want to when I go back from checking my mail and the stupid TweetCaster moves me to  a tweet that was posted 23 seconds ago.)

Phew, okay, I feel better now.

An Interface Implementation Pattern for Consideration

By Nick at February 03, 2012 23:42
Filed Under: Delphi, Software Development

So I’ve been writing about Interfaces, and mostly talking about how you should use them.  But as important as designing and using the interfaces themselves is how you implement those interfaces.  I talked about the basics in the previous article, but there are some things that you can do to make implementing an interface a little easier.

I’d like to show one way that you might go about it for the purpose of starting a discussion about the technique.  I’ve seen the method I’m going to describe below used in a number of places, most notably back in WebSnap. (Remember that?  WebSnap was actually a pretty cool library of code, doing a lot of things in a somewhat MVC fashion  before MVC and web development was in, well, fashion.)

Anyway, here is how the implementation pattern I’m talking about here works:  You create a “base” class that implements each member and property of the interface. Then, you add a virtual, abstract method that corresponds to each interface method with a naming convention of DoMethod.  You then call that virtual, abstract method inside the implementation of the interface methods. 

This base class then becomes the parent for any class that implements the interface.  In essence, you create an easy-to-inherit class that easy implements the interface so you don’t actually have to worry about implementing the interface over and over again. 

Naturally, this is hard to explain, so a code example is in order.

Consider the following simple interface:

type
  IDemoInterface = interface
    procedure ProcessSomething;
    function ProcessData(aString: string; aInteger: integer): Boolean;  
  end;

Nothing fancy, and obviously illustrative. 

To do what I’m talking about, you’d implement this interface as follows:

type

  TBaseDemoInterfaceImplementor = class abstract(TInterfacedObject, IDemoInterface)
  protected
    procedure DoProcessSomething; virtual; abstract;
    function DoProcessData(aString: string; aInteger: integer): Boolean; virtual; abstract;
  public
    procedure ProcessSomething;
    function ProcessData(aString: string; aInteger: integer): Boolean;
  end;

procedure TBaseDemoInterfaceImplementor .ProcessSomething;
begin
  DoProcessSomething;
end;

function TBaseDemoInterfaceImplementor .ProcessData(aString: string; aInteger: integer): Boolean;
begin
  Result := DoProcessData(aString, aInteger);
end;

So, what you have now is a class – TBaseDemoInterfaceImplementor – that can be used to really implement the functionality of the IDemoInterface.  You have an abstract class to inherit from, and two methods to override to implement the functionality. 

So, of course, the class that you’ll actually use would look something like this:

type
  TRealDemoInterfaceImplementor = class(TBaseDemoInterfaceImplementor)
  protected
    procedure DoProcessSomething; override;
    function DoProcessData(aString: string; aInteger: integer): Boolean; override;
  end;

function TRealDemoInterfaceImplementor.DoProcessData(aString: string; aInteger: integer): Boolean;
begin
  ShowMessage(Format('I am processing the following data: %s and %d', [aString, aInteger]));
  Result := Random(2) = 1;
end;

procedure TRealDemoInterfaceImplementor.DoProcessSomething;
begin
  ShowMessage('I am processing something!');
end;

What happens is that the implementation becomes much less painful once you have the base class defined with the details of implementing the interface neatly tucked away.  You are doing simple class inheritance at that point. 

Now I’ve thought about this pattern for a while, but I’m not sure about it.  I’m very interested in hearing what you all think.  I guess one downside is that the class doesn’t clearly declare that it implements a given interface.  Perhaps a naming convention would do that? 

On the one hand, it seems a nice way to create a class library that implements an interface.  To me, it seems like a good use of polymorphism. There may be times when you want a large chunk of your library to implement a “basic” interface, and using this inheritance trick can make that easy.  Once you create a base class, you can now build a class hierarchy based on that class, with all the classes implementing the interface with much less hassle and more cleanly.  In addition, it makes it easier to create any number of descendants  from the base class if you want to have a number of different implementations for the interface.  For instance, if you had ICreditCard, you might create TBaseCreditCardImplementor, making it easy to descend from and create TVisa and TMastercard, etc. 

Pattern? Anti-pattern?  Maybe I’m crazy and this is a really silly idea.  Maybe this is a known pattern already and I’m just ignorant.  Maybe this is the coolest idea ever. 

What do you guys think?

Okay, So When Should You Call Create?

By Nick at January 30, 2012 23:27
Filed Under: Delphi, Software Development

Okay, I want you all to notice that in my previous post about the use of Create,  I was pretty careful not to say “Never call Create”. And near the start I said “For the most part”. So let’s be clear – just as I didn’t say “Never ever call FreeAndNil”, I’m not saying “Never call Create”.  And while I am at it, I didn’t say “Use interfaces everywhere” either.  Those of you who are accusing me of saying so are wrong.  Incorrect. Inaccurate.  You should be ashamed and you should correct yourselves. You should also read more carefully and think more precisely.

Enough about what I didn’t say.  What am I saying?  I’m saying “Architect your code so that you avoid calling Create, because doing so causes problems”.

Problem number one is that your code becomes difficult to test.   This is a fact:  When you call Create – when you create more than just an instance of a specific instance of a specific class – you are tightly coupled to that class and it’s entire dependency graph. (If you don’t know what a dependency graph is, you can find out more here.)  Some classes have huge dependency graphs.  That is, the creation of that class cause a cascading of creation of other classes which can initiate any number of things:  Connections to databases, locking of files, attachment of limited resources like turnstiles or cash registers – who knows what? 

Classes that have dependency graphs are classes that should not be manually created, but instead should be created by a class that can control if and when that class is created.  The creation of such classes should be definable and controllable.  They should be referenced by an abstraction and they should be created in a configurable way.  If you want to test the dependent class, then you can have your system create a mock instead of the real thing.  If you call Create on that class, you can’t do that. 

How should we refer to these types of classes – classes that have dependency graphs of any sort?  Let’s refer to them as “complex classes”.  (I looked for the commonly accepted term here, and couldn’t seem to find one.  I haven’t the slightest doubt that one of you will tell me what the “right” term here is. I’ve seen the term “volatile” used, but I don’t like that because of the keyword volatile that some languages use.) So for the purpose of our discussion, a complex class is one that has a dependency graph; it’s a class that, when created, brings in other external dependencies.  Sometimes those external dependencies are easy to define, and sometimes the dependency graph gets so complex it is hard to know what is happening exactly when that class is instantiated.  For instance, think of TForm.  When you create TForm, holy mackerel – a long, complex host of other things are being allocated – Windows handles, other VCL classes, fonts and this and that and the TKitchenSinkTForm is most definitely a complex class.

But, what about something like TStringListTStringList has, as far as I can tell, no real dependency graph.  Create one of those, and you really aren’t creating a host of external dependencies.  TStringListis basically self contained.  It is a known, limited entity. (Look at it’s constructor and the constructor of TStrings.  It basically doesn’t create anything, so it really can’t have any dependency graph.)  It can be created without worrying that you are going to end up calling some charge-money-every-time-you-use-it web service.  It’s simple, clean, and limited.  It’s not a complex class.  It’s a simple class.

So, to answer the question posed in the title of this post – you can (and should) call Create on what I’m calling simple classes.  Generally, these will be classes defined in the RTL that clearly are stable or simple in that they don’t have dependencies that are non-deterministic, unknown, or complex.  Classes like TStringList, TStringBuilder, TList, the classes in Generics.Collections.pas, and many others are examples of classes that you should feel fine about creating.  These classes are know and proven by virtue of being part of the RTL.  You probably have many similar classes in your own library – classes that you have bathed in unit tests so you know that they are isolated, stable, and simple.  You can determine the complexity of such classes by looking at the constructor of a given class.  (And note: The use or lack of use of Create in those classes indicates whether they are complex or simple.  Hmmm.)

You should feel safe creating such simple classes because you know that you aren’t dragging in the TKitchenSink when you create them.

So that should answer the question, eh?

What I've Been Reading

By Nick at January 28, 2012 10:34
Filed Under: Book Review, General, Personal

Flotsam and Jetsam #54

By Nick at January 28, 2012 10:06
Filed Under: Delphi, Flotsam and Jetsam
  • I like FireMonkey.  Actually, I confess that I don’t know much at all about FireMonkey, but I like that it exists.  I don’t use it, but I like that it is there, broadening the appeal of Delphi and generally advancing the cause of the tool we all love so well.  So I was pleased to see that the nascent market for third-party FireMonkey controls continues to grow.  The latest offering is from Jason Southwell’s Arcana with the cleverly named “ApeSuite”.  ApeSuite is in beta, but you can get in early at a special price.  Jason has been updating the library pretty regularly. I’m glad to see people getting a good start on what will hopefully be a thriving marketplace, and I tip my cap to Jason for jumping in.
  • Alex Ciobanu – formerly of the Delphi RTL/VCL team – has made a few changes to his outstanding open source offerings.  First, his DeHL project has been discontinued.  I’m sorry to hear that – there are some really interesting things in there.   But second, he has done a brilliant job with a new project that is, to a certain degree,  a replacement, Delphi Collections.    He says it is “on hold” but it appears that he is actively working on moving it forward.  Alex is a really, really good programmer, so I keep a close eye on what he is up to.  His contributions to the Delphi community are very large, and I’m very appreciative of what he does.  Lots to learn there.
  • How to Get Your Comments Deleted:  This is my blog, and what ends up on on it is up to me.  I’ve noticed that some of you have been trying really hard, though, to get your comments deleted with a modicum of success – and I’ve been helping to make sure that you succeed in this endeavor when appropriate.  I thought that you all might want to know for sure how to get your comments deleted.  The best way is to be a jerk and write a content free but insulting comment that adds no value whatsoever.  Do that, and you’ll get your comment deleted.  Hope that helps.
  • Eric Grange pointed out that there has been a marked uptick in activity on open source projects involving Pascal.  It’s nice to see numbers attached to something that I’ve kind of felt to be the case.  The addition of generics and anonymous methods to Delphi really opened the language up to some really cool and really powerful frameworks, and things like Alex’s code above, the Spring Framework, Delphi Mocks, and all kinds of other frameworks.  It’s a really good time to be a Delphi developer.  (And Ohloh is a pretty interesting site – worth poking around.)
  • What and how things are named in our code is a really important part of being a good developer. That’s why I thought this post was interesting – “Interface naming: prefix 'Can-' vs suffix '-Able'”    We tend to create interface names with –able (ISerializable, IDisposable, IEatable, whatever….) and maybe that isn’t always the best convention?

Life is Too Short To Call Create

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

Introduction

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

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

Life Too Short?

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

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

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

I’m Lazy

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

Don’t Cause Dependencies

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

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

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

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

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

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

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

Following SOLID

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

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

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

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

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

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

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

Why You Should Be Using Interfaces

By Nick at January 22, 2012 21:15
Filed Under: Software Development, Delphi

I’ve been railing on why you should be coding against interfaces, and a number of you have been asking me to write an article about it, so I did.  It turned out to be pretty long, so rather than make it a blog post, I turned it into an article.

Why You Should be Using Interfaces and not Direct References

Flotsam and Jetsam #53

By Nick at January 18, 2012 09:20
Filed Under: Flotsam and Jetsam

Why I Prefer Android to iOS

By Nick at January 16, 2012 19:54
Filed Under: TechBiz, Tech Stuff, General

I have an Android phone – a Samsung Nexus S 4G which I love. It’s a "pure Google” phone in that it’s sponsored by Google and doesn’t have any of the vendor specific stuff on it that some of the carriers like to include.  And as you know, I just bought an Amazon Kindle which has a version of Android on it.  I’m still saving up for a full-fledged, 10 inch Android tablet.  I really like Android. 

And I have no interest at all in the iPhone, the iPad, and their accompanying operating system, iOS.

So I thought I’d explain why.  There are a number of reasons why I like Android and generally avoid Apple.  Here they are:

First, I really like that Android has the notion of a desktop similar to Windows.  On it you can place all kinds of things called “widgets’ – clocks, weather updates, twitter feeds, Facebook timelines, and shortcuts.   They are all available instantly on the pages of your desktop.  You can put almost anything you want on your multiple pages of the desktop.  I have one touch access to turning on and off things like WiFi and sound.  I can turn on the “Flashlight” (the camera flash) with a single touch of my desktop.  I can read news headlines just by swiping to my “news page”.  That’s a lot of power without having to hunt for and find a specific app.  The desktop on iOS (if you can call it that) is nothing but a listing of the applications on the device.  That’s fine as far as it goes, but the Android desktop provides a lot of very valuable and cool functionality.  I find that very useful.

Not only does Android provide the notion of a desktop with Widgets, it allows you to configure almost any aspect of the system.  You can choose from any number of configurable, intelligent keyboards that make typing easier.  You can pick from an array of desktop launchers that work in ways you might prefer.  You can choose launchers for efficiency, for visual appeal, or for configurability.  Or for all three.     You can even customize the lock screen if you want.  Again, this is really cool and I prefer it over the limited system that iOS provides. In the end, you have complete control over the appearance and functionality of your device – something I really value.

And the reason that Android provides so much flexibility and power to the user is that the OS is open source.  Developers can see how the OS works and build apps, launchers, and widgets accordingly.  And of course, they can even modify the operating system itself.  In addition to the Android Open Source Project, there are a number of alternative operating systems.  The most popular are CyanogenMod and MiUi.  Some handset vendors lock down their bootloaders, but most are wising up and allowing users to easy root their phones and modify them in ways of their choosing.  The stock systems customers buy are plenty powerful, but if one is so inclined, one can completely control what runs on the phone.  Sure you can jailbreak your iOS devices, but you are still stuck with the single, closed operating system.  Android users have no such restrictions.

Since the system is open, there are multiple ways to get applications.  Android users can get apps from the Google Android Market, from the Amazon AppStore, and other places like AppBrain, and they are perfectly free to “sideload” applications from any source if they so choose.  There is no single, controlled point of entry for applications.  That’s cool. And hey, maybe you don’t like Flash, but at least you can run it on an Android device if you want to. And oh yeah, you don’t have to pay for the privilege of distributing your apps, nor do you have to get “approval” from the AppStore gods.

And of course, Android customers have a wide choice of hardware as well as software.  The iPhone and the iPad hardware is cool, and yeah, you can have any choice of hardware you like -- as long as it is the hardware Apple provides.  Android phones and tablets come in many sizes, colors, and flavors.  Most come with removable and configurable storage. They come from different vendors and carriers. (iPhone initially launched with one (1!) choice of carriers, slowly moved to two, and now begrudgingly added a third.) They progress and advance more quickly.  Each vendor competes to out do the other in providing features and power.  You can already buy quad-core Android tablets.  

Now let me be clear:  If you like Apple, love Apple, or even are an “Apple Fanboi”, that’s fine with me.  Knock yourself out.  You won’t get any argument from me.  We all have our preferences, and if you prefer Apple over PC’s and Android, that’s great.  I’m not going to get into a flame war over “My OS is better than your OS”.  I’ve been there, done that, and frankly, I’ve grown out of it.  I happily admit that I was an immature fool to engage in those kinds of discussions.  You like Apple?  Awesome.  I don’t myself, but live and let live, eh?    I know it is too much to hope that the comments won’t prove to be contentious, but I myself am not going to get into a debate.  I’m just expressing my opinions here, and am 100% fine if you disagree 100% with me.

And easily one of the coolest things about Android is the whole Google eco-sphere and cloud.  Android is completely integrated with all the Google apps that we know and love:  Gmail, Maps, Docs, Reader, Tasks,  Google+, Google Music, everything.  A single sign-on brings it all together on your phone, on your tablet, and on your desktop computer.  There basically isn’t a Google App that isn’t completely integrated with Android.  And because the Google cloud is completely open, third-parties can easily integrate into it and use its functionality to enhance what Google provides. For instance, gReader is a third-party app that leverages Google Reader to provide a better RSS experience on Android.  Integrating with what Google provides is easily one of the most powerful and valuable features of Android.  Okay, call me a Google FanBoi, but there is a lot of cool power there that I really like and  use.

But at a more basic level, one of the more fundamental reasons I prefer Android is that, well, it’s not made by Apple.  I do not – and never really have – liked the way Apple does things.  I don’t like how they strictly and ruthlessly control their eco-systemsI don’t like the way that they treat developers.  I don’t like how they use lawsuits to try to stifle competition  (I thought the “look and feel” wars were over, but I guess not).  I’m perfectly happy to admit that Apple makes wonderful hardware and has blazed some important trails in many ways.  That’s all well and good – I just prefer not to do business with them.  Moreover – and I agree that this is harder to qualify --  I’ve never really like the “hipster, holier than thou” attitude that seems to emanate from the Apple community.  I know it’s totally my problem, but as far as I’m concerned,  the smuggest place on the planet is the center of an Apple store. And I don’t do smug.  I literally shake my head and snigger constantly when I take my daughter there (She has a Mac – despite my best efforts to persuade her otherwise...).   I know that’s not really rational, but that’s just how I feel.

So in summary, I like Android because it really doesn’t lock you in to anything.  It doesn’t lock you into hardware, application sources, carriers, or operating systems.  Just as DOS/Windows was more open flexible, and easy to develop for back in the early days of personal computing, so is Android currently the open, flexible, easy to develop for platform on portable devices.  I totally get that openness has it’s price – but I preferred the openness then, and I still prefer it today.

Why I Bought a Kindle Fire

By Nick at January 14, 2012 18:47
Filed Under: TechBiz, Tech Stuff, General, Personal

Last week I became the proud owner of a Kindle Fire.  I know that in my last post I spoke a few unkind words about Kindles, and so I wanted to write about why I decided to get a Kindle after all.

Here at our house, we are in Debt Assassin mode, so I have very little leeway for discretionary purchases like a tablet.  I get a monthly allowance to spend on anything I want, so if I want a new tablet, I have to save up.   I decided that I wanted a tablet earlier in the year, and I originally set my eyes on a Samsung Galaxy Tab 10.1 which at the time was the Android tablet to get.  (I have a blog post coming up about why I prefer Android over iOS…)  It is still a very nice dual-core tablet, but as things go in the tech business – and since it took me a while to save up my pennies – technology marches ever forward and I soon switched to wanting the more powerful and more feature-rich ASUS Transformer Prime

The Transformer Prime is a really, really sweet tablet.  It’s a quad-core machine using the Tegra-3 chip, with an amazing 1280x800, ten finger multi-touch screen.  It  has a flexible, add-on keyboard that effectively turns it into a notebook computer.  It even had a fifth core which would do minor tasks like check email and other background tasks while the screen is asleep.  It was priced right at that sweet spot of $499.  Interest was very, very high in this device, and all the Android blogs and news sites were abuzz with anticipation. 

It was supposed to be available just before Christmas, but pre-ordering the device was troublesome.  Amazon, which has a very good policy of not taking pre-orders unless it is sure it can deliver them, stop taking pre-orders in late November.  Delivery dates for other vendors were unclear.  When Amazon did start taking orders again before Christmas, they listed fulfillment as 5-7 weeks out.  Clearly ASUS had that good problem you don’t want to have – demand far outstripping their ability to deliver on that demand.  As a result, I held off on placing my order. 

But then a few hiccups began to occur.  I suspect that because it was the first tablet to use the Tegra-3 Quad-core chip, they had some problems with the product.  While initial quick-looks were very encouraging, reports started to surface of problems with wireless receptivity and the GPS.  Apparently the actual physical design of the case was causing reception problems.  These reports didn’t seem to dim interest in the device, however, as it’s still hard to get a hold of one, and as of this writing, Amazon itself isn’t taking orders, instead is is fulfilling the order via a reseller – who currently is jacking up the prices to over $600.  FInally, though it was short lived and ASUS pretty quickly backed down, word came out that ASUS had locked the bootloader for the Transformer Prime. 

Okay, so given all that, I decided to hold off and see what would happen.  ASUS was actually pretty good about acknowledging and fixing the problems, but I decided to defer my gratification (I was pretty jacked up for getting a tablet, and it was hard to wait…..) and let things shake out.  But then again, I wanted a tablet now.  And of course, as I’m holding off, Google announces their “Google Tablet” and that catches my eye, because I have a Nexus S phone and I’m a big fan of the whole “pure Google” concept. However, that isn’t coming out until the fall.   What to do?

Well, I took the advice of one of my co-workers and decided to get the Kindle.  His advice was this:  Tablets actually can have an impact on your life – you don’t know how it will fit or what role it will play. $500 is a lot to spend to find out, so get the Kindle at $200, find out how tablets work for you, and then save up for the Google tablet or whatever tablet is the “must have” tablet to get when I’m ready to buy.  Plus, the Kindle will likely hold it’s value, and I’ll be able to easily sell it when I decide to make the move.  In a sense, the Kindle is a “Starter Tablet” for me, and a pretty inexpensive one at that. 

And so far, I really like my decision.  I still have a pretty good chunk of change in my “saved up allowance” envelope (no sense putting it in the bank with interest rates hovering a hairs-breath of 0.00%….), and I can save for my next tablet.  I’m finding that I like the Kindle a lot (I’ll write about that in a future blog post) and the notion of “finding out how I work with a tablet” is definitely playing out.  I can now keep an eye on the market, and make a good decision on a good, quad-core tablet when the time comes.   Overall, it was outstanding advice, and I’m really happy with how things are working out.

The Bookstore of the Future

By Nick at January 09, 2012 00:17
Filed Under: Delphi, General, Tech Stuff, TechBiz

Bookstores are Cool

I love bookstores.  A lot of people love bookstores.  I love hanging around in a bookstore and seeing what is new, what is popular, and what is available.  I love seeing the cool games and other non-book stuff they have.   I love how most bookstores now have wireless, a café, and plenty of large cozy chairs to sit in if you want a closer look at a book. Bookstores are very cool, and I like having a good one nearby.

There are more than just superficial reasons to like bookstores.  First, they provide instant gratification.  If you want a book, you can get it immediately.  You can hold it in your hand and walk out of the store with it.  Another nice feature is the ability to browse – you can wander around, look around, and perhaps find a title that you didn’t know you wanted.  In addition, the ambience of a good bookstore is appealing and valuable as well.   The addition of café’s, music, and other products have also made bookstores much more appealing.  Clearly there is demand in the marketplace for bookstores, since whenever I go to one, there are always people there. 

Bookstores are in Trouble

But bookstores clearly are struggling.  Big player Borders recently went out of business (Anyone else notice where http://www.borders.com goes?)  Many smaller, independent vendors have been driven out of the market as well , though some of superior quality to survive (For instance, my sister loves Wild Rumpus, near her home, and they seem to be doing very well).  Online retailing has affected brick and mortar sales.  In addition, used book stores seem to have grown as well, putting market pressure on retailers of new books.  The Books-4-Less store near my house is a pretty good source of reasonably priced books, and they have a very nice selection.  They also accept “trade ins” for store credit, so you can clean out your basement and get a few new books at the same time. 

But people shopping online in the comfort of their own homes at sites like Amazon can get a much wider selection, recommendations, reviews, and all kinds of information available.  Online retailers can offer reviews, an almost infinite range of other books to “browse”, recommendations, and more.    If you know what book you want to get and aren’t feeling an urgent need to have it at this exact moment, dialing it up on Amazon’s site and ordering it with (often free) super-saver shipping can be a great time saver.  Plus, there’s non tax, and you save the gas and time of a trip.  I don’t have specific numbers, but I’m guessing that the ease of buying books online has hurt bookstore sales more than anything else.  For instance, books are always a popular gift, and the convenience of Amazon’s gift giving capabilities make giving a book as a gift vastly more convenient.  Amazon gets the book, wraps it in gift paper, and takes it to the post office for you.  Very convenient.  I’m guessing that I’m not telling you people something that you haven’t already figured out yourselves -- you are taking advantage of them in increasing numbers.

And if that isnt’ bad enough, adding to the online competition for bookstores are devices like the Amazon Kindle and other similar electronic reading devices.  Sales of Kindles and Nooks continue at a brisk pace, and every one of those represents countless book purchases that won’t be made in a bookstore.  Digital books don’t need a bookstore at all (Can you even have a bookstore of digital books?)  I know people that have Kindles who have bought many books, but haven’t held a new book in their hand in a long time – a fact good for Amazon, but not good for the brick-and-mortar retailers.  Why  even go to a bookstore?  Your friend at the local Starbucks can recommend a book and you can be reading it in just a couple of minutes – not something the owners of Borders were happy to realize. 

The Kindle is cool, but there are a few things I don’t like about it.  The top one is there isn’t any easy way to “peek ahead”.  Surely you do this – you are lying in bed reading, and you start feeling tired.  Do you just quit now, or is there a natural breaking point coming soon – a chapter ending, a sub-chapter break?  You can’t do that easily with a Kindle.  Second, (and this is why Amazon is so up on it), you pretty much have to pay for everything you want to read.  You can’t easily loan books to friends (the time limit is no fun – what to do if you have two chapters left when the time runs out?) Borrowing books from the Library has the same problem.  Amazon Prime does offer a lending service, but again, you pay for it. (See why Amazon likes the Kindle? Winking smile)  There’s a lot to like about Kindle’s, but there are a few things not to like as well.

The Current Model Costs A Lot

One of the largest struggles of the average bookstore – and the broader book industry – is costs.  The current business model is staggeringly inefficient.  Huge boxes of books – most often more books than will ever sell – are printed at a central location, loaded onto trucks and shipped to bookstores all around the country.  Those boxes are opened, and books put out on the shelves.  The rest are stored somewhere at the bookstore “in the back”.  After a while, a certain percentage – hopefully a high one, but not always – of the books are sold.  The rest are put into the “bargain bin” and sold at a discount.  Eventually, the remainders end up at those sad little bookstores at the mall or destroyed.  The costs of transporting books – they are heavy, as anyone who has moved house knows – is high.  The waste of printing books no one wants is high.  Trying to figure out the right number of books to go to the thousands of different locations – some books may be more popular in Topeka, KS than in New York City – is pretty difficult to predict.  It’s the common problem of centralize planning – who can know?

The bottom line is that the costs involved with the current bookselling/bookstore business model are simply too high.  It’s no wonder Borders went out of business – they were a day late and a dollar short with their eReader – and it’s a wonder that Barnes & Noble have kept their stores, too.

Emerging Technology

Despite the aggressive onslaught of online retailing and eReaders and very high costs, I still think there is a future – a pretty cool future -- for brick-and-mortar bookstores. However, they are going to  have to change a bit, and adapt to some new and emerging technologies.

That key emerging technology bookstores need to learn to leverage is on-demand printing.  On-demand printing is a relatively new technology, but one that can be a positive and powerful inflection point for bookstores.  On-demand printing is the ability to print a book – cover, contents, everything (even hardcovers) – immediately and on demand.  Think of it as a copy machine for books.  I’m not intimately familiar with the current technology, but I understand that it is getting to the point where a book from an on-demand printer is virtually indistinguishable from a “real” book.  Services like lulu.com and other retailers enable authors to publish any content completely unencumbered by the established publishing houses.  Because books are printed as ordered, they don’t care about volume. 

In addition, the margins on book sales are much better, and so authors can make more money – much more money – on each book sale.  Delphi authors like Marco Cantu and Bob Swart have leveraged these services to bring you high-quality content while making more money in the process.  Sweet for everyone.  On demand printing is clearly an technology that will require some adjustments to business plans throughout the bookselling business.

The Bookstore of the Future

In the future, I envision a bookstore working very similarly on the surface, but very differently behind the scenes.  Bookstores will become a retail outlet for on-demand printing. On the outside and to the casual observer, bookstores will appear to be much the same – books on shelves, cafés, calendars, music, videos, etc.  But a closer look will reveal some differences brought about by on demand printing. 

First, a bookstore will have the ability to print immediately any book.   The shelves will be full of books as now, but a customer will also be able to ask for, and get, any book in the publishing system.  This feature will help bookstores match the online retailers by allowing a book buyer to get almost anything they want.  The ability to print any book immediately will be a big feature that will enhance a bookstore’s market appeal. 

And not only will a customer be able to get any book they want, the bookstore could offer any number of customizations to a book.  Kids could get copies of the Twilight series with a selection of different covers of their favorite characters.  Readers could choose font type and size, and perhaps even different colors of paper.  Each feature could cost extra, increasing margins.  I can foresee computer kiosks at the store allowing users to pick features a la carte.   Heck, I can even foresee bookstore branded kiosks at grocery stores much like RedBox.

The second subtle change that will take place is that the books available on the shelves will consist of fewer duplicates.  Since the books are printed onsite, they don’t need to stock up on multiple copies, leaving room on the shelves for a wider variety.  This will improve the browsing experience.  And of course the store can keep the shelves fully stocked.  The point of sale system would record each sale, and a book is sold, a replacement can be immediately and automatically printed. Efficient printing and stocking would mean that the shelves would be full, and a wider variety of books would be available on the shelves almost constantly. 

And of course, the printing of books right in the store means no more distribution costs – no more centralized printing with the subsequent distribution inefficiencies. New books will be distributed electronically of course.  Book stores will still need paper, glue, ink, toner, etc., but t’s much easier and less costly to distribute supplies than it is boxes of specific books.  And the waste of printing books that never get sold will be reduced because inventory will be wider and flatter with little over-stocking.

How it Will Happen

The transition to this new model will be interesting.  I don’t think that you’ll see it come from existing chains like Barnes & Noble.  Generally, a radical, disruptive change like this needs a fresh, upstart business to challenge the existing firms.  I also suspect that existing chains are too tightly tied to the existing publishing houses to allow them to be this flexible.  And I’m pretty sure that the existing publishing houses will not embrace this new model. The music industry has been glacial in accepting and understanding the changes brought by digital music, and I suspect that the book publishing industry will have a similar reaction. 

However, I think it will eventually happen.  The current bookstore model is clearly in trouble – even Barnes & Noble is having trouble in the marketplace despite the lost of major competitor Borders.  But in the end, the demand for the things that bookstores offer is strong.  The industry will be fine once they figure out how to leverage the advantages that on-demand printing offers.

My Book

A Pithy Quote for You

"Just the knowledge that a good book is awaiting one at the end of a long day makes that day happier."    –  Kathleen Norris

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