Why use property in a class?

后端 未结 7 445
闹比i
闹比i 2020-12-17 00:34

I was just wondering about why should I use property in a class instead of \"normal\" variables (class attributes?). What I mean is this:

TSampleClass = clas         


        
7条回答
  •  不思量自难忘°
    2020-12-17 01:15

    There are real-life advantages:

    • Properties can be changed to be read/write/read'n'write easily, without need to hassle with separate Getters and Setters all over the code;
    • Properties can be made public/published in child classes by just adding one line in initialization section;
    • Properties are more friendly when it comes to setting fields, compare "Label.Font.SetSize(14)" with "Label.Font.Size := 14", you can align ":=" with tabs/spaces and code will be much more readable;

    EDIT: Another thing I thought of, properties force you to limit Get/Set methods to only 1 parameter, which is good for OOP. Compare that to some over-engineered functions:

    GetItem(Index:integer; ForcedIndex:boolean=false):TItem //Forced index to get any value
    GetItem(Index:integer; out Res:PItem):boolean //Result signals if out pointer is valid
    

提交回复
热议问题