Why people dislike global variables so much while I find them so convenient?

Steven Schveighoffer schveiguy at gmail.com
Wed Jan 26 16:04:36 UTC 2022

On 1/26/22 4:10 AM, rempas wrote:
>> In some cases, they make sense, and in those cases, I'd recommend at 
>> least guarding the direct access to the variable through properties so 
>> you can control how it's used.
> What do you mean "properties"? I suppose not struct/class properties right?

A property is a functional setter/getter (or only one of those) that 
prevents incorrect usage.

For example, if you have a global int, and it really should only be in 
the range of 1 to 1000, you can guard the setting of the int to make 
sure that value was correct.

Or if you have a class reference stored globally, you may want to 
prevent someone from reassigning the class reference to another object. 
Then you can restrict access to getting only, and not allow setting.

You can implement a property in D at global level, e.g.:

private Resource _resource;

public Resource resource() { return _resource; } // only can access via 
this property


More information about the Digitalmars-d mailing list