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

Three Sentence Movie Review: Crazy, Stupid, Love:

By Nick at January 02, 2012 22:32
Filed Under: Three Sentence Movie Review
Crazy, Stupid, Love: This is actually a rather profound movie with great acting and terrific characters.  It deals with the nature of true love, and shows how people can learn from each other when they least expect to do so.  I could have done without the kiddie porn situation, but overall, I rather enjoyed it, especially the Tour de Force performances by Ryan Gosling and Steve Carell.

More on FreeAndNil

By Nick at January 02, 2012 14:03
Filed Under: Software Development, Delphi

I love a good, testy comment section in a blog post.  Winking smile  The discussion in the comment section of my FreeAndNil post has been interesting and lively.  In addition, the thread in non-technical continues apace, with new threads springing up!  Along the way, a couple of interesting points were made that I’d like to highlight here because I think they are germane.

  • First, I can sum up the article as follows: “Don’t use FreeAndNil.  If you feel the need to use FreeAndNil, then your code almost certainly needs to be refactored to limit the scope of your references.”.    People arguing for it’s use are, in my mind, simply saying “I don’t know how to or don’t care to control the scope of my pointers” 
  • Second, I want to stress again that I totally get that sometimes you have to use FreeAndNil. Sometimes you maintain old code that played fast and loose with pointer scope, and didn’t contain things like we now know you should.  I get that.  But those situations should cause you shame and embarrassment, and should motivate you to refactor your code to control references and make the need for FreeAndNil go away.  The reason that I totally get this is that I manage such a codebase.  The point isn’t about maintaining legacy code, it’s about how to write new code the right way.  And if you are writing new code while feeling the need to FreeAndNil stuff, then you aren’t doing it right, quite frankly.
  • Jolyon Smith wrote the following in the comments: “Surely you must also admonish everyone to write code that never requires the use of if Assigned(someReference) then…”  Well, yes, I suppose that is exactly correct in most cases, unless you are doing lazy initialization, which I wouldn't recommend using anyway.  If you are using Dependency Injection -- and you should be -- there is never a reason to be worried about your references not being assigned. 
  • John Jacobson writes: “Reference-counted interfaces are what you should be using anyway, keeping your actual class implementations private and hidden in the implementation section of their unit.”  He’s absolutely correct. Ultimately, you should be coding against abstractions, not implementations.  If you are doing that – and of course you should be in Delphi via reference-counted interfaces – then you shouldn’t be freeing anything other than local, non-volatile variables, and you should never need to FreeAndNil those.

By now many of you all are probably saying “This guy is a nut!  Get over the FreeAndNil thing already!”  Well, okay, I agree I’ve beaten this drum quite a bit.  And I agree that I’m pretty much a nut. But I really think that it represents a critical point that we all need to understand in order to move forward:  Code needs to be under control.  Good development dictates that we limit the scope of references.  And finally, out of control references are the cause of many, many bugs, and are the cause of 100% of access violations.  The use of FreeAndNil is a blatant symptom of this problem.

Here’s the bottom line, and I’ll be blunt: If you are arguing in favor of using FreeAndNil, what I really hear you saying is “I learned to code in 1991 and haven’t learned a thing since.” 

Okay, that’s a little harsh.  I’ll put it a bit softer:  Worrying about pointers and references is, well, an old-fashioned way of thinking.  There are ways to code so that worrying about whether a pointer is valid or not is no longer something you have to worry about.  This way of coding is more productive, cleaner, and more effective.  It produces high-quality, testable code.  

Doesn’t that sound enticing and intriguing?  Why wouldn’t you want to learn more?

Produce More, Consume Less

By Nick at January 01, 2012 12:59
Filed Under: General, Personal, Delphi

The world seems to be bent more and more on input.  The internet company sells you almost exclusively on the download speed they provide, and couldn’t care less about the upload speed.  Heck, we don’t care about upload speed much.  We are migrating towards devices that don’t have physical keyboards.  The whole idea of tablets is as media consumption devices, designed to bring data to our fingertips, where ever our fingertips may be.  (My favorite place – more on this – seems to lying down somewhere….). 

It’s never been easier to dial up a TV show or movie and watch it.  Shoot, you can even pick specific episodes for your viewing pleasure.  You can track the every move of your favorite celebrity.  You can buy almost anything to want without getting up off the couch.  You can watch replays of ever game and every highlight. You can read the thoughts of millions of 14 year old girls.  Advertising is customized to your specific interests.  It all comes at you in a slickly packaged, conveniently laid out format. 

And all you have to do is (as the airlines seem to be required to say) sit back, relax, and enjoy the flight. 

So this gets me to my New Years Resolution:  To produce more and consume less.  First, I have to give full credit to Scott Hanselman for inspiring me.  He posted this on Google Plus last night: “#1 Productivity Tip: Spend 10% of your time consuming and 90% of your time producing. Make more stuff. Watch less. Read less. Do.”

And it hit me that this was exactly what I needed to do.  I spend a lot of time consuming. A lot of time.  I watch a lot of TV shows on Netflix that I don’t need to watch. I  read a lot of RSS feeds that I don’t really need to read. I poke around on the internet way too much. Along side of all that consumption, I feel like to don’t do a lot of the things I want to do.  I have a million ideas for blog posts, but I never seem to write them.  I have a ton of ideas for writing code, but I don’t write it. I have a lot of ideas for trainings and presentations, but I don’t prepare and give them.  I sit on my butt instead of walking the dog.  Generally, I just consume and I don’t produce nearly as much as I could be. 

So that is my resolution for this year.  To produce more and consume less.  That means, specifically, I’m going to:

  • Write a substantive post on my blog once a week.  At least.  Probably more.  I want to get my “Blog Post Ideas” list down to zero and keep it there.  This blog post is the first of hopefully more.  No one might care what I have to say, but hey, at least I said it.  Winking smile
  • Find an open source project and work on it.  I’ve made some furtive efforts to support the Delphi Spring Framework project, and I intent to renew that effort at producing value for the Delphi community.
  • I’m going to get off my butt and walk.  Once I lose weight, I’m going to start running again.  I’m going to produce some better health for myself.  And my dog, too.  Winking smile
  • I’m going to write a book on coding in Delphi.  I’ve got it outlined, and I’m going to write it.  I think it will be good.  It’s been hard to get started, but that is the “big goal” for the year.  If I can produce a book in 2012, that will be a big win. 
  • I’m going to be deliberate and purposeful in what I read.  I’m going to read less (I have a lot of writing to do!) but I’m going to get more bang out of the time I do spend reading.  I’m going to focus on business books and development books.
  • The same is true for movies and TV shows.  I’m going to be deliberate and plan any watching I do.  No more just dialing something up on Netflix because I am bored.  I will be purposeful in managing my Netflix queue.
  • I’m going to remove FreeCell from my phone.  We all have that app that we use when we are – ahem – “indisposed”, and I’m going to replace FreeCell with my Bible Reading plan.  A little thing, but hey. Out with the bad and in with the good, right?  (Sorry, couldn’t resist….)
  • I’m going to spend time selling stuff on eBay.  I have a lot of stuff I don’t need but that is still valuable to somebody.  I can produce a little wealth for myself and my buyers by selling on eBay.  Last month, my awesome wife turned a bunch of stuff in our basement into over $1000 cash.  This is a productive endeavor. 

That should keep me busy this year, and that is sort of the point, right? I’d love to hear from you guys about what you are doing to produce more and consume less. 

I’ve gotten lazier over the last few years as I’ve gotten older, and it is time to reverse that trend.  It’s a gorgeous day here today in Pennsylvania, so I’m going to post this and go walk the dog. 

Flotsam and Jetsam #52

By Nick at December 31, 2011 16:59
Filed Under: Flotsam and Jetsam, Delphi
  • Many of you have headed over to the Delphi UserVoice page and voted on your favorite new feature for Delphi and RAD Studio. (Feel free to go over and vote for this one or this oneWinking smile) I’m still an Admin there, and have been, well, doing a bit of administering.  One thing I’ve been doing is marking as “Declined” a lot of “Laundry List”  and the “Too Quick” requests.  A Laundry List request is one that has multiple requests in it on a general topic.  I’m closing these because they can’t ever really be “finished”.  It might be that three of the four requests get done, but it can’t be marked “Finished” because of that last item.  Instead, one should enter a single item for each request.  “Too Quick” requests are requests without any content, and that can’t possibly ever be completed (or could be marked completed anytime) – things like “Better support for <some feature>”.  What the heck is that supposed to mean?  Anyway – you may have a few more votes as a result, so feel free to go over and cast them again, or enter better formed requests.
  • Has anyone besides me noticed that Embarcadero has done a pretty large buy with Google AdSense? I’ve got Delphi ads popping up while I’m watching YouTube videos and even reading political articles. I also get a Delphi ad on many of the pages I see over at StackOverflow.    I like it myself – I’m always happy to see advertising tailored to my specific wants and interests. Plus, I’m glad to see that the marketing folks are In any event, Google has figured out that I’m a big Delphi fan.
  • DevExpress has updated their VCL subscription to support Delphi XE2, including 64-bit Delphi.  The post even included kind words about Embarcadero from Julian Bucknall about XE2, so you know that something has to be going really well with Delphi XE2. Winking smile
  • I love a man who writes about Dependency Injection.  Brings a tear to my eye. I’m getting to the point where I think that Dependency Injection is the only way to code – that if you are calling Create and otherwise insisting on a particular implementation of an interface then you are just writing back code. 

Three Sentence Movie Review: Mission Impossible 4

By Nick at December 26, 2011 14:27
Filed Under: Three Sentence Movie Review

Mission Impossible 4:  This is a seriously excellent action film, especially when you see it at the new “BigD" theater like I did.  I know that Tom Cruise is insane, but I still find him a very compelling movie star.  I’d recommend seeing this film for the amazing stunts and a fairly compelling action plot. 

Three Sentence Movie Review: The Adventures of TinTin

By Nick at December 26, 2011 01:01
Filed Under: Three Sentence Movie Review

The Adventures of TinTin: I saw this delightful, highly recommended, must-see-in-3D film with my son this weekend.  It was very faithful to the original comic and is possibly the most visually appealing film I’ve ever seen.  I’d definitely recommend seeing this one in the theater.

Using FreeAndNil

By Nick at December 14, 2011 01:39
Filed Under: Delphi, Software Development

There has been a large and ongoing thread in the Delphi Non-Technical newsgroup about the proper use of FreeAndNil.  It’s been contentious and a tad touchy, too -- just as I like it.  Winking smile  The discussion falls out into two schools of thought:  Those that use FreeAndNil liberally and almost everywhere, and those that use it not at all or only in very rare, specific cases.  The former argues it is “defensive coding”, while the latter argues that it is the coding equivalent of spraying perfume on a skunk. 

I am in the latter camp.  I am in the the latter camp for a very good reason:  because the latter camp is right.  Winking smile There’s almost never a reason to use FreeAndNil in the new code that you write. 

And I want to be clear about that – I’m talking specifically about new code.   If you have old code that was designed in such a way that the scope of your pointers wasn’t tightly contained, than yes, you’ll probably have to use FreeAndNil to make that code work right.  But if you are doing that, I hope that you recognize that it is a problem and plan to refactor the code to contain the scope of your pointers.   I’m totally aware that legacy code may very well require that you nil pointers because the scope of those pointers is not well managed.  I know this because our system has such code, and thus contains calls to FreeAndNil

So, anyway, here’s an explanation why I think that FreeAndNil should only be used very, very sparingly. 

Before I start, I want to add that this blog post is heavily influenced by the eloquent wisdom and excellent explanations of a number of people who participated in the thread, including Bob Dawson, Wayne Niddery, Rudy Velthuis, Joanna Carter, Mark Edington, and Pieter Zijlstra.  Any profundity, excellent examples, pithy similes, or clear descriptions of things are very likely a result of me reading their posts in the thread.

Introduction

FreeAndNil is a function declared in the SysUtils unit and was introduced in Delphi 4, if I recall correctly.  I myself suspect that it was added more because of customer demand than because the R&D Team felt some need for it, and I’m reasonably sure that if they had it to do over again, they would not have added it at all.  But there it is.

The code for FreeAndNil is as follows:

procedure FreeAndNil(var Obj);
var
  Temp: TObject;
begin
  Temp := TObject(Obj);
  Pointer(Obj) := nil;
  Temp.Free;
end;

That does seem a bit weird looking – you might expect it to look like this:

procedure FreeAndNil(var Obj: TObject);
begin
  Obj.Free;
  Obj := nil;
end;

But it doesn’t.  It looks the way it does for a couple of reasons.  First, the parameter passed needs to be a var parameter because two things need to happen.  The object referenced needs to be freed, and the reference itself needs to be altered  -- that is, set to nil.  Thus, you need the freedom to change both the reference and the thing being referenced that the var parameter gives.  Second, the parameter is untyped because when you pass a var parameter, “Types of actual and formal var parameters must be identical.” Given that, if you declared the parameter as a TObject, then you could pass only a TObject to the method and not any of its descendants.

For instance, the following code will not compile:

program WontWork;

{$APPTYPE CONSOLE}

uses
  SysUtils;

type

  TMyClass = class(TObject);

procedure Foo(var Obj: TObject);
begin
  WriteLn(Obj.ClassName);
end;

var
 MyClass : TMyClass;

begin
  MyClass := TMyClass.Create;
  try
    Foo(MyClass);
  finally
    MyClass.Free;
  end;
end.

I should point out that the use (or non-use) of FreeAndNil is not an insignificant and uncontroversial issue.  The thread that spawned this is typically long.  Allen Bauer, the Chief Scientist at Embarcadero, blogged about it, and quite a discussion ensued in the comments – so much so that he felt the need to blog about it again.  StackOverflow has a whole bunch of questions on the subject.  The VCL uses FreeAndNil in places that I wouldn’t necessarily approve of.   I think that in most places its use indicates, uhm, an “older” design choice that probably wouldn’t be made today, given newer language features.  In any event, clearly folks have strong views on this and that the use (or note) of FreeAndNil is not “settled science” (though I believe it should be…). 

Okay, So When Should You Use FreeAndNil?

In my mind, the answer to the question “When should I use FreeAndNil?” is “never”, or at least “Almost never, and if you must use it, make sure that there is a really, really good reason to do so and that you clearly document that reason”.  I myself have never (to my best recollection – I fully expect someone to find some obscure reference to code I wrote years ago that uses it….) used the procedure and see no possible scenario where I would want or need to in the code I write.  My recommendation is that you never use it either, because I don’t believe that you are writing code that needs it either (unless you are on the Delphi R&D team working in the bowels of the RTL, I suppose). 

Why I Don’t Use FreeAndNil and Why You Shouldn’t Either

There are a number of reasons why I don’t use FreeAndNil

First, a call to Free is sufficient. It gets the job done.  Free will, well, free the memory associated with your reference.  It does the job completely and totally.  Can’t do any more.  Setting a pointer to nil doesn’t get you anything.  The memory isn’t going to be more free or freed faster as a result of calling FreeAndNil.  Since it’s always a good practice to use exactly the right tool and nothing more, there’s no need to make the extra call.  Consider this – there’s no SetToZero call for integers, and if there were, why would you use it?  All code should be written with “considered intent,” and the indiscriminate use of FreeAndNil shows a lack of consideration and intent.

Second, using FreeAndNil where Free alone will do just fine obfuscates your code.  Using a call that executes unneeded instructions sends a message to future readers of the code that shouldn’t be sent.  A subsequent developer maintaining your code might look at the call and say “What the heck?  Why is FreeAndNil being used here and not just Free?  Is something going on here that I don’t know about?”  Time might then be wasted investigating, and a satisfactory answer may never be found.   Code that uses Free and FreeAndNil as exactly the same thing has reduced the amount of information that your code can convey.  And when you are dealing with something as important as memory management, you certainly don’t want to reduce the amount of information your code can convey.

FreeAndNil has a clear meaning – it is a very clear indicator that the pointer being freed has meaning outside of the scope where it is used.  If it doesn’t say that, then you shouldn’t use it.  If you use FreeAndNil when that is not the case, then you’ve sent a bad message to future maintainers.  Clarity in code is paramount – nothing should be done to decrease that clarity.  Code should be intentional and there for a reason.  Code that is there that doesn’t need to be can be misleading and distracting.  Misleading and distracting are not two thoughts that developers want crossing their minds while maintaining code. 

Free has meaning as well – it clearly states that the use of that pointer reference is now done and over with.  As noted above, there’s no need to call anything else.  The indiscriminate use of FreeAndNil fails to draw the clear distinction between Free and FreeAndNil.  Losing clarity in your code is bad, right?

Third, one of the justifications for using FreeAndNil is that it is defensive and that it protects against using a pointer at the wrong time.  The claim is that if a pointer is nil, and you then use that pointer, then you’ll know right away, and the bug would be easy to find. Thus, if you feel the need to use FreeAndNil to ensure that you don’t misuse a pointer somewhere, then it is very likely you have a design problem:  the scope of the pointer in question is larger than the use of that pointer in your code.  Or, in other words, the scope of a pointer and the scope of the use of that pointer aren’t the same and they should be.  If they aren’t , you are simply begging for trouble. 

If you want to really be persnickety, a variable that is broader in scope than it’s use is a form of a global variable.  And I would hope that we agree that global variables are bad.  If we can’t agree on that, well, then we can’t agree on anything.  Winking smile

Maintaining proper scope is critical to good, clean code.  I’ve discussed this before, and so I won’t go on about it here.  The germane point here is that if the scope of a pointer is of the “laying around waiting to be used”, then there is no limit to the mischief that this wayward pointer can cause.  So, if you don’t “leave a pointer lying around”, you can’t misuse it.  So, well, don’t leave a pointer lying around.   If you don’t leave roller skates at the bottom of the stairs, you can’t go careening down the hallway.   Keep your pointers and the use of those pointers in the same scope and you can’t misuse a pointer.  And you won’t feel the need to use FreeAndNil

And if you do use it for defensive reasons, you have to use it everywhere.  You have to use it in ever single place it is needed and you can’t miss a single place.  And, every single maintainer of the code after you has to as well.  One instance of not using it basically removes all the reasons for using it.  It’s a much better plan to simply control your scope and never feel the need for it. 

So, in the end…

In the end, I guess the argument for using FreeAndNil seems to boil down to:

“Of course I use FreeAndNil – it protects against bugs and makes other bugs easy to find, and besides, what’s the harm?”

Well, it would seem that none of those reasons is really true.  The real argument is:

“If your code requires you to use FreeAndNil to reveal and easily find bugs, then your design is wrong.  Good, clean code never feels the need to worry about errant pointers.”

Hey, look: design your code however you like. However, if you were to ask me, I’d say to design your code in such a way that FreeAndNil sends no signal, doesn’t find any bugs any sooner, doesn’t protect against anything, and thus becomes utterly superfluous.

Flotsam and Jetsam #51

By Nick at December 12, 2011 09:51
Filed Under: Delphi, Flotsam and Jetsam, Software Development, Three Sentence Movie Review
  • If you missed CodeRage 6, or you didn’t get to every session that you wanted to see (hear?), it is now all online.  That link also points to the latest offers and ways to find out more about XE2.  I love XE2, and think it’s the best Delphi ever.  And I say that not even using the FireMonkey/cross-platform stuff – so it’s even better than I think.  Winking smile
  • I was digging around in my boxes in the basement – we’ve moved a ton, and so I’ve got stuff scattered all over – and came across a CD labeled “Website”.  I opened it up, and lo and behold, there was a copy of one of my very first web sites, built with NetObjects Fusion.  It was fun to poke around and see some of my really old content.  (As a point of reference, the homepage has “This site was last updated on  Tuesday, December 18, 2001” at the bottom.  Remember when we used to do that?) Actually, I think some of the stuff will end up on my current site.  Winking smile  Not all the links work, but if you’ve been around a while, you might remember some of it.  Most of it was hand-maintained, but you can see where I tried to integrate in some early Delphi-based CGI stuff.   I actually still like the colors and the template.  Winking smile
  • The Generics.Default.pas unit is an interesting one – you may never have cause to use it directly, but it contains a lot of interesting stuff in support of the classes in Generics.Collections.pas.   It’s worth poking around in.  I was doing just that, and came across some interesting code – a function called (and I quote) BobJenkinsHash.  It is used rather extensively throughout the unit, and appears to be a general purpose hashing code.  Who is Bob Jenkins, you may ask?  Well, apparently he’s a guy that wrote a very powerful and useful hash function, and Embarcadero has utilized it as part of their generics library.  And here’s the interesting part – they created it using a set of GOTO(!!) statements whose use , well  -- I seriously can’t believe I’m actually saying this – actually kind of make sense.  The C code depends on the “fall through” nature of C’s switch statement, and the GOTO calls actually mimic that rather nicely.  I’m open to suggestions on how it might have been written better.  Winking smile (Again – I can’t believe I just said that, but there it is.)  And to redeem myself, I’ll chastise the author for not defining his interfaces in their own unit.  (Sorry, Barry – I had to do something to restore my street cred for actually liking the way the GOTO’s worked…..) Anyway, interesting little find in the bowels of the Delphi RTL.
  • I’ve added a new category, Three Sentence Movie Reviews.   I watch a lot of movies, and have all these aspirations of writing up movie reviews when I watch, but I never do because it takes too long.  So I thought I’d simply limit myself to three sentences in reviewing the film, and that way I might actually get the review done.  I might have to get a bit creative – sort of like keeping tweets to under 140 characters.  Should be fun.  If you read this blog via DelphiFeeds, you won’t see it as I’ll not be putting the Delphi category tag on them. Just another reason to subscribe to my real feedWinking smile

Three Sentence Movie Review: Soul Surfer

By Nick at December 10, 2011 23:21
Filed Under: Three Sentence Movie Review

Soul Surfer:  This is a beautiful and touching film about a very courageous young woman, Bethany Hamilton.  You are probably familiar with Bethany, who lost her arm in a shark attack, recovered, and went on to become a professional surfer.  I strongly recommend this film about faith, courage, and determination.

One Right Thing at a Time

By Nick at November 24, 2011 22:44
Filed Under: Delphi, General, Software Development, TechBiz

Wherein I discuss how to do things that you should be doing and how not to do things that you shouldn’t be doing….

Sometimes you tweet something and it makes sense to you, but then you realize that it also kind of begs for more discussion. 

For instance: “Things move so quickly that doing the *one* most important thing means it's less likely that you'll do the wrong things in the long run.” 

I thought that a little more explanation would be in order.  Let’s say you have ten cool features on your “Things Customers are Screaming For” list.  There are two basic approaches you can take to getting them done: You can do them in series or in parallel.  If you do them in parallel, you’ll get them all done sooner, but you may not get them done as thoroughly.  If you do them in series, it will take you longer to do them all, but you’ll likely get each one done more thoroughly.

However, doing them in series – that is, sequentially doing only the most important remaining item – has an added benefit:  It can help you not do things that you shouldn’t do.  You may have ten things on your “We need to get these done right away”, but as time passes, some of those things may prove to be not needed, overtaken by events, or just plain dumb ideas.  Doing things in parallel may mean that you get everything done sooner, but it also means that you might do something that proves to be a waste of time later on.

For example, if you have a team of five folks, and you have five ideas that take six man months each, you might give each person one idea to work on, and then six months later, you have all five ideas done. Great!  But uh oh! -- as it turns out, over the course of those six months, things changed and events transpired in such a way that two of the ideas weren’t really good ideas after all, and at the end of the six months you regret ever starting on them.  So in the end, you have three things done that needed doing, but have wasted your time on two ideas that you should have left undone.  Furthermore, since you only had one person working on each idea, you may not get a fully fleshed out solution, but instead, one that may have missing features or is not complete in some way.

But consider what happens if you work on them in series: say that instead of starting in all at once on the entire list,  you pick the single most important of the ideas on the list.  You focus your whole team on doing that one idea.  You will likely be able to get it done somewhat sooner, say in one or two months instead of the six months in our example. (Five team members working on a six man-month project will likely take a bit longer because of transaction costs.)  In addition, you will get a “five-headed” solution instead of a “one-headed” one, and thus the solution would likely be more complete, fleshed out, and feature rich.  In other words, you might very well end up doing one thing properly and thoroughly instead of doing five things not so completely. 

The added benefit comes when, after doing the most important project, you realize that one of the ideas you had originally thought was awesome isn’t really that awesome, and that you can take it off the list and not waste time on it. You might add another item to the list, or another item that was on the list suddenly becomes vastly more important than it was at the start of the first project.  Instead, you can repeat the process and start working on the next most important thing.  You end up with a very nice implementation of each project you do undertake, and you don’t do the projects that shouldn’t be done.

In a rapidly changing technical environment, that which looks like a no brainer in January might be old news by July.  Obviously you want to avoid working on that project.  A practical example might be that you are a software tools vendor, and people are pressing you to do, say, a development tool for Windows Mobile 6.  You could choose to add staff and get that request done sooner, or you could stay the course and do more important things, only to discover with massive relief that you didn’t do Windows Mobile 6 at all when Windows Mobile 6 becomes a legacy technology.  (Sound familiar? Smile

Now, I’ll grant that if you follow this plan, you’ll end up with fewer features in the long run.   But you’ll also end up with more complete features with less wasted effort.  You won’t have spent time on things you ultimately should not have.  It might take a little longer to get any particular feature to market, but in the above example, you’ll end up with three really solid features and no time spent working on things that you should not have worked on at all instead of five half-baked features, two of which were a waste of time.

Repeat this process enough, and it becomes much more likely that you will end up with a product that has the right – and fully rendered -- feature set.  In many ways, inefficiencies are the result of choosing to do the wrong thing.  If you keep your choices finely grained – that is, always put your efforts only into the things that are obviously the very most important thing to do do right now – you will end up doing the right thing every time, even if there is slightly less of it. 

It’s often been said that knowing what you should do is easy; it’s knowing what you shouldn’t do that’s hard.  If you repeatedly focus on and complete the one single thing you absolutely should do and do it well, it will be more readily clear what those things are you should not do. So, I guess ultimately, you have to choose: More features done less thoroughly with time spent on things that turn out to be a waste, or fewer, more complete features with fewer projects that you shouldn’t have done.

Flotsam and Jetsam #50

By Nick at November 23, 2011 12:32
Filed Under: Delphi, Flotsam and Jetsam, Software Development

Flotsam and Jetsam #49

By Nick at November 09, 2011 13:46
Filed Under: Software Development, Flotsam and Jetsam, Delphi
  • Hallvard Vassbotn has been sighted in the wild! Hallvard is an amazing developer and a great writer, and I’m delighted at the prospect of him starting to blog again, especially given his propensity to stretch Delphi language and RTL features to the limit.  Given all the new things that have happened in these areas since Hallvard’s last blog  post, one can only hope for really interesting stuff.
  • Fun to see people taking up the Dependency Inject mantle – here’s an article by Yanniel Alvarez Alfonso on a simple example of DI using DelphiDean Hill has a very good article about Software Flexibility that discusses how Dependency Injection can make your software more flexible and adaptable.   If my efforts have sparked an interest in Dependency Injection, I couldn’t be happier.  I’ll say it again:  If you aren’t using even the most basic form of Dependency Injection, then you are doing it wrong.
  • ninite.com is a really cool site that provides a valuable and helpful service.  It allows you to create a single install for a pretty broad and selectable collection of popular software.  This is particularly useful when setting up a new machine.  There’s always a million of these things that you want to install – Skype, Chrome, Firefox, your favorite IM client, media players, various utilities, etc. --  and Ninite.com allows you to select all of these and get a single installer for them all.  It does all the “smart” things that you want it to like get the 64-bit version if possible, ensures you have the latest versions -- and best of all -- it clicks all the “Next” buttons so you don’t have to.  Sweet.
  • I tweeted this notion this week -- “Crazy Idea of the Day: Every class that raises an exception unique to itself should have it's own exception type to raise. “ – and I thought that I’d expand a bit on it here.  One of my pet peeves is unclear error messages.  Somewhat of a corollary to that is the irritated feeling you get when an exception is raised, but you can’t tell right away where it came from. Thus was born the notion above – that if your class is raising an exception unique to itself (i.e., not something “normal” like EConvertError or EFileNotFoundException or something like that….) it should be raising an exception type defined specifically for the class itself.  This way, you can put a very descriptive error message in the exception, and the developer or user seeing the exception can know exactly where it came from. In addition, it allows anyone using  your class to easily trap exceptions specific to your classes.  I’ve been doing this for years, but have never seen anyone in the Delphi community really discuss it.
  • Every once and a while, I like to remind folks that they can go to the Delphi UserVoice page and vote for their favorite new features in Delphi.  This is totally unofficial, but it is interesting.  I’m still an admin there, so it’s always fun to mark items done as they get shipped. (I confess that it is also fun to close and/or reject requests that are……. not well thought out…?)  Currently, this item – “Better GUI separation and abstraction” -- is the top voted thing on the whole site, and I’m wondering if that really is indeed what the Delphi community wants the most.  In any event, you can certainly go there and vote and perhaps influence the future of the product. 

Getting Giddy with Dependency Injection and Delphi Spring #9 – One Interface, Many Implementations

By Nick at November 07, 2011 20:27
Filed Under: Delphi, Software Development

So far, we’ve been registering interfaces and implementations in a one-to-one relationship.  Each interface has one implementing class registered against it.  But what if you want to implement an interface many different ways, choosing which implementation to use depending on user input or other external factors?

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

Well, lucky for us, the Spring Container lets us do just that.  The Delphi Spring Framework container registration system allows you to specify a name for any giving implementation registration, thus distinguishing different registrations from on another, even if you register multiple implementers for the same interface. 

If you register multiple implementers for a given interface without specifying a name for each one, then the “last one in wins'”.

So, for instance, you might declare a simple credit card interface as follows:

type
  ICreditCard = interface
    ['{6490640C-0E2B-4F7D-908C-0E6A74DCC0A0}']
    function IsValid(aCreditCardNumber: string): boolean;
    function ChargeAmount(aCreditCardNumber: string; aAmount: Double): Boolean;
  end;

There are any number of credit cards that customers might want to use, so you’ll need to have credit card implementations for the various common vendors:

  GlobalContainer.RegisterType<TVisa>.Implements<ICreditCard>('VISA');
  GlobalContainer.RegisterType<TMasterCard>.Implements<ICreditCard>('MasterCard');
  GlobalContainer.RegisterType<TDiscover>.Implements<ICreditCard>('Discover');
  GlobalContainer.RegisterType<TAMEX>.Implements<ICreditCard>('AMEX');

This code registers four different classes (TVisa, TMasterCard, TDiscover, TAMEX) for the same interface (ICreditCard) via the string parameter on the GetService call.  Once these are registered, you can pick and choose whichever credit card processing class you want as the implementation of ICreditCard.  You can even change the selection at runtime based on, say, user input or different orders being processed, etc. 

For instance, if you have four radio buttons that allow the user to select one of four credit cards, you can do the following:

var
   CurrentCard: ICreditCard

...

procedure TMultipleImplementationsForm.RadioButton1Click(Sender: TObject);
begin
  CurrentCard := ServiceLocator.GetService<ICreditCard>('VISA');
end;

procedure TMultipleImplementationsForm.RadioButton2Click(Sender: TObject);
begin
  CurrentCard := ServiceLocator.GetService<ICreditCard>('MasterCard');
end;

procedure TMultipleImplementationsForm.RadioButton3Click(Sender: TObject);
begin
  CurrentCard := ServiceLocator.GetService<ICreditCard>('Discover');
end;

procedure TMultipleImplementationsForm.RadioButton4Click(Sender: TObject);
begin
  CurrentCard := ServiceLocator.GetService<ICreditCard>('AMEX');
end;

The above code will assign an instance of the appropriate implementing object to the single variable CurrentCard depending on which radio button the user selects.  The proper object is returned based upon the string parameter passed to the GetService call.  That string value, of course, corresponds to the object registered with that same string as shown above. 

Thus, you can register by name and then use as many implementing objects for a single interface as you want.   This is obviously very powerful, as you can choose from any number of implementations as well as add new implementations anytime you want.

A sample application showing this technique as well as some other interesting features can be found in the samples that come along with the Delphi Spring Framework

Fun Code of the Week #2

By Nick at November 07, 2011 15:51
Filed Under: Delphi, Fun Code, Software Development
function RandomString(aLength: Integer; aInputChars: string): string;
begin
  Result := '';
  if Length(aInputChars) <= 0 then
  begin
    Exit;
  end;
  Randomize;

  repeat
    Result := Result + aInputChars[Random(Length(aInputChars)) + 1];
  until (Length(Result) = aLength);
end;

Getting Giddy with Dependency Injection and Delphi Spring #8 – Miscellanea

By Nick at November 05, 2011 14:03
Filed Under: Delphi, Software Development

So far I’ve covered a much of the basics of Dependency Injection.  There’s a lot more to it, and plenty more to discuss, but for this article, I want to stop and discuss a few items that I have kind of glossed over.  So without further ado, here they are in my beloved bullet form:

  • I have been, as you’ve likely noticed, encouraging you to use interfaces when coding, and registering classes as implementing those interfaces with the framework.  What I think I failed to mention explicitly is that all interfaces registered with the Spring Framework have to have a GUID associated with them.  You can add a GUID any time you want into your code by pressing CTRL+SHIFT+G.  If you try to use an interface that doesn’t have a GUID, you’ll get this error:  “Project <projectname>.exe raised exception class ERegistrationException with message 'Non-Guid Interface Services are not supported.
  • If you’ve looked closely at the code in the demos, you might have noticed that before you can do anything with the Spring Container, you need to call GlobalContainer.Build;  This method needs to be called before you can get anything out of the ServiceLocator.  The Build method is the code that gathers up all the registered classes and either creates them or enable them to be created on demand, depending on the lifetime type that you have selected.  If you get the error 'LifetimeTypeManager was expected.' when you run your app, it likely means that you have faced to call Build on your container.  And in fact, the Build method is really the main purpose of your DI Container.  You should call Build once, and at the root of your application.  For Delphi developers, this means that it probably ought to be called as one of the very first things in the DPR file. This also means that you need to register your classes as early as possible as well.
  • You don’t have to use the Global Container and the Service Locator provided by the framework.  You are more than welcome to create your own and expose the functionality as you want.  What we have done here at Gateway Ticketing is to declare an interface that is a complete abstraction of the notion of a DI Container, and then implement the interface ourselves using a TContainer descendant from the Delphi Spring Framework.  That way, if the framework changes (and it has since we started) or if we even decide to use a different container, our code is completely decoupled from any particular implementation.  Just another great example of “Code against abstractions, not implementations.” Smile
  • I feel compelled to point out that the whole concept of a Service Locator is considered an “anti-pattern” by some. I haven’t come to a firm conclusion on this issue myself.  Yes, a Service Locator is almost always a Singleton, but I personally don’t view read-only singletons to be bad as do some.  (A read-write singleton is really a global variable, and I think we can all agree that global variables are the Spawn of Satan.) However, there appears to be some dispute as to whether the use of a container is indeed a Service Locator. Also, if all of your dependencies are defined before execution is available to the user, then is a Container really a variable at all?  It remains a matter of debate. Ultimately, I guess I view a Service Locator as so valuable and useful so as to out-weigh any of the drawbacks they might have. 
  • There is a weakness here -- and which gets to the previous point – in that things are actually so decoupled and late-binding is so explicit that it is indeed possible to get a successful build and not know that you forgot to register a needed implementing class until runtime.  And, in a complex system, it might be a long time before anyone notices that the implementing class for a seldom used interface is missing.  If you follow the pattern that I have shown of registering an implementation in the initialization section of a unit, then you must use that unit somewhere in your app to actually have the registration take place. And as mentioned, if you forget to add it, and don’t actually include that unit in your app, the compiler won’t tell you and you will only find out at runtime.  This is a weakness and you need to be very careful to ensure that you don’t fall into this trap.  Strategies might include a single unit for doing all of your registration, or some type of static analysis that ensures that every call to GetService has a corresponding RegisterService call (or whatever your methods are called).  Something to be aware of.

Those are just a few things that you might want to consider as you integrate Dependency Injection into your coding techniques. I’ve said it before, and I’ll say it again:  If you aren’t doing Dependency Injection, you're doing it wrong. 

My Book

A Pithy Quote for You

"We all want progress, but if you're on the wrong road, progress means doing an about-turn and walking back to the right road; in that case, the man who turns back soonest is the most progressive."    –  C. S. Lewis

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