Pages

Advertisement

Wednesday, July 4, 2007

Interesting Nil Reference Quirks in Delphi Code

So here’s an interesting question. Why does the following code not blow up if x is nil?

FreeAndNil(x);

The Free method of TObject that is called by FreeAndNil does the check for nil before doing the destroy. The discussion on the Delphi.non-tech newsgroup on this topic led to some interesting discussion.

Assigned does the same thing as testing for nil (except for method pointers. See Allan Bauer’s post about this). Here is the Delphi help entry on Assigned:

Assigned Routine Tests for a nil (unassigned) pointer or procedural variable.

Unit System

Syntax

[Delphi] function Assigned(var P: Type): Boolean;

Description Use Assigned to determine whether the pointer or procedure referenced by P is nil. P must be a variable reference of a pointer or procedural type. Assigned(P) corresponds to the test P<> nil for a pointer variable, and @P <> nil for a procedural variable. Assigned returns false if P is nil, true otherwise.

Note:

Assigned can't detect a dangling pointer--that is, one that isn't nil but no longer points to valid data. For example, in the code example for Assigned, Assigned won't detect the fact that P isn't valid.

In the FreeAndNil method you find this code:

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

In the TObject.Free method you find this code:

procedure TObject.Free;
begin
  if Self <> nil then
    Destroy;
end;
 

That means you can call free on a nil reference and it will NOT give you an access violation, or try to free the object a second time. Since you can call Free on a nil reference, you can also call FreeAndNil on a nil reference. Furthermore you can call it over and over again if you want. The following code never produces any access violations or invalid pointer operations:

T: TObject;

T := nil;

T.Free;

FreeAndNil(T);

T.Free;

After the variable is set to nil, no combination of Free or FreeAndNil will cause any problems whatsoever. So there is no need to test for nil before freeing a variable. It is a waste of time. The two following lines are exactly the same:

FreeAndNil(T);

If Assigned(T) then FreeAndNil(T);

If you don’t believe it, try it yourself. The key is in one line of the TObject.Free method, that might look odd. You can actually use this same odd code in your own code to make nil-safe objects, but we’ll get to that in a moment. Here we go:

if Self <> nil then

That line of code inside the Free method of TObject keeps the method from AVing, even though it looks from the calling code like an AV might be inevitable. Surely, some of you must be thinking that T.Free will AV long before it gets into the Free method because T is itself nil. But it doesn’t. Why is this? Now we are getting to the part I was re-learning. Delphi book author Jon Shemitz explained it in a newsgroup post when he said:

In message <4540f380.53de8de6@midnightbeach.com>, Jon Shemitz wrote:

> theo wrote:

>

> > if Self <> nil then ..

> >

> > Can somebody explain? How can you call MyObject.free when MyObject is nil?

>

> It's pretty simple, really: TObject.Free is not virtual, so MyObject

> is not referenced when you call Free. Rather, the object code simply

> reads the current value, and passes it to the method as the Self

> parameter.

>

> You can call any instance method with a Nil reference, and everything

> will be fine until the method refers to an instance field or calls a

> virtual method, at which point you are dereferencing Nil, and you'll

> get an exception.

>

> By contrast, when you try to call a virtual method using a Nil

> reference, you get an exception at the call point.

So, the explanation is that because TObject.Free is NOT a virtual method, it therefore can be safely called from a nil reference. This is very interesting. I wrote a little bit of code to demonstrate this principle:

unit Unit6;
 
interface
 
uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls;
 
type
  TForm6 = class(TForm)
    Button: TButton;
    procedure ButtonClick(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
  end;
 
    TFunWithNils = class
  private
    FProtectedProperty: Integer;
    function GetProtectedProperty: Integer;
    procedure SetProtectedProperty(const Value: Integer);
  public
    ADataField: integer;
    procedure NonVirtualMethodAccessingDataField;
    procedure IsAVirtualMethod; virtual;
    procedure NotAVirtualMethod_Protected;
    property ProtectedProperty: Integer read GetProtectedProperty write
        SetProtectedProperty;
  end;
 
 
var
  Form6: TForm6;
 
implementation
 
{$R *.dfm}
 
procedure TForm6.ButtonClick(Sender: TObject);
var T: TFunWithNils; W: integer;
begin
  T := TFunWithNils.Create;
  try
    T.NonVirtualMethodAccessingDataField;
    T.IsAVirtualMethod;
    T.ADataField := 5;
    FreeAndNil(T);
    T.NotAVirtualMethod_Protected; //NEVER AV'S
    T.ProtectedProperty := 7;      //NEVER AV'S
    W := T.ProtectedProperty;      //NEVER AV'S
    FreeAndNil(T);                 //NEVER AV'S
    T.IsAVirtualMethod;            //ALWAYS AV'S RIGHT HERE
    T.NonVirtualMethodAccessingDataField; //ALWAYS AV'S INSIDE METHOD CALLED
    T.ADataField := 5;             //ALWAYS AV'S RIGHT HERE
  finally
    T.Free; //<----never AV's here because T is already nil by this point
  end;
end;
 
{ TFunWithNils }
 
function TFunWithNils.GetProtectedProperty: Integer;
begin
  if self <> nil then
    Result := FProtectedProperty
  else result := 0;
end;
 
procedure TFunWithNils.IsAVirtualMethod;
begin
  if Self = nil then exit;
  ADataField := 5;
end;
 
procedure TFunWithNils.NonVirtualMethodAccessingDataField;
begin
  ADataField := 5;
end;
 
procedure TFunWithNils.NotAVirtualMethod_Protected;
begin
  if Self = nil then exit;
  ADataField := 5;
end;
 
procedure TFunWithNils.SetProtectedProperty(const Value: Integer);
begin
  if self = nil then
    exit;
  FProtectedProperty := Value;
end;
 
end.
 

I’d advise playing with this code a bit, commenting out lines that get AV’s to see the next ones that get AV’s. You’ll discover that the rules are

1) nil references to virtual methods AV right at the point of access

2) nil references to static methods AV inside the static methods as soon as they access a data field or a virtual method of the class

3) nil references can always be freed without consequence

4) nil references to a data field AV right at the point of access

If you think about the consequences of this a little bit you will soon realize that one could construct a class that is nil-proof, meaning that you could dereference nil references to this class without ever getting any AV’s. The way you would do it is by using only non-virtual methods, each of which has a

  if self = nil then
    exit;

as the first line. For data, you would use properties whose accessor and getter methods are protected in the same manner as the class above. The key is to write it so that no fields or virtual methods are accessed until after self is tested for nil. Then, as long as you nil a reference once you’ve freed it, you would not have to worry about double-frees, AV’s from dereferencing nils, etc. Dangling pointers are still a possible problem though, if you make copies of pointers. The only real cure for them is to either disallow copies of references or require them to always be passed as var parameters to procedures, so that when they are FreeAndNil’led in the procs, they are thereby nilled in the calling code as well.

ReSharper 3.0

ANTS Profiler from RedGate Software is one my favorite tools since day one. Recently, I downloaded ReSharper 3.0 and it has found a place in my Toolbox already.

I like this part -

From the beginning, ReSharper has excelled in analyzing code on the fly. In addition to finding and highlighting errors, warnings, and warning-type situations in your code, now we've trained it to understand your code even deeper. ReSharper offers code suggestions - critical analysis of possible flaws in code design - with suggestions to improve them - all while you type.

Check out here for more details and free trial

.NET 3.0 and Beyond – Heading to Project Unknown?

Here are some points to consider in .NET 3.0 and 3.5.

  1. Scripting over procedural and object-oriented is the case in XAML.
  2. Pointers were NOT added to C# 1.0 but heavy use of generics adds same level of difficulty to C# 2.0 and 3.0. If you are planning to use LINQ (you will have no choice), you can’t bypass generics and attributes.
  3. Harcoded recordsets are back in form VC++ to C# in form of attributes. For example, if you have a Customer class link to a Customer table in database in LINQ and later you add or change a column type, you will have to go back to your code and change the class.
  4. Anders (father of C#) is pushing too much Mathematics in new versions of C#.


Problem with LINQ versus ADO.NET

So far, ADO.NET provides me more flexibility where I don’t have to hard-code my classes based on tables, columns, and their types. Generics are used in LINQ instead. Generics sound generic but actually they are not. Instead of using a DataSet or a DataTable, I have to use a class name, which is hardcoded. In other words, if I have a Customer class linked to a Customer table, I can’t use that for an Order table in the database.

LINQ supports SQL Server database only.

I am still confused about underlying technology is used in LINQ to connect to the database? Is this one of the existing – ODBC, ADO.NET etc or something new?

One of the biggest problems with LINQ I see is no Server side support. Let’s say, I have 1 million records in a table and need only 10 records, I can write a stored procedure and pass some parameters to SP and can filter the records. It makes code more managed and cleaner. Now using LINQ queries, I will be writing SQL in my code and put all looping and filtering in my code. Result? More and more messy code.

In current scenario, if I have a programmer who is not good at database side, I have DBA take care of efficient SPs and let programmer talks to the database via SPs only. Every thing else is hidden from the Programmer. BUT with LINQ, programmers have control over the whole selection process. Result? More and more messy code.

Here is good comparison of various technologies with LINQ, but again, how many developers really need Object-Relational DB objects mapping?

http://msdn2.microsoft.com/en-us/library/aa479863.aspx

Making Money Through Adsense Firefox Referrals: A Look at Explorer Destroyer

I’ve only recently come across Explorer Destroyer, an interesting website which helps you to make more money from Adsense by switching users from Internet Explorer to the Firefox browser.

As you probably already know, Google’s Adsense referral program will pay you $1 for every person who downloads Firefox from your referral link.

Explorer Destroyer expedites the task of getting more Firefox referrals by offering a free script that allows you to automatically promote Firefox to IE users visiting your website.

Once the script is installed, a message which sells the benefits of using Firefox (along with your referral link) will appear to IE users when they visit your website or blog.

There are three types of settings for the script, depending on how aggressively you want to push for conversions. Installation instructions are clearly provided at the Explorer Destroyer website.

Level 1 will make IE visitors see a message across the top of the page, encouraging them to download Firefox.

level-1.jpg

Level 2 will direct IE Visitors to a splash plage with a download link and a link to continue to your site.

level-2.jpg


Level 3 will not allow anyone using IE to access your website. A splash page is shown instead with a Firefox download link. This seems to go against Google’s TOS, so you’ll have to use a regular, non-Adsense referral link instead.

level-3.jpg

It is interesting to note that Explorer Destroyer was started by a team of four people with the sole aim of overturning Microsoft’s dominance over the web browser market. Their manifesto offers more clues into Explorer Destroyer’s mission:

Firefox is one of the most important software applications in the world because it can play a big part in determining the future of the web. It is crucial that an open-source, standards-based web browser becomes the most popular browser, and Firefox has a shot at being that.

We’ve spent days fixing computers of our family members that have been hobbled by spyware that Internet Explorer allowed in. These annoyances alone more than justify a aggressive campaign to switch people to Firefox.

But what really matters is putting the internet back in the hands of the public and ensuring that the technology that will remake so much of our world in the next 30 years is a public resource not a corporate one.

The Explorer Destroyer idea does seem like it would lead to more Firefox downloads, although it seriously affects web usability because it interrupts the viewing experience of all visitors to your site.

Level 1 of the script setting is the least intrusive and will probably be the only one that is doable for most blogs or websites. Level 2 and 3 might be more successful in getting sign-ups but they will most definitely drive visitors away from your site as well.

See this parody website for an alternative perspective on Explorer Destroyer’s campaign to win more Firefox users.

I haven’t seen any other websites using the script so I’m not 100% sure if the script still works. If anyone has used it before or am currently using it, do leave a comment to let us know if it still works.

Update: According to various readers, the script apparently still works and you can try to download it from Explorer Destroyer’s website.

The Ultimate Beginner’s Guide to Effective Adsense Link Units Optimization

Most webmasters and bloggers make money from their website through Google Adsense and I’ve noticed that not all of them include Adsense link units as part of their contextual monetization strategy.

It’s useful to note that Adsense link units can and will help you to generate more income from your website, if you are able to integrate them perfectly within the overall site design and layout.

Google has recently updated their Adsense program policy and publishers are now allowed to place three link units on a single page instead of just one:

As we’ve noted in the past, link units are a great way to provide relevant, user-friendly ads in hard-to-fit locations on your site. With the new opportunity to place three link units — and the plethora of link unit formats — we hope you’ll find great ways of incorporating this unique ad format on your site.

While this change won’t drastically improve your monetization potential, it does offer more placement options for publishers. I thought would be helpful to create a basic primer on how to use Adsense Link Units for your own website or blog.

If you’ve never used link units before, this might be a good time to experiment and find out how they work for your website and monetization goals.

What are Adsense Link Units?

Basically, link units are simply a collection of four to five links within a horizontal or vertical format. When clicked, each of these links will open up into a webpage that consists of nothing but Google ads.

adsense-link-unit.gif

Characteristics of the Adsense Link Unit

* Link units are unobtrusive. They do not take up much space and can be easily integrated into any single webpage. Their small size and design will not affect the viewer experience of content on your website.

* Link units do not seem like ads. Unlike other contextual ads, link units can be skillfully blended to look like navigational units on any website. This increases the possibility of click-throughs.

How do you Make Money with Adsense Link Units?

Unlike other Adsense ad units, you’ll only make money when the visitor clicks on the link unit and then clicks on any link within the link page. In other words, you’ll need two visitor clicks before you actually make any money.

This means that, in order to maximize your earning potential, you’ll need to get as many people to click on the link units as possible in the hope of receiving a larger percentage of second clicks.

The link units earnings model simply emphasizes the importance of ad blending and placement. From my experience with link units, I believe that one can easily see a decent number of ad clicks if your link unit is well blended on your site.

Setting up Adsense Link Units for your Website

First of all you’ll need to signup for Google Adsense if you haven’t already done so. After which, log into your account and then click on Adsense Setup and then Adsense for Content. You’ll come to the following screen:

adsense-linkunit-screen.jpg

Select the Link Unit and click Continue. You’ll then be able to choose a horizontal or vertical link unit while determining the number of links that will show up in each unit.

After which, you’ll have the option of setting up a channel to track the performance of the link unit. Create a channel by clicking on the Add New Channel link at the bottom of the screen and give it an appropriate name that suits your site.

adsense-linkunit-channel-setup.jpg

And you’re done! Just copy the code to your site template and the link units should show up immediately.

Optimization Guidelines for Adsense Link Units

Most of these optimization tips apply to Adsense ad units as well so they may not be new to you:

* Text color for the link unit should be the same as the link color for your website.

* Remove the ad borders and ensure that the background color matches your site. This will increase the potential for blending and clickthroughs.

* Above the fold placement or placement of link units near the top of any webpage will work best for link units.

* Avoid Ad Congestion and clutter. Link units should not be placed too closely to other advertisements because they may be easily overlooked by visitors. Link units work best when placed to navigational links or as standalone units.

* Optimize for Search Traffic. Link Units work best with visitors from search engines and should be placed on pages which receive the most consistent search traffic, even if you don’t want to use them on a site wide basis.

* Use Ad Channels. Ad channels allow you to measure the performance of each link unit you use and allows for comparative analysis. Essential if you want to know which link unit to drop and which to maintain.

* Mirror your site link structure. One useful method to improve your link unit click through rate is place your link unit beneath or beside your on-site navigational links. This conceptually makes them blend in extremely well although they may confuse visitors.

Four Link Unit Placement Examples

Adsense link unit placement can be broadly divided into four formats, each involving different usages of both horizontal and vertical link units.

I’ve included several screenshots of each format and have included a brief commentary on how you can use them for your own website.


1. Horizontal Link Units as Menu/Navigation Links

horizontal-adsense-link-unit.jpg

adsense-horizontal-link-unit-header.jpg

In my opinion, this is by far the best way to use link units because they do appear to be exactly like menu links and will attract navigational clicks from visitors who are trying to find more information from your website.

You can include the link units within your header, just beneath your header or only on individual webpages or blog post pages. The key point is to keep them above the fold to ensure maximum visibility.


2. Horizontal Link Units as Footer links

adsense-link-unit-footer.jpg

Footer link units are the most unobtrusive and will attract clicks from visitors who browse or scan your website from top to bottom. They can be a useful addition to other link units placed above the fold.

I’ve used horizontal link units as a footer link on Dosh Dosh for about a week and the results have been rather satisfying, given its almost indiscernible placement on the homepage.

I initially put them up as an experiment and I have found that this link unit makes me a few dollars a day, which is not too bad at all.



3. Vertical Link Units as Category Links

adsense-vertical-link-unit.jpg

adsense-link-unit-vertical.jpg

I’ve seen some blogs and websites use vertical Link Units as some sort of a category unit in their sidebar. I think these vertical ad units generally perform poorly in comparison to the horizontal link units, which are more well blended and less ad-like.

Unless you’re willing to create a linking structure similar for the link units (see the first screenshot on top), they are likely to stand out like a sore thumb.

Then again, the vertical link unit’s performance may depend on your actual site design and layout so you’ll need to test them to see if they do attract ad clicks from visitors.



4. Vertical Link Unit within Content

adsense-link-unit-within-content.jpg

adsense-link-unit-within-content-1.jpg

I’ve come across very few websites which include a link unit within actual content of a web page and I always wonder how they are performing for these publishers.

Most webmasters would rather include an Adsense ad rectangle instead of a link unit because it only provides one click earnings, instead of the two-clicks which you need from link units.

Giving up a prime in-content spot to link units is such a good idea, not to mention that it’ll add to the overall clutter of your webpage.

Disadvantages of Adsense Link Units: Factors to Consider

Some have suggested that very well-blended Adsense Link Units are unethical because they can be made to appear as legitimate navigational links which have a high chance of inducing clicks from visitors who are searching for information on your site.

A visitor might click on the link thinking that it is a category or menu button of some sort, only to be led to a Google Adsense page full of links.

While the links might be relevant to the link unit text and your site, some visitors might not like the feeling of being ‘tricked’ when they click on the link unit.

Another issue to consider is that these link units are exit points which siphon traffic away from your site. Instead of browsing more pages on your site, a visitor might click on a link unit and then click on another link to be led to another site.

The visitor might not return to your website again and the likelihood of this is higher if they are led to a page full of ad links which point to similar websites or even your immediate competitors.

Experiment, Document and Evaluate.

As many have mentioned before, experimentation and analysis is the best to way to ensure that you’ll make money with Adsense. You need to put up ads and measure them over time to assess their performance.

Don’t be reluctant to tweak your ad placement to see if you can achieve higher click through rates. Only by experimenting with different ad formats and placement positions can you find an format that will bring you the most potential for profit.