ajrussellaudio
ajrussellaudio

Reputation: 401

Constant Functions Over Global Variables?

Global variables are bad, hopefully we are pretty much all agreed on that. But are global functions that only ever return one thing less bad?

var foo = 42; // this is bad
function foo() { return 42; } // less bad?

I get the feeling I can't be the first one to think of doing this, but am having difficulties thinking of the drawbacks.

Upvotes: 1

Views: 149

Answers (2)

Farooq Hanif
Farooq Hanif

Reputation: 1899

The main disadvantage of having globals (functions or variables) is that their names can collapse with other libraries or frameworks that you use in your application. Also they negatively affect code reusability and code distribution. Due to these reasons you should avoid using globals. Instead you should encapsulate these globals in some namespace and you should try your best to make the namespace name unique enough so that it does not conflict with any library or framework.

Upvotes: 1

Quentin
Quentin

Reputation: 943207

You still have a global variable (and it is a variable, not a constant), the only difference is that the value of that variable is a function.

There are no benefits, and you have the overhead of calling the function whenever you want to get the value.

If you want a constant, then use a constant.

const foo = 42;

This still has the drawbacks of being a global and you should still aim to define your variables and constants in as narrow a scope as you can.

Upvotes: 3

Related Questions