Escape from chain of Assigned() in Delphi

Viewed 227

Sometimes I see in source code long chain of checks by Assigned() in deep of object like

if Assigned (ASomeObj)
   and Assigned (ASomeObj.Session)
   and Assigned (ASomeObj.Session.UserInfo)
   and Assigned (ASomeObj.Session.UserInfo.SomeFactsList)
then
  // to do some actions

It's the way to check by nil all intermediate entities. Maybe anybody knows a way to cropping chain in condition part?

As an idea a watched to

try
  if Assigned (ASomeObj.Session.UserInfo.SomeFactsList)
  then
    // to do some actions
except

end;

Whether exists paths to simplify it? How it is clear and easy for reading source code?

As I know in Csharp exist "?" operator for using like ASomeObj?.Session?.UserInfo?.SomeFactsList for check by Null

1 Answers

TL;DR There's no such operator in Delphi language and I don't think we'll get it anytime soon. But there are some good practices as a way around it. Read more ...

Let's start from the bottom of your question.

As I know in CSharp exist ? operator for using like
ASomeObj?.Session?.UserInfo?.SomeFactsList for check by null

First of all there is no ? operator in C#, but there are some that have ? in them:

You were obviously referring to ?. a.k.a. safe navigation operator or even

Elvis operator

There's no such operator in Delphi language and I don't think we'll get it anytime soon considering that there's not even true ternary conditional operator yet:

  • RSP-12100: Add a ternary operator to the Delphi language
  • RSP-14621: Proposed syntax for ternary operator

You're not the only one asking for it - there's an open feature request to add support for null-conditional operator (RSP-21323).

FWIW: Oxygene language from RemObjects Software (disclaimer: no relation) has colon operator for this purpose.

Where do we go from here? I would first recommend you to re-think your design (as it was pointed out by the comments under the question).

Let me quote from Just Say No to Nulls (or Refactoring Your Way to Programmer Bliss):

The truth is, when we find ourselves wading through endless object hierarchies such as these, that there is what we call a code smell. And it’s a pretty good indication that we might want to revisit our design. A true OO design is composed of nice little well behaved classes that expose methods we can call on to have them do things for us. These classes abstract the nitty gritty behind the scenes details and just do it (often without the need to return any value at all).

dog.bark() not dog.getAnatomy().getVoiceBox().EmitSound("woof")

Another option would be to make the intermediate objects not nil using Null object pattern. That would help you get rid of chained Assigned checks.

Cheap and dirty solution would be to introduce shorthand property SomeFactsList or class helper directly on ASomeObj so at least you wouldn't need to repeat yourself all over the place, if you have.

Further reading:

Related