Share a JavaScript library's namespace or use your own? - namespaces

It is fairly well known in JavaScript that declaring variables within the global scope is a bad thing. So code I tend to work on contains namespaced JavaScript.
There seems to be two different approaches taken to this -
Adding your application specific functions to the libraries' namespace e.g. $.myCarouselfunction
Creating your own namespace e.g. MyApplication.myCarouselFunction
I wanted to know whether or not there is a better solution or if they tend to meet somewhere close in terms of pros and cons.
The reason for me personally deciding not to go with the library so far is for Seperation / Isolation / Lack of conflict with library code and potential plugins that are likely to share that namespace. Is there more to this that I'm not considering?

I think the most important thing in choosing this sort of thing is semantics.
Does your function/class extend or depend on a library-specific feature? Put it in the library namespace.
Is your function/class library-independent? In this case, it is better to put it in a custom namespace. This makes it possible to reuse your code outside the the library you originally used it with.

Personally I like this sort of approach:
(function(namespace) {
function myPrivateFunction(){};
namespace.myPublicFunction = function(){};
})($); // passing the $ namespace, but if it clutters,
// we can change it to something else

If you've ever tried to pull in more than one library using the same namespace, it can be surprising how likely collisions are to occur, and it can be quite frustrating in that these sorts of bugs often crop up in surprising and hard to debug ways. I think that your intuition about collisions is correct, and that the most import consideration as to whether to define your own namespace or reuse someone else's is to respect namespace ownership. That means that that unless you are in contact with the people who maintain another namespace and they know what you are doing, it's a good idea to use your own namespace.
If you do decide to ignore the advice on namespace ownership and define an API on an existing namespace (for semantics or whatever), one thing to consider would be to use an export function to detect errors. Basically, you can first define something on your own namespace, and then export it to the target namespace, along the lines of:
MyApplication.exportName = function(objToExportTo, name, obj) {
if (objToExportTo[name] === undefined) {
objToExportTo[name] = obj;
} else {
// Possibly assert!
}
};
MyApplication.myCarouselFunction = function() { ... };
MyApplication.exportName($, 'myCarouselFunction', MyApplication.myCarouselFunction);

I tend to prefer adding custom code to the library myself. The biggest reason for that is so that the usage semantics remain consistent across the built-in code and my custom code. That being said I can't really think of any technical advantages or disadvantages to this approach. I think your concern about conflicts is valid, though probably not very likely (if you end up with a component/module that conflicts with one of your custom functions, chances are it will be because you are replacing your code with someone else's).

The correct choice depends on your target environment. You're choosing between two namespaces, both of which can become arbitrarily cluttered. If you think it's more likely that you'll encounter a conflict in the library namespace, you should use the window namespace. If you think the window namespace is more likely to get cluttered, choose the library namespace.
In either case, you usually should only create one "global" name. In other words, if you're going to put your function in the library's namespace, it's best not to name it $.myFn. Name it $.yaya3.myFn and then cache a local reference to it in any context where you're calling myFn multiple times.
One best practice for referencing your function is to pass the namespace that it lives in as an argument to an anonymous function:
(function (yaya3) {
var myFn = yaya3.myFn;
myFn("frobnard!");
}(window.yaya3)); // you could instead pass $.yaya3 or YUI.namespace("yaya3") here
This makes it much easier if you discover that you need to move to a different namespace.

Related

Clojurescript decoupled file & namespace?

I'm using reagent to build several alternate root components, only one of which will be mounted on any given page; definitely either/or. These have a degree of commonality in their makeup, hence it will be convenient to move what is common among them to a common namespace.
What would be ideal is if in the file for each of these components I had the option to switch namespace into common, and add defs particular to the component, then switch back, thus avoiding circular dependencies nor needing any kind of inheritance.
I recalled this being possible in common lisp, how wonderful it was, and it also seems possible in clojure.
From Clojurescript docs: ns must be the first form and can only be used once, and in-ns is only usable from the repl.
I'm wondering if there's a way to achieve this kind of thing in clojurescript which is still eluding me.
If not I may need to reconsider my assumptions behind multiple alternate root components; the "many builds within one build" kind of idea, if that makes sense.
Update after some futher experimentation and confusion:
another option might be to split a single namespace across multiple files (is this possible?). Not sure what direction to turn in here.
The fact that in reagent I am using atoms in the global namespace is what's creating the need for circular dependencies if I use a separate namespace for common. Hence, wonder about one global namespace, in which case multiple files might help. Or is the way forward one giant file and one namespace??
Update: I've realised there is a great tension between keeping all app state globally (in my current case, multiple atoms), and passing app state around. My pattern currently is everything global, don't pass any of it around. Passing the necessary state as parameters to fns in the common namespace would solve the problem here (duh!), but then there's the question of what principles are being followed here regarding app state. If I just added a param whenever I needed one, but started with the idea that everything was global, there'd be no real principle to it...
In ClojureScript, everything is pre-compiled into a single static JavaScript "executable", so there is nothing like the repl you are used to in Clojure. Indeed, in CLJS the "Var" concept doesn't really after the compiler, they are just static (constant) variables and cannot be rebound.
Having said that, CLJS does emulate the behavior of Clojure dynamic variables via the binding form, so that may help you to reach your goal. As in CLJ, it creates what amounts to a (thread-local) global variable. This is a degenerate case in CLJS since there is only one thread. However, the source code looks identical to the CLJ case.
Another way to accomplish this is to just use a plain atom as a global variable so you don't have to pass a parameter around.
As always, when using a global variable, it reduces the number of parameters in function call trees, but it creates invisible dependencies between different parts of the code. Somethimes convenient, but usually a bad tradeoff.

Mixed Classes/Objects and Functions: Code Smell?

I'm looking at refactoring to move to OOP, since I have mandated PS5 for all users, and there are some things in my code that could really benefit from inheritance. My script has lots of utility functions that are used in various places. Some of them will make sense to make helper methods within my classes, but some will be used beyond just one class. So, is it appropriate to keep them as Functions, or is that really a code small it everything should be converted to Classes and Objects? And if a utility function is converted to OOP, what is the mechanism for sharing it between other classes? Do you use a global variable, do you create a local variable and past some how to the object that needs it?
I have spent a great deal of time writing PowerShell classes simply for the sake of exploring the what/how/why during my day-to-day work, and in doing I have started to ask myself the following questions:
Am I going to be creating multiple instances of this thing?
Do I need it to always have these specific properties & methods?
Will this make my scripts harder for me to understand later?
For question one, it will help prevent creating additional complexity on a class you're going to create only a single instance of, when it could just as easily be a series of functions & variables contained in its' own .ps1 script
For question two, you filter out unnecessary complexity even further by eliminating classes that simply don't need to be that rigidly defined. If you have two functions for a single array of strings that contains structured data inside, your time would be better spent ensuring the functions themselves are concise and well documented instead of trying to turn it into a class definition.
Lastly for question three, if you are working on scripts that either presently, or may in the future, be passed on to another individual you need to ask whether this quality of life adjustment will make the intent of your scripts more difficult to understand. This is usually not a problem, but if you're solving an inherently procedural / functional problem with OOP concepts you're simply going to obfuscate the actual solution.
Finally, to address your concern regarding sharing information between classes, simply make your class properties public if they need to be shared between instances or functions and reference those values in the scope the instance is created.
For example, say I have Class Foo with property Bar that I want to access from a script function:
Class Foo {
[Int] $Bar = 0
Foo () { $Bar = 5 }
}
$MyVar = [Foo]::New()
Function GetBar() {
return $Script:MyVar.Bar
}
Write-Host GetBar

ES6 modules: Are functions and variables not available in global space

Is everything in ES6 part of module.
eg. if I write in a file.
function simpleFunc(){
console.log("test")
}
Is this function not available to code in other places. In regular javascript , this function can also be executed from within html script.
What is the whole concept of modules. I understand polluting global namespace is a bad practice , but when we export a function or const, is it just an approach to avoid polluting global namespace. Can a developer still write var a= 10 in a js file and waste all the efforts of maintaining modules. I suppose this would still be possible because es6 is supposed to be backwards compatible with js.
Simply my question boils down to: Is a js file different when the language is ES6.
Not sure why no-one has answered this question yet, it's a simple answer, so I will answer it in case anyone else stumbles onto it:
Javascript is javascript.
ES5 practices still apply to ES6 in terms of script placement. Modularization allows you to import code from one script to another - this can help you keep large applications maintainable as well as many other structural benefits.
Additionally you are right about not polluting the global namespace - modules are also namespace containers, which protects the global namespace.
Here's a quote from a good (full) explanation to the importance of modules:
Modularization is the basic necessity for any software development. Breaking things into smaller pieces of functionality gives us the power to reuse the code. Modules are also containers for the namespaces.

Making superclass variables read-only to children in TCL OO

Let's I have a class foo, with a variable bar. Now... I want that if there is a class moo, which has class foo as a superclass, I want that any attempts to write to, or better yet, even refer directly to bar will be errored out. This could save situations when someone is using my code (which could be compiled to byte-code), to not override, by having one's own variable with the same name
TclOO simply does not support the concept. Classes are not security boundaries in TclOO, just as namespaces are not security boundaries in plain Tcl (TclOO objects are really just fancy namespaces). Tcl's security boundaries are between interpreters, and between the Tcl script level and the (usually) C implementation level. We're considering adding “private” instance variables for Tcl 8.7, but even those won't be truly private; their names will still be predictable if you know how (and they will be accessible from outside the class; that's important for when using the variable with third-party code such as Tk). To reiterate: classes are not security boundaries.
If you have something that must be locked out of sight, it is easiest to implement it in C. You can plug in methods implemented in C into TclOO (applying whatever controls you can think of) and those methods can use the (C level only) metadata mechanism to create instance-attached storage that they can use. All the callbacks are in place to do deletion correctly at the right time. Methods in C are not much more complicated than commands in C; the function callback signature is a little different and the usage is a bit more complicated (because there are other standard operations on methods such as copying them) but if you can do one, you can figure out how to do the other too.

Code optimization - Unused methods

How can I tell if a method will never be used ?
I know that for dll files and libraries you can't really know if someone else (another project) will ever use the code.
In general I assume that anything public might be used somewhere else.
But what about private methods ? Is it safe to assume that if I don't see an explicit call to that method, it won't be used ?
I assume that for private methods it's easier to decide. But is it safe to decide it ONLY for private methods ?
Depends on the language, but commonly, a name that occurs once in the program and is not public/exported is not used. There are exceptions, such as constructors and destructors, operator overloads (in C++ and Python, where the name at the point of definition does not match the name at the call site) and various other methods.
For example, in Python, to allow indexing (foo[x]) to work, you define a method __getitem__ in the class to which foo belongs. But hardly ever would you call __getitem__ explicitly.
What you need to know is the (or all possible) entry point(s) to your code:
For a simple command line program, this is the "main" method or, in the most simple case, the top of your script.
For libraries, in fact, it is everything visible from outside.
The situation turns more complicated if methods can be referenced from outside by means of introspection. This is language specific and requires knowledge into details of the techniques used.
What you need to do is follow all references from all entry points recursively to mark up all used methods. Whatever remains unmarked can safely - and should - be removed.
Since this is a diligent but routine piece of work, there are tools available which do that for various programming languages. Examples include ReSharper for C# or ProGuard for Java.