I am trying to make little web framework in clojure. I have a bunch of clojure files in /handlers directory and I want to require all of them in my project's .core namespace. Every file defines its own namespace. For example: project.handlers.home. The idea behind this is when I add new handler, I don't want to modify namespace declaration in my core file to include it. The only solution I came up is to find all files in directory and load them with clojure.core/load, but it is far from beautiful and idiomatic. Is there a idiomatic way to do this?
Is there a idiomatic way to do this?
IMO, no. The idioms in Clojure usually favor being explicit over "doing magic", especially when it comes to naming global objects (which auto-loading namespaces clearly is).
I don't know why you wouldn't want to modify your "core" file when adding new handlers but you might consider introducing an additional namespace that loads both "core" and your handlers and hooks them together.
Noir included some functionality like this, making it an explicit API call to load namespaces under a particular directory. See load-views for an example of this. It used this to auto-load paths.
However, the Noir approach didn't feel idiomatic due to the amount of magic involved, as well as additional complications from the approach (e.g. lingering path definitions).
If you need to find namespaces from a tooling, framework, or library perspective, I would use find-namespaces in tools.namespace and then require/load them. This approach could be useful in terms of providing user level pluggability, where a user can drop a handler into a directory and then see new options in the code, though again being explicit tends to be significantly cleaner.
Related
What is the best way to restrict use of certain headers(features of the library itself) in certain Cpp files. And if it fails to follow the set rules, compilation should halt.
This is not about finding out superfluous includes. This is about restricting the developers to the applicaiton framework.
For example if there exists a osUtils class as osUtils.h and if as per this, this application's development framework mandates use of osUtils.h for filesystem operation like to make a folder. but there are always a chance that individual module finds it convenience to break this rule by including sys/stat and use a mkdir() method. But if the intention of providing a framework here lets say for cross-platform abstraction or special path handling logic, the objective is lost by doing it out of framework. Is there a way to restrict this? like restricting the usage of sys/stat.h in certain files (except for osUtils.h file in this case) can help solve the problem. but how to implement it so it will not compile if the rule is broken.
I don't know how to do this by breaking compilation - the idea of compilation failure because of a valid code don't appeal to me. I've got some other ideas:
Code review. If done right this should prevent such errors.
I am pretty sure that some static code analysis tool can help detect
those things (they can check things like 'include what you use', so
a rule 'don't include 'XYZ' should be there)
If you have this static analysis tool ready there is a problem with getting people to use it and fix errors shown by it. One option that you can use is git hook. If the new code don't pass the static analysis - reject the commit. If you cannot use hooks, or don't want to - make a separate CI job that will check for the violations of the static checking. Then you'll see who and when pushed some bad code.
I am just started on clojure and have a very basic question about core.clj.
What is a convention about it? What code should go there? Public API?
It is generated by leiningen when creating a project.
I have looked into source code of some libraries and this file is also present there (per package?).
Thanks
There's no defined meaning for it, but in an application it's often where you'll find the entry point, the main- function. For libraries, foo.core is often the namespace users will import to get your main functionality.
You don't have to do it that way, but it's a semi-predictable place to have the 'central bit' of whatever it is you're writing - even if your actual logic and algorithmic code is somewhere else.
Leiningen generates foo.core because it needs to pick a name and core is generic enough that it probably wont' be wrong. It's a style decision, but I typically opt to rename core.clj to a name that is actually meaningful for my project.
It's just a template file emitted by Leiningen. If I run lein new foo there is no specific or standard meaning to the namespace foo.core. It is entirely legal for the namespace foo to be the main API container for a project. It's just a free file for you to start working in.
That said, if you have a project foo, it is expected although not enforced that all your code for that one project exist in the foo.* namespace. Leiningen will allow you to build a project with the files src/foo.clj and src/bar.clj and it is entirely reasonable for foo to require bar, however when packaging your code for distribution this is probably a bad idea.
In order to start my C++ program, I need to read some configs, e.g. ip address, port number, file paths... These settings may change quite frequently (every week or everyday!), so hardcoding them into source files is not a good idea.
After some research, I'm confused about whether there is a best practice to load config settings from a file and made those configs available to other class/module/*.cpp in the same project.
static is bad; singleton is bad (an anti-pattern?) So, what other options do we have? Or, maybe the idea of "config file" is wrong?
EDIT: I have no problem of loading the config file. I'm worried about, after loading all those settings into a std::map< string, string > in memory, how to let other classes, functions access those settings.
EDIT 2: Thanks for everybody's input. I know these patterns that I listed here are FINE, and they are used by lots of programs. I'm curious about whether there is a (sort of) BEST pattern to handle configurations of a program.
Arguably, a configuration file is a legitimate use for a Singleton. The Singleton pattern is usually frowned upon because Singletons cause problems with race conditions in a multi-threaded environment, and since they're globally accessible, you run into the same problems you have with globals. But if your Singleton object is initialized once when you read in the config file, and never altered after that, I can't think of a legitimate reason to call it an "anti-pattern" other than some sort of cargo-cult mentality.
That being said, when I need to make a configuration file available as an object to my application, I don't use a Singleton. Usually I pass the configuration object around to those objects/functions which need it.
The best pattern I know of solving this is through an options class, that gets injected into your code on creation/configuration.
Steps:
create an options parser class
configure the parser on what parameters and options it should accept, and their default values (default values can be your "most probable" defaults)
write client code to accept options as parameters (instead of singleton and/or static stuff).
inject options when creating objects.
Have a look at boost.program_options for an already mature module for program options.
If you're familiar with python, have a look at the examples in the doc of argparse (same concept, implemented in python library). They are very easy to get the concept and interactions from.
I'm developing a C++ library. It got me thinking of the ways Java and C# handle including different components of the libraries. For example, Java uses "import" to allow use of classes from other packages, while C# simply uses "using" to import entire modules.
My questions is, would it be a good idea to #include everything in the library in one massive include and then just use the using directive to import specific classes and modules? Or would this just be down right crazy?
EDIT:
Good responses so far, here are a few mitigating factors which I feel add to this idea:
1) Internal #includes are kept as normal (short and to the point)
2) The file which includes everything is optionally supplied with the library to those who wish to use it3) You could optionally make the big include file part of the pre-compiled header
You're confusing the purpose of #include statements in C++. They do not behave like import statements in Java or using statements in C#. #include does what it says; namely, loads and parses the entire indicated file as part of the current translation unit. The reason for the separate includes is to not have to spend compilation time parsing the entire standard library in every file. In contrast, the statements you're trying to make #include behave like are merely for programmer organization purposes.
#include is for management of the compilation process; not for separating uses. (In fact, you cannot use seperate headers to enforce seperate uses because to do so would violate the one definition rule)
tl;dr -> No, you shouldn't do that. #include as little as possible. When your project becomes large, you'll thank yourself when you're not waiting many hours to compile your project.
I would personally recommend only including the headers when you need them to explicitly show which functionalities your file requires. At the same time, doing so will prevent you from gaining access to functionalities you might no necessarily want, e.g functions unrelated to the goal of the file. Sure, this is no big deal, but I think that it's easier to maintain and change code when you don't have access to unnecessary functions/classes; it just makes it more straightforward.
I might be downvoted for this, but I think you bring up an interesting idea. It would probably slow down compilation a bit, but I think the concept is neat.
As long as you used using sparingly — only for the namespaces you need — other developers would be able to get an idea of what classes were used in a file by glancing at the top. It wouldn't be as granular as seeing a list of #included files, but is seeing a list of included header files really very useful? I don't think so.
Just make sure that all of the header files all use inclusion guards, of course. :)
As said by #Billy ONeal, the main thing is that #include is a preprocessor directive that causes a "^C, ^V" (copy-paste) of code that leads to a compile time increase.
The best considered policy in C++ is to forward declare all possible classes in ".h" files and just include them in the ".cpp" file. It isolates dependencies, as a C/C++ project will be cascadingly rebuilt if a dependent include file is changed.
Of course M$ compilers and its precompiled headers tend to do the opposite, enclosing to what you suggest. But anyone that tried to port code across those compilers is well aware of how smelly it can go.
Some libraries like Qt make extensive use of forward declarations. Take a look on it to see if you like its taste.
I think it will be confusing. When you write C++ you should avoid making it look like Java or C# (or C :-). I for one would really wonder why you did that.
Supplying an include-all file isn't really that helpful either, as a user could easily create one herself, with the parts of the library actually used. Could then be added to a precompiled header, if one is used.
Simple question. I'm new to Clojure.
How can I use one file from my project in another file? Basically how can I include, import, or require another file? Not from libraries but fro my own code.
Thanks,
Alex
Normally you'll want to use the same method that you use with library code, which is to use / require your namespaces (through an ns form at the top of the file and sometimes the use / require functions at the REPL). For this to work, you have to make sure they are on the classpath. A short guide to that:
Follow the usual Clojure project structure: a src/ directory containing all your source files, where file src/foo/bar/baz.clj defines a namespace called foo.bar.baz. Note that you must maintain the directory structure / namespace name structure correspondence; things won't work otherwise. Also note that you must not use the _ character in namespace names or the - character (the hyphen) in filenames and whenever you use _ in filenames you must use a - in namespace names (and the other way around.) Finally, the directory hierarchy will be slightly more complicated with Maven projects, but don't worry about this for now (unless you're already a proficient user of Maven, in which case this won't be a problem for you).
Also see this answer of mine to an earlier SO question about Java classpath handling with Clojure for a more detailed step-by-step explanation of the filesystem hierarchy / classpath hierarchy correspondence.
If your code from the foo.bar namespace needs to use code from the foo.quux.baz namespace, do something like (ns foo.bar (:require [foo.quux.baz :as baz])) in foo/bar.clj and call functions from baz as baz/some-function. Or you can put (:use foo.quux.baz) in the ns form instead to call them directly (without the namespace qualifier, e.g. some-function). That's exactly the same thing as what you'd do for library code.
When working with your project's code from the REPL, make sure you include the src/ directory (the directory itself, not any of the files therein) on the classpath. You should probably consider using some tool to automate the REPL setup (including classpath management) for you; Leiningen is very popular with Clojurians and there are plugins for using Maven with Clojure too.
Warning: Your JVM-launching command might (in fact, probably will) recognise an environment variable called $CLASSPATH. As for its relationship to your Clojure projects, well, basically there should be none. More likely than not, your projects will require a different classpath each, with some possibly using versions of certain jars incompatible with those required by others (notably if you're using Clojure 1.1 -- latest stable release -- for some projects, while experimenting with 1.2 snapshots with others). Thus the correct way of managing the classpath is to prepare a minimal version for each project and pass that to the JVM launching command. As mentioned previously, you should invest some time in learning to use a good tool (like the above mentioned Leiningen) to set up the classpath for you as soon as possible so you don't need to care about this yourself.
(As a side note, you might have to add more than just the src/ directory and your jars to the classpath in some scenarios, e.g. if you plan on calling compile to produce .class files, you'll have to put the target directory on the classpath too. That's beyond the scope of this question, though.)
BTW, I've started this answer with the word "normally", because you could also use things like load & in-ns to split a single namespace into multiple files. Most of the time this won't be what you really want to do, though; just use a well thought out namespace layout instead.