Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ok , global variable is condemned, singleton is despised, what's the alternative?

For desktop application that is. This is just a general question that maybe only need general answers.

like image 315
mhd Avatar asked Dec 13 '08 14:12

mhd


People also ask

What can I use instead of a global variable?

In a scenario, where you need one central global point of access across the codebase, singletons are a good alternative for global variables. We can call a singleton as a lazily initialized global class which is useful when you have large objects — memory allocation can be deferred till when it's actually needed.

Are singletons global variables?

The Singleton pattern is basically just a lazily initialized global variable. It ensures that the class has one instance and that instance is globally accessible. However, do not confuse Singleton design pattern with single instances.

Why do we use the Singleton design pattern when we can just declare static global variables?

The Singleton pattern ensures that only one instance of a class will be created and provides a global point of access to it. Any global variables that are required can then be placed within this class and accessed wherever they are needed.

What should be used to prevent creating global variables accidentally?

Also, strict mode will prevent us from creating global variables accidentally. So if we have: 'use strict'; count = 10; then we'll get an error.


1 Answers

A static class with static data members? But who cares. Static data members are just global variables with more politically correct packaging.

Don't let fashion override your common sense. There's nothing wrong with using a plain old global variable. The singleton pattern is often overkill and annoying to type, and annoying when you are single stepping through code to debug it.

Assuming you are using C/C++, I would recommend that you not have global variables that are class instances that allocate memory from the heap. They will make it harder for you to use tools that check for memory leaks. Declare the global as a pointer, new it at the beginning of main(), delete it at the end.

EDIT AFTER 6 COMMENTS: Think of logging. Wouldn't you want to be able to write a line to your log from anywhere in your app? How concretely do you accomplish that without there being something globally visible to do that logging? If you want something globally visible, then go ahead and make it globally visible.

like image 174
Corey Trager Avatar answered Sep 21 '22 00:09

Corey Trager