What is the sense of get or set?

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MaaaxiKing

Since years, I do not understand why there are setters and getters. Can’t you always access a variable/property trough it’s name?
Example:

extends Label

func _ready():
	print(text) # prints the gotten text
	print(get_text()) # prints the gotten text
	text = "hello" # sets text
	set_text("hello") # sets text
:bust_in_silhouette: Reply From: Rickers

I’m not entirely sure, I think it’s partially preference, and using setters and getters is probably a better practice as many nodes contain them and it can make your code a little easier to read. I remember some GDquest videos making explicit use of them, but then again they some are pretty old.

:bust_in_silhouette: Reply From: exuin

The reason those functions exist is because in Godot 2 you couldn’t access properties directly. Now in Godot 3 you can, but the functions still remain.

I thought, this would exist in all languages, does it not? And afaik, the functions will still be improved or developped.

MaaaxiKing | 2021-02-23 15:52

Sorry, I’m not sure what you’re saying.

exuin | 2021-02-23 15:53

I thought, setters and getters would exist in every programming language and as far as I know, setter and getter functions will still be being continued to develop.

MaaaxiKing | 2021-02-23 16:58

I don’t think that’s the case for all programming languages. Like, python doesn’t have those since there are no private variables. I guess more setter and getter functions will be added to gdscript because of compatibility reasons though.

exuin | 2021-02-23 17:42

:bust_in_silhouette: Reply From: Inces

I found them extremely usefull, since they let adress any property as a string. And this opens a variety of options for dynamic coding, strings are very elastic variable type.

:bust_in_silhouette: Reply From: stormreaver

Getters and settings (generically called “Accessors”) are useful for:

  1. Providing a single location for access, which is a generally desirable feature.

  2. Allowing additional functionality to be attached to such access in an easily maintainable way. Say you wanted to ensure that all sets to a string variable are forced to uppercase. You could either code the requirement in every place that assigns a value to a string, which requires a lot of code that quickly becomes unmanageable; or you can write it one time in the setter, which then becomes the only code that has to be maintained.

Even in languages where properties replace accessors, the former are usually syntactic wrappers around the latter for those same reasons.

finally ​​​​

USBashka | 2022-07-30 13:58