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.
Related
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.
I have defined list_t in my project that got list module API like list_pop(). But now I have to use MySQL lib to communicate with DB, but the MySQL lib still got its list implements, and also defined a list_pop() API. In my other modules, I have to link both of them, and comes the conflict.
One of my solution is, separately include header file for different list API calling, this works well, but while some function need to call both of MySQL::list_pop() and local::list_pop(), how to notify the compiler the correct link point? Is there some GCC trick that can do these without any changes to local::list_pop()?
For most practical purposes, you are going to have to rename one or the other set of functions. It is probably easier to rename your own than those of MySQL.
The simplest approach is to simply add a prefix that has a higher probability of being unique (enough), such as your initials, or the codename of your project, or something. Or you can rename everything to avoid collisions, being aware that MySQL might add a new function in the future.
This is exactly why namespaces were invented for C++, and why C projects usually have systematic prefixes on sets of functions.
There is a way to solve this. Refactor your list_pop() to, say, my_list_pop().
There is one other way to solve this,
Looking at the header of the MySQL my_list.h here, https://github.com/lgsonic/mysql-trigger/blob/master/mysql/my_list.h you can see that list_pop is just a macro, and its binded at compile time, not at runtime(hence not a real library function). Changing list_pop of MySQL to list_pop_my(just in the #define) can make it do what you want it to do.
what is the purpose of namespaces ?
and, more important, should they be used as objects in java (things that have data and functions and that try to achieve encapsulation) ? is this idea to far fetched ? :)
or should they be used as packages in java ?
or should they be used more generally as a module system or something ?
Given that you use the Clojure tag, I suppose that you'll be interested in a Clojure-specific answer:
what is the purpose of namespaces ?
Clojure namespaces, Java packages, Haskell / Python / whatever modules... At a very high level, they're all different names for the same basic mechanism whose primary purpose is to prevent name clashes in non-trivial codebases. Of course, each solution has its own little twists and quirks which make sense in the context of a given language and would not make sense outside of it. The rest of this answer will deal with the twists and quirks specific to Clojure.
A Clojure namespace groups Vars, which are containers holding functions (most often), macro functions (functions used by the compiler to generate macroexpansions of appropriate forms, normally defined with defmacro; actually they are just regular Clojure functions, although there is some magic to the way in which they are registered with the compiler) and occasionally various "global parameters" (say, clojure.core/*in* for standard input), Atoms / Refs etc. The protocol facility introduced in Clojure 1.2 has the nice property that protocols are backed by Vars, as are the individual protocol functions; this is key to the way in which protocols present a solution to the expression problem (which is however probably out of the scope of this answer!).
It stands to reason that namespaces should group Vars which are somehow related. In general, creating a namespace is a quick & cheap operation, so it is perfectly fine (and indeed usual) to use a single namespace in early stages of development, then as independent chunks of functionality emerge, factor those out into their own namespaces, rinse & repeat... Only the things which are part of the public API need to be distributed between namespaces up front (or rather: prior to a stable release), since the fact that function such-and-such resides in namespace so-and-so is of course a part of the API.
and, more important, should they be used as objects in java (things that have data and functions and that try to achieve encapsulation) ? is this idea to far fetched ? :)
Normally, the answer is no. You might get a picture not too far from the truth if you approach them as classes with lots of static methods, no instance methods, no public constructors and often no state (though occasionally there may be some "class data members" in the form of Vars holding Atoms / Refs); but arguably it may be more useful not to try to apply Java-ish metaphors to Clojure idioms and to approach a namespace as a group of functions etc. and not "a class holding a group of functions" or some such thing.
There is an important exception to this general rule: namespaces which include :gen-class in their ns form. These are meant precisely to implement a Java class which may later be instantiated, which might have instance methods and per-instance state etc. Note that :gen-class is an interop feature -- pure Clojure code should generally avoid it.
or should they be used as packages in java ?
They serve some of the same purposes packages were designed to serve (as already mentioned above); the analogy, although it's certainly there, is not that useful, however, just because the things which packages group together (Java classes) are not at all like the things which Clojure namespaces group together (Clojure Vars), the various "access levels" (private / package / public in Java, {:private true} or not in Clojure) work very differently etc.
That being said, one has to remember that there is a certain correspondence between namespaces and packages / classes residing in particular packages. A namespace called foo.bar, when compiled, produces a class called bar in the package foo; this means, in particular, that namespace names should contain at least one dot, as so-called single-segment names apparently lead to classes being put in the "default package", leading to all sorts of weirdness. (E.g. I find it impossible to have VisualVM's profiler notice any functions defined in single-segment namespaces.)
Also, deftype / defrecord-created types do not reside in namespaces. A (defrecord Foo [...] ...) form in the file where namespace foo.bar is defined creates a class called Foo in the package foo.bar. To use the type Foo from another namespace, one would have to :import the class Foo from the foo.bar package -- :use / :require would not work, since they pull in Vars from namespaces, which records / types are not.
So, in this particular case, there is a certain correspondence between namespaces and packages which Clojure programmers who wish to take advantage of some of the newer language features need to be aware of. Some find that this gives an "interop flavour" to features which are not otherwise considered to belong in the realm of interop (defrecord / deftype / defprotocol are a good abstraction mechanism even if we forget about their role in achieving platform speed on the JVM) and it is certainly possible that in some future version of Clojure this flavour might be done away with, so that the namespace name / package name correspondence for deftype & Co. can be treated as an implementation detail.
or should they be used more generally as a module system or something ?
They are a module system and this is indeed how they should be used.
A package in Java has its own namespace, which provides a logical grouping of classes. It also helps prevent naming collisions. For example in java you will find java.util.Date and java.sql.Date - two different classes with the same name differentiated by their namespace. If you try an import both into a java file, you will see that it wont compile. At least one version will need to use its explicit namespace.
From a language independant view, namespaces are a way to isolate things (i.e. encapsulate in a sens). It's a more general concept (see xml namespaces for example). You can "create" namespaces in several ways, depending on the language you use: packages, static classes, modules and so on. All of these provides namespaces to the objects/data/functions they contain. This allow to organize the code better, to isolate features, tends for better code reuse and adaptability (as encapsulation)
As stated in the "Zen of Python", "Namespaces are one honking great idea -- let's do more of those !".
Think of them as containers for your classes. As in if you had a helper class for building strings and you wanted it in your business layer you would use a namespace such as MyApp.Business.Helpers. This allows your classes to be contained in sensical locations so when you or some else referencing your code wants to cosume them they can be located easily. For another example if you wanted to consume a SQL connection helper class you would probably use something like:
MyApp.Data.SqlConnectionHelper sqlHelper = new MyApp.Data.SqlConnectionHelper();
In reality you would use a "using" statement so you wouldn't need to fully qualify the namespace just to declare the variable.
Paul
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.
I've got a program where a lot of classes have really complicated configuration requirements. I've adopted the pattern of decentralizing the configuration and allowing each class to take and parse the command line/configuration file arguments in its c'tor and do whatever it needs with them. (These are very coarse-grained classes that are only instantiated a few times, so there is absolutely no performance issue here.) This avoids having to do shotgun surgery to plumb new options I add through all the levels they need to be passed through. It also avoids having to specify each configuration option in multiple places (where it's parsed and where it's used).
What are some advantages/disadvantages of this style of programming? It seems to reduce separation of concerns in that every class is now doing configuration stuff, and to make programs less self-documenting because what parameters a class takes becomes less explicit. OTOH, it seems to increase encapsulation in that it makes each class more self-contained because no other part of the program needs to know exactly what configuration parameters a class might need.
Regardless of the way you do it, you have several "modules" which compete for the same sequence of command-line arguments. There must be some cooperation so that the same command-line arguments can be processed by your classes without clashes.
By having each class implements the parsing, you simply make that cooperation implicit. There is no module dedicated to the cooperation between your classes. The problem becomes a matter of documentation rather than a matter of code. It is not bad but it may seductively appear as if the problem has simply "gone away". To be brief, this practice requires more discipline.
Also, it will make major overhauls of command-line argument syntax more difficult.
it seems to increase
encapsulation in that it makes each
class more self-contained because no
other part of the program needs to
know exactly what configuration
parameters a class might need.
If I understand what you're proposing, it really makes each class hide their dependencies.
The dependencies in this case may be simple (primitive), but if a class needs an username and password to function correctly, it should say so in its constructor. Otherwise, the class' callers need to look at the source code or documentation to use it.