views:

99

answers:

1

In my experience, most JS functions, constructor functions, or module-pattern functions, are declared as globals or are bound to a global namespace object. In any case, these identifiers are globally accessible.

From any line of code in your system you can have:

mod1 = somepackage.SomeModule(); // couple to me!

Here's a quick JS example, but in other languages the idea applies.

function A () { // couple to me!
  return { foo: "bar" };
};

(function () {
  function B () { // don't couple to me!
    function c () { // really don't couple to me!
      return "buzz";
    };
    return { fizz: c() }; // 0 scope lookup
  };
  var a = A(); // 1 scope lookup
  var b = B(); // 0 scope lookup
})();

var a1 = A(); // 0 scope lookup
var b1 = B(); // B is not defined

Since globals are considered harmful, how much should visibility of functions/classes be restricted? What are the tradeoffs?

My question is somewhat motivated by: 'when are globals acceptable', 'alternatives to globals', and 'return of the globals'

Thanks!

+3  A: 

Well it is always best to start with minimal scope which you can increase if there are requirements. But if you keep things public in the first go then it will be really really hard (almost impossible) to minimize the scope as you will have to refactor/fix other code in the process.

This is one of the main things when designing an API.

Also keeping the scope minimal is also a good design decision. This way you can manage the usage of the classes. For instance in case of factory patten you keep the constructor's scope to default so that only the code in that particular package (i.e., your factory class implementation) can create the object and others can't.

Faisal Feroz
I agree reducing scope is a good decision. My concern is that, compared to a variable scoped to a block or a function, a variable scoped to a package is accessible from many more lines of code. It makes me wonder if constructors should be defined closest to their site of first use.
James
I think variables should be scoped private unless there are compelling reasons for not doing so (inheritance etc.)
Faisal Feroz
It seems like reducing scope also reduces reusability, requiring method signature changes everywhere the factory could be passed.
James
A pedantic example in Java, and closer to what I'm referring to, would be a class defined and used in a method only. See: http://stackoverflow.com/questions/2428186/use-of-class-definitions-inside-a-method-in-java
James