Clojure template engine to generate Java source - clojure

I am writing a Clojure program which need to generate a Java source. Is there a good idiomatic way/template engine for that.
In Java world I would probably use Velocity or Freemarker. I know I can still use them from Clojure, but wondering if there is better way.

Probably you can take a look at Rythm template engine, which is much faster than Freemarker and Velocity, also much easier to use.
Document could be found at http://www.playframework.org/modules/rythm-1.0.0-20121210/home
Note although the document is for play-rythm module, the most part of it also apply to pure rythm environment

I've been using Clojure with StringTemplate for the purpose you describe for quite some time now with good results. I 've also defined a helpful set of macros that make the invocation of the StringTemplate renderers from Clojure a breeze. StringTemplate is established, solid and used for heavy-weight compilers so it can't fail you. On simplicity / speed or other trade-offs I cannot comment.

Related

How do I effectively manage a Clojure code base?

A coworker and I are Clojure newbies. We started a project a couple months back, but quickly found that we had a tough time dealing with our code base -- by 500 LOC we basically had no idea where to start with the debugging, when things went wrong (which was often). Instead of pairs, functions were getting lists, or numbers, or what-have-you.
Now we're starting a new but related project and migrating a lot of the old code over. But we're again hitting a wall.
We're wondering, how do we effectively manage a Clojure project, especially as we make changes to existing code?
What we've come up with:
liberal use of unit-tests
liberal use of pre-, post-conditions
informal type declarations in function comments
use defrecord/defstruct/defprotocol to implement a data model, which would really simplify testing
But post-, pre-conditions seem not to be used very often. Unit-testing + comments will only help so much. And it seems like Clojure programmers don't typically implement formal data models.
Do we just not get Clojure? How do Clojure programmers know that their code is robust and correct?
I think this is actually an evolving area - Clojure hasn't really been around long enough for all of the best practices and associated tools for managing a large code base to be developed yet.
Some suggestions from my experience:
Structure your code in a "bottom up" way - in general, the way you want to structure you code will have the "utility" code at the top of the file (or imported from another namespace) and the "business logic" code that uses these utility functions towards the end of the file. If this seems difficult to do, then it's probably a hint that your code needs some refactoring.
Tests as examples - Test code in clojure works very well both to sanity check your code but also as documentation (e.g. "what kind of parameter is this function expecting?"). If you hit a bug, refer to your tests to check your assumptions and write a couple of new tests to flush out what is going wrong.
Keep functions simple and compose them - Kind of an extension of the "single responsibility principle" to functional programming. I consider more than 5-10 lines in a Clojure function as a major code smell (if this seems extreme, just remember that you can probably achieve as much in 5-10 lines of Clojure as you could with 50-100 lines of Java/C#)
Watch out for "imperative habits" - when I first started using Clojure, I wrote a lot of pseudo-imperative code in Clojure. An example would be emulating a for loop with "dotimes" and accumulating some result within an atom. This can be painful - it's not idiomatic, it's confusing and usually there is a much smarter, simpler and less error-prone functional way of doing it. This takes practice, but it is worth it in the long run...
Debug at the REPL - usually when I hit an issue, coding at the REPL is the easiest way to flush it out. Generally this means running some specific parts of the larger algorithm to check assumptions etc.
Refactor common utility functions out - you'll probably find a bunch of common or structure repeated in many functions. Well worth pulling this out into a function or macro that you can re-use in other places or projects - that way you can test it much more rigorously and have the benefits in multiple places. Bonus points if you can get it all the way upstream into Clojure itself! If you do this well enough, then your main code base will be extremely succinct and therefore easy to manage, containing nothing but the genuinely domain-specific code.
simple composable abstractions
"It is better to have 100 functions operate on one data structure than to have 10 functions operate on 10 data structures." - Alan J. Perlis
For me its all about composing simple functions. Try to break every function down into the smallest units you can and then have another function that composes them to do the work your need. You know you are in good shape is every function can be tested independently. If you go too heavy on the macroes then it can make this step harder because macroes compose differently.
D.R.Y, Seriously, just don't repeat yourself
starting with well decomposed functions in a a bunch of namespaces; every time I need one of the composable parts somewhere else I "hoist" that function up to a library included by both namespaces. This way your commonly used abstractions sort of evolve over the course of the project into "just enough framework". It is very difficult to do this unless you really have discrete composable abstractions.
Sorry to dig up this old question, the answers by mikera and Arthur are excellent, but it's something I've also wondered about as I've been learning Clojure, and thought I'd mention how we organise files.
In a similar vein to ensuring each function has a single job, we group related functions into namespaces to make it easier to navigate the code. So we might have a namespace for functions providing access to a particular database, or providing a collection of HTTP-related utilities. This keeps each file relatively small, and makes tests easier to find. It also makes refactoring much more straightforward. This is hardly anything new, but it's worth bearing in mind.

Learning Clojure by reading core.clj

I came across the tweet today:
Start each day by reading the implementation of a function or macro in Clojure's core.clj.
My Clojure knowledge is really basic, I can hardly read other's Clojure (or Lisp) code.
Can I do well with core.clj, especially I have the feeling it is full of complicated macros?
I think a better place to start is by doing a project; anything that interests you and seems manageable is good.
core.clj is not readable right now; perhaps the latter half is, but the first half isn't something I'd wish on anyone as an introduction to the language. The truth is, even if you read it very carefully, you'd not have a solid idea of what was going on without also reading a lot of Java code, too.
Make an asynchronous text-based game (technomancy—Phil Hagelburg—has a nice one to look through on his Github, though it's a little dated by now)
Scrape websites using the Enlive library.
Maybe just solve some math problems, and/or
Graph things using Incanter.
Build first. Once you acquaint yourself with the tools you are using, start reading them. The libraries mentioned here are well written (you can't go wrong with anything by Christophe Grand, for instance), and once you start using them, you'll understand what they do, which makes it much simpler to figure out the why and how later.
That tweet is probably a great idea once you have enough experience to be able to read Clojure code well enough to understand what is going on.
Before that point, I'd recommend gaining a strong familiarity with the language by writing a lot of small mini-programs. It's best to learn by doing, after all.
I personally found Project Euler very useful while I was learning Clojure.
You might also take a look at the Clojure Koans, though they may be a bit beginner-oriented for you, depending on how much Clojure you already know.
As a good starting point, I would recommend 4Clojure. It looks similar to Project Euler and Code Katas, but has more forgiving learning curve.
There's a lot I don't understand in it, but there's also a lot I do, and it's fascinating looking at the language getting bootstrapped from its minimal initial implementation.
Another place to look for little projects to get you going would be any of the Kata repos. My personal favorite at this point is Coding Kata.org, but there's also Coding Dojo, Ruby Koans (with a little translation effort), and of course Google.
Try to do one of those a day and you'll quickly pick up the language.
Try reading the Clojure contrib libraries or look at some Clojure projects on github to get a better feel for idiomatic Clojure code.
The advice above is good. Another fine example of learning-by-doing is well illustrated here by the creator of Ruby on Rails: How Do I Learn to Program? I hope you have an app that you care about that you could just go for in Clojure.
I find the clojure.core a good way to find ideas of how things are implemented, as more of a reference guide. As noted earlier, the early parts or neither pretty nor exemplary. However, the later parts can be a good example especially when needing to write a function that is close to core function but different.

Which could become a strong alternative JVM language: Scala, Clojure, Fan, JavaFX Script, or other?

I am currently deciding on an alternative JVM language to port an existing Swing desktop application written in Java 6. Given that JavaFX specifically targets this kind of application, it would seem that my best option is JavaFX Script.
However, what about other kinds of applications and libraries? Would JavaFX Script be the best choice in general for a second JVM language?
Currently, it seems that Scala is the most talked about alternative to the Java language. This month (October 2009), it is at position 34 in the TIOBE index, while JavaFX Script is at position 44, and Clojure, Fan, and Groovy are at positions below 50.
So, what are your impressions? Which language would you invest your time in learning and using (and why), assuming you can freely choose the language for a given project to run in the JVM?
My main question would be: why are you porting an existing application? The answer to this question may give you some idea of where you want to go.
Some quick perspectives on the main choices:
Scala is in my view, a better Java than Java. If you want a language that takes the best bits of Java buts adds a lot of new innovations and features, then it may well be for you.
Clojure is an amazingly well designed language, particularly if you believe in a future of highly complex, concurrent applications. It's also extremely productive - I can probably create more value/hour in Clojure than any other language. However, unless you already know Lisp it will seem very unfamiliar at first. If you are willing to live on the cutting edge to get these benefits, Clojure may well be for you.
JavaFX script - has some very nice features for GUI design, and clearly has support of Sun/Oracle. On the other hand, I don't see it having massive traction outside this domain. I'd suggest giving it a trail run to see if it meets you needs.
Java - should still be on your list! If the reason you are porting is because the code has become difficult to maintain, then maybe a focused phase of re-factoring while staying on Java can get you the benefits you want. It's possible to write perfectly good GUI applications in Java.
Groovy - really nice scripting language on the JVM. Particularly good if you want to embed scripting features within an existing Java/JVM application. Not sure I'd choose it for (re)writing a complete application however.
JRuby / Jython - haven't seen these much myself but heard good things. Probably most suitable if you have Ruby / Python skills in the team but also want the benefits of the JVM platform.
The best alternate language, and the best language overall, IMO, is that which best allows you to write the program in the best model for you.
So, if you are writing a GUI app, then Scala may be the incorrect choice, as you wouldn't be moving away from Swing.
If JavaFX best meets your needs, then use that language.
If you know LISP then Clojure would be a good choice, but, like Scala, not for this problem, it sounds like.
If you don't know lisp and you want/need a functional programming language, then Scala would be the best choice.
Basically, there is no one language that is best in all situations, it helps to know what you want to do, and the strengths/weaknesses of the various options.
Those all sound like good choices. You could add JRuby to the list...

How can I implement scripting in my game?

I'm trying to write a game and implement scripting so that later on in development I won't have to recompile everything when I want to change numbers.
My problem is that I don't know how scripts should interface with the game. The scripting language I'm using is angelscript.
Right now, I have a state: the intro state, which I'm using as a test for most of the modules in my game "engine" (it's more like a loose collection of classes). It will load and draw a picture and draw text, and use scripting to update itself, and maybe switch to a dummy state afterwards to test the state manager.
While writing it, I realized that using the script to do most of the updating would require that I register most of my game engine's modules with the script, and pretty much move the bulk of the code to the scripting language. Personally, I'd rather have the C++ portion doing the majority of the work, and have the scripting language come up with the numbers to use in the formulas/drawing/whatever.
However, if I'm right, doing it that way would entail lots of different update modules for the majority of the things in the game that need to be updated, and requiring that they all be loaded in, and that the C++ code would have to run each update function individually.
Or, there's a way to achieve script and program interoperability that I'm overlooking. Either way, could someone help me figure out what the best way to get scripting implemented into my game is?
There's no correct answer to such a large question really. You do it the same way you would do engine/game logic separation in C++. Define an API that the script can call that allows it whatever it is you want it to do. Register functions in that API with the script, and use the API in angelscript. What that API should be depends entirely on your needs and what kind of power you want to give the scripter.
If you want AngelCode (or any other scripting approach of your choice) to just "come up with some numbers", hey, use it that way -- e.g., in AngelCode, compile the scripts by exposing to them a single C++ function of yours, say "void ProvideNumberFor(string reason, number value)", and the scripts will be responsible for calling that function as many times as needed to "provide the numbers", and nothing more.
If you look at real examples like Garry's mod or games written with UnrealScript you'll find that quite a bit of logic in modern games is implemented in the scripts. C/C++ code is best for "static" and bottleneck-prone parts of the engine, like the renderer, physics engine, low-level networking, etc. Scripts are best for content (i.e., game logic).
Aside: The best game-scripting language IMHO is Lua. It provides easy intregration with C/C++, is very well-documented, and will be familiar to users of Javascript.
I've used Lua for exactly this purpose, and it does a great job. Look at all the games programmed using Lua. Also, it's blazingly fast.
EDIT: I didn't read the question fully...sorry. This is my real answer ;)
If you're familiar with Qt4/Javscript you can always use QtScript http://qt.nokia.com/doc/4.5/qtscript.html.

What combination do you use for your polyglot solution?

Those of us who use multiple languages to solve problems can combine them in a lot of ways. Personally I use PL/SQL, XSLT, JavaScript, and Java plus the pseudo languages HTML, XML, CSS, Ant, and Bash. What do you use?
Paraphrasing one of my favorite quotes:
Always write your code as if it were going to be maintained by a homicidal maniac that knows your home address.
I have a D/MySQL/JavaScript[1]/HTML/CPP[2] app.
[1] compile time D template generated
[2] C pre-processor used to generate apache configs and SQL sprocs
Yes, I am trying to take things to the insane! ;)
I work on a desktop application, so my alphabet soup looks like: C# and C++ as well as XML and T-SQL.
Java + Clojure works very well as a combination for me.
Java is good for the low level code that needs to be well optimized. It also gives you access to the huge array of libraries in the Java ecosystem.
Clojure is great for rapid development of higher level code, working interactively in a REPL. It has great support for meta-programming and concurrency, and I often use Clojure to "glue together" Java based components into a working application.
It helps enormously that Java and Clojure run in the same JVM - calling between the two is very easy and has effectively zero performance overhead.