Jump to content
Ian Branch

Getters & Settters??

Recommended Posts

That information about memory management is at least 20 years old. That's why I wrote that now it's probably irrelevant

Share this post


Link to post

@David Heffernan - I write about my own preferences, based on my own code, the libraries I use, and the experiences I've had. 

I am not trying to recommend a "one right way" to write code, since there are so many considerations depending on the context. 

 

Which part of "I prefer" do you consider to be a generally invalid point?

Share this post


Link to post
23 hours ago, Stano said:

I remember that the number of arguments 3 is related to memory management.

There is a limit to how many parameters can be passed in registers (faster) vs. on the stack. But that limit also depends on the parameter type and apart from really time critical code you should simply ignore this possible issue, because other considerations are far more important.

Share this post


Link to post
On 11/6/2022 at 7:35 AM, Dalija Prasnikar said:

TFoo = class

protected

FValue: Integer;

published

property Value: Integer read FValue write FValue; end;

Hi Team,

I have set some properties per the above guideline.

Is it correct, or have I missed something, that the property ' Value' only becomes visible/usable at Form Show, no sooner?

It doesn't seem to be available at Form Create.

 

Regards & TIA,

Ian

Share this post


Link to post

Depends on when you create an instance of TFoo. Unless I am missing something.

Share this post


Link to post

Mark,

Ahh good point.  TFoo is created in another form, a value assigned to the property and then the form shown with a ShowModal.

  //
  var Foo := TFoo.Create(nil);
  //
  Foo.Value := 46547;
  //
  try
    Foo.ShowModal;
  finally
    //
...
...

 

Edited by Ian Branch

Share this post


Link to post

Actually I can answer my own question.  Stepping back, I can see that the Foo.Value isn't part of the Create, it is added after, therefore it can only be 'visible' at ShowModal.

All good now.

Share this post


Link to post

in "forms", you can try use "AfterContruction" event to init some value! Same that the "form" is not "ready" for use, but you can access the fields or others if the instance is ready!

in "inheriting" case, it's necessary look with more attention of calls order :<

--> a lazy debug help... create a new form with all events called and see how it happens (who is called at first...)?  OnCreate or AfterConstruction?  (try with this events "overrided")

 

Edited by programmerdelphi2k

Share this post


Link to post
6 hours ago, Ian Branch said:

Actually I can answer my own question.  Stepping back, I can see that the Foo.Value isn't part of the Create, it is added after, therefore it can only be 'visible' at ShowModal.

All good now.

Not true. FValue, in your example, is available as soon as the instance has been allocated. Realistically the earliest you get to use it is inside the constructor. 

  • Like 2

Share this post


Link to post

ordem to calls: Form1: Loaded, Create, AfterConstruction, FormCreate, FormShow... if there is not others on process, of course!

 

01 - Create event (before "Inherited") - Self = NOT nil
02 - Create event (before "Inherited") + FValue (Private field on form)= hello world
03 - Loaded (before "Inherited")
04 - Loaded (after "Inherited")
05 - Create event (after "Inherited")
06 - Create event (after "Inherited") - Self = NOT nil

07 - AfterConstruction, before "Inherited"
08 - FormCreate event (before "Inherited")
09 - FormCreate event (after "Inherited")
10 - AfterConstruction, after "inherited"
11 - FormShow event (before "Inherited")
12 - FormShow event (after "Inherited")

 

 

type
  TForm1 = class(TForm)
    Button1: TButton;
    Memo1: TMemo;
    procedure FormCreate(Sender: TObject);
    procedure FormShow(Sender: TObject);
    procedure Button1Click(Sender: TObject);
 private
    FValue: string;

 public
    constructor Create(AOwner: TComponent); override;
    procedure Loaded; override;
    procedure AfterConstruction; override;
  end;

procedure TForm1.Loaded;
begin
  WhoIsFirst(LText, 'Loaded (before "Inherited")');
  inherited;
  WhoIsFirst(LText, 'Loaded (after "Inherited")');
end;

constructor TForm1.Create(AOwner: TComponent);
begin

  FValue := 'hello world';

  //
  WhoIsFirst(LText, 'Create event (before "Inherited")');
  inherited;
  WhoIsFirst(LText, 'Create event (after "Inherited")');
end;

procedure TForm1.AfterConstruction;
begin
  WhoIsFirst(LText, 'AfterConstruction, before "Inherited"');
  inherited;
  WhoIsFirst(LText, 'AfterConstruction, after "inherited"');
end;

procedure TForm1.FormCreate(Sender: TObject);
begin
  WhoIsFirst(LText, 'FormCreate event (before "Inherited")');
  inherited;
  WhoIsFirst(LText, 'FormCreate event (after "Inherited")');
end;

procedure TForm1.FormShow(Sender: TObject);
begin
  WhoIsFirst(LText, 'FormShow event (before "Inherited")');
  inherited;
  WhoIsFirst(LText, 'FormShow event (after "Inherited")');
end;

Edited by programmerdelphi2k

Share this post


Link to post
On 11/5/2022 at 12:20 PM, Ian Branch said:

Can some one point me to a plain English explanation of what Getters & Setters do and how they do it.

Do I need both a Getter & a Setter for the functionality to work?

 

 

If there's anything you take away from this discussion, it should be that understanding Properties (with their getter and setter methods) is helpful, but when you get into discussions involving passing data in and out of Forms, it usually turns into something more akin to a religious debate.

 

There are lots of common practices that apply to interacting with classes, starting with the basic principles of "objects" which are: encapsulation, inheritance, and polymorphism.

 

The whole point of classes is twofold: (1) model behavior; and (2) maintain state. In most GUI-based apps, a form's behavior is going to vary with how it's used: maybe to simply display a message; get an input value; display and/or edit some data; and more complex forms that combine several of these.

 

However, there are several ways to get and set the state (field values) inside of that form class. Worse, the way people employ these methods is very inconsistent, which can be observed by looking at a lot of different code written by may different people.

 

Properties are properties, and Dalija did a great job explaining them. The "why" part wasn't really addressed: it's because properties afford the programmer some latitude in terms of 'encapsulation'. For instance, you put 'i' and 's' in front of some property names to clue the programmer into how they're used (handy if you're not using an IDE that already ensures the types match up). The point here is, right now you might have implemented those as one type that makes sense today; but in a month or a year down the road, it might make sense to change those types or where the values are stored. And that's where Getters come in -- they enforce the promise that the property is whatever type you say it is, regardless of how it occurs inside the class. So an integer could change to a string, or vice versa, because of some other change. If you accessed that variable directly by name, and its type changed, that could have incredibly wide-ranging repercussions on the rest of the application. But by using a property that says CustomerNum (with or without an 'i' in front) is always an Integer, you don't have to worry about whether the underlying variable changes to a string or a field in some other record or object -- references to CustomerNum will always refer to an integer. Even if you replace it with a DB query.

 

As for Setters, they have a totally different set of uses that can be equally important. Their main use is to ensure the integrity of the internal state of the object. If the state of a given variable can only have three distinct values, you'd use a Setter to make sure it isn't assigned something else, which can cause problems for the behavior of the entire object later on. So the Setter can act as a sort of "door bouncer" to keep disreputable characters out of the club, so to speak. 

 

That's the "why" part in a nutshell. Here's where we get into what's behind the religious debate part...

 

In Delphi, a "form" is a TForm which is a class derived from something in the VCL that's intended to act as a container for visual components -- hence VCL = Visual Component Library.


When you create a 'class' in Delphi, it inherits from TObject and it's pretty much a blank slate. You get to define what's in it and how its clients are supposed to use it.

 

When you create a 'form' in Delphi, it's actually a TForm, a class in itself, and it's FAR from a blank slate. It's part of a complex inheritance tree and it acts as a container for VCL components that depend on things present in the TForm inheritancy hierarchy. This imposes a bunch of fixed rules as well as guidelines to follow, some of which are required and some optional.

 

How you get data into and out of a form should be guided by how you do that with any other class. However, in practice, people tend to not follow those rules very much. And you can tell from all of the back-and-forth between different folks here that some hold rather strong opinions about what to do and not do.


I did a presentation for CodeRage 9 where I discussed this very topic in some detail, entitled "Have You Embraced Your Inner Software Plumber Yet?"

 

 

 

The essence of this presentation is that getting data in and out of forms is more aligned with the whole domain of Dependency Injection than anything else. Unfortunately, when people hear that term, they tend to think of Unit Testing, not managing the lifetime of forms in their apps, including Dephi's forms.

 

There are three types of DI for classes: (1) constructor injection; (2) property injection; and (3) setter/getter injection. People have described all of these earlier in the thread. Neither of them is "best", although some are better for certain situations and needs than others.

 

Complicating things, the data they represent can be input only, output only, and bi-directional. So the DI part needs to account for this dynamic as well.

 

(FYI: a DI framework / Service Locator lets you save and lookup different instances of things is a totally different and unrelated discussion. It would have been nice if the original developers built Delphi's form management on top of a DI framework, as that would have codified how to get data in and out of forms consistently, but ... they didn't go that way. I've seen it done in large applications, and it simplifies the hell out of things because the way you interface with every form is the same. It's quite refreshing to see!)

 

And in my talk, I don't even address the situation where the form is interacting with a database maintained implicitly in another unit than the one that's dealing with it. This is the situation where you say, "Open this form to edit the current record in some DB based on whatever the user is doing right now." It's extremely common, and takes very little effort on your part because the form is simply mirroring both data and state being managed by some database components that probably live on a Data Module elsewhere. You just call Create and ShowModal and everything else is handled automatically.

 

A guy named Mark Seemann has written a lot on this topic; he has a blog, has written some books, and gives talks on the subject. He has written a book, Dependency Injection for .NET that's quite popular, and while the code is focused on .NET, the principles apply equally well to Dephi. He seems to have co-authored a newer version of it recently that I haven't seen but is probably worth checking out.

 

There's also the book Dependency Injection in Delphi by Nick Hodges. You can use Mark's book to learn the principles and Nick's book to see a lot of the examples in Delphi. I don't think Nick intended that, but it just shows how universal these patterns are. (It looks like all of Nick's books are on sale at Amazon right now.)

 

Edited by David Schwartz
  • Like 3

Share this post


Link to post

David, 

Thank you for your clear and helpful explanation.  Appreciated.

I have been looking in my Apps to see where/how the use of Properties can improve my code.  I have found a couple of cases so far.

Stano,

Tks.  I have downloaded the book.

 

Regards,

Ian

Share this post


Link to post
On 11/27/2022 at 1:07 PM, Ian Branch said:

David, 

Thank you for your clear and helpful explanation.  Appreciated.

I have been looking in my Apps to see where/how the use of Properties can improve my code.  I have found a couple of cases so far.

Unless you have a flawless crystal ball that sees very far into the future and all of the ways the class might be used, you have no way to predict which, if any, of the state variables you're adding to your class might change over time. By using a property to expose all of these state variables, you allow the class to evolve without impacting existing clients of the class in any way. 

 

Using properties is more of an on-going "best practice" as far as I'm concerned, that's simply rooted in years of having to deal with the consequences of NOT using them in large projects.

 

It's the same reason people use #define for constants in C rather than the values themselves. They're read-only, but you can change them in one place without impacting all of the code. In fact, this is one thing I find totally insane about CSS -- you cannot define symbolic constants for anything, and so if you want to change a property of a common thing, you have to edit the value of that property everywhere!

 

Properties in Delphi take it another step by allowing you to simply refer to the variable name itself if you don't need to do anything with it, or refer to a proc or func that can do pretty much anything with it. This is particularly handy in situations where you want to use Property Injection after a object has been created. Every assignment can have a setter that sets a flag saying whether a required parameter was set. Then if you try using a method and a required parameter has NOT been set, it's easy to raise an exception that uses very little overhead in that determination.

 

Thinking about these things becomes second nature after a while, and it's great to have a practice to follow that makes it easy to change your mind about things later on.

 

 

 

Edited by David Schwartz
  • Like 1

Share this post


Link to post
Quote

I got an email with a link.

I made one more attempt. Nothing again. Maybe they don't like that I'm from Slovakia - Central Europe :classic_laugh:
I give up.

Share this post


Link to post

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

×