4

I'm following along in Pawel Glowacki's Expert Delphi book. On page 98 he has the following onClick event handler:

procedure TFormFavJSON.btnReadDOMClick(Sender: TObject);
var
  favs: TFavorites; valRoot: TJSONValue;  objRoot: TJSONObject;
  valFavs: TJSONValue;  arrFavs: TJSONArray;
begin
  favs := TFavorites.Create;
  //
  // Several lines of code omitted
  //
  favs.Free;
end;

However when I type .Cre and use the code completion Ctrl + Space the IDE completes the code with a set of empty parenthesis.

favs := TFavorites.Create();

So which of the following is the most correct?

  favs := TFavorites.Create;
  favs := TFavorites.Create();

3 Answers3

9

They're both equally correct. Object Pascal allows you to omit the parentheses when the procedure or method requires no parameters, but also allows you to include them. It's up to you which you prefer.

David Heffernan
  • 601,492
  • 42
  • 1,072
  • 1,490
Ken White
  • 123,280
  • 14
  • 225
  • 444
  • `It's up to you which you prefer.` - unless there are direct semantic implications for choosing one expression over the other. They are not always equivalent. – J... Feb 09 '19 at 16:54
8

Makes no difference. Pascal allows either syntax. I prefer without parentheses when there is no need.

user3701103
  • 157
  • 1
  • 8
  • 7
    There is a difference when assigning to a procedural type though, parentheses guarantees a call. You can't write, f.i., `favs.OnChange := favsChange();`. Some prefer the parentheses when it's a call for that reason. – Sertac Akyuz Feb 09 '19 at 01:36
  • 6
    Actually, Pascal does not allow both. It's the Delphi language that does. – David Heffernan Feb 09 '19 at 07:24
3

They are the same, and both correct. But if you use the constructor with arguments, the parenthesis is more helpful.

Vu Tong
  • 31
  • 1
  • 5
  • 5
    "*if you use the constructor with arguments, the parenthesis is more helpful*" - more accurately, the parenthesis are **required**, not merely "helpful". – Remy Lebeau Feb 09 '19 at 02:30
  • 1
    Oh, it seems that my way of speaking has a bit of a problem. Follow me, **helpful** means you can type faster. If code completion does not generate parenthesis you will have difficulty with constructors with arguments. – Vu Tong Feb 09 '19 at 03:42