Amazon.com Widgets December 2011

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.

My Book

A Pithy Quote for You

"There are no such things as limits to growth, because there are no limits to the human capacity for intelligence, imagination, and wonder"    –  Ronald Reagan

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.