Nulls and Nullable Types in Delphi

ESBPCS has always supported Nulls via our Components – even those that are not Data Aware. I lectured a fair bit on Database Design in the early ’90s and emphasised the need and value of Nulls in Databases. Whilst we have had Null handling in our Edit Components since before we released ESBPCS, we didn’t have a nice way to handle them outside of the components.

One of the things we wanted to do with the redesign for ESBDevLib is to make much more use of Generics. We did “play” with some Nullable Type approaches back in the early Delphi days, but they were far from intuitive and we left them on the back burner. I have also liked Operator Overloading since I taught some Ada units back in the ’90s.

Now we can combine Records, Generics and Operator Overloading to supply a Nullable Type for use in ESBDevLib – for both VCL and FMX. C# has Nullable Types built in – and I need to play a bit more with them to see if it is worth adding our Nullable Type to the .NET version.

Our work here has been also be inspired by Jeroen Pluimers (worth following Jeroen’s blog ) – plus Jim McKeeth and Allen Bauer have also made worthy contributions to the dialog on Nullable Types in Delphi.

So basically we have a record:

type
 Nullable<T> = record
{$ENDREGION}

And we add Properties for IsNull and Value and overload the various Comparisons and Assignments.

We also create some Date Type specific Nullables:

type
 NullableString = Nullable<string>;
 NullableInteger = Nullable<integer>;
 NullableInt64 = Nullable<Int64>;
 NullableDouble = Nullable<Double>;
 NullableSingle = Nullable<Single>;
 NullableCurrency = Nullable<Currency>;
 NullableDateTime = Nullable<TDateTime>;
 NullableRefDate = Nullable<TEDLRefDate>;
 NullableRefDateTime = Nullable<TEDLRefDateTime>;

So we can assign Nil to our Nullables, check to see if they are Null, and assign values:

var
  X: Nullable <Integer>;
begin
  X := nil; // X is Null;
  if X.IsNull then
    // Do stuff if X is Null.
  X := 5; // X is 5

We are also allowing the Value in our Data Type Specific Edits to be accessible (both ways) via Nullable Types.

So as we continue, we will look at ways to better use Generics and other recent Delphi Features to make Data Handling and Manipulation even easier 🙂

About esbglenn

Software Developer working at our Family owned business, ESB Consultancy, which is located in Kalgoorlie-Boulder, in the Eastern Goldfields of Western Australia.
This entry was posted in Beta Development, Generics and tagged , , , , . Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.