Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using too many static variables in Objective-C a bad practice?

Will usage of static variables expose them to a danger of being modifiable from anywhere ?(In context of Objective-C). If yes, can someone suggest best alternatives for using shared variables across all classes ?

like image 899
Ankit Malhotra Avatar asked Mar 24 '23 22:03

Ankit Malhotra


1 Answers

Is using too many static variables in Objective-C a bad practice?

Yes. Of course, "too many" has not been quantified and is subjective. Really, global/static variables are very rarely a good thing -- very convenient to introduce and very difficult to debug and eliminate. Also rare is the case that they are good design. I've found life far easier without them.

Will usage of static variables expose them to a danger of being modifiable from anywhere? (In context of Objective-C).

It depends on where they are declared and how they are used. If you were to pass a reference to another part of the program, then they would be modifiable from 'anywhere'.

Examples:

If you place them so that only one file can "see" the variable (e.g. in a .m file following all includes), then only the succeeding implementation may use it (unless you pass a reference to the outside world).

If you declare the variable inside a function, then it is shared among each translation and copied for each translation in C/ObjC (but the rules are very different in C++/ObjC++).

If yes, can someone suggest best alternatives for using shared variables across all classes?

Just avoid using globals altogether. Create one or more type/object to hold this data, then pass an instance of it to your implementations.

Singletons are the middle ground, in that you have some type of global variable/object based abstraction. Singletons are still so much hassle -- they are categorized as global variables and banned in my codebase.

like image 115
justin Avatar answered Apr 18 '23 21:04

justin