Using Groovy as a scripting language
I prefer to use scripting languages for short tasks, anything such as a really simple http bot, bulk importing/exporting data to/from somewhere, etc etc... Basic throw-away scripts and simple stuff. The point being, that a scripting language is just an efficient tool to write quick programs with. As for my understanding of Groovy at this point...
If you were to program in Groovy, and you wan't to write a quick script, wouldn't you be forced to going back to regular java syntax (and we know how that can be convoluted compared to a scripting language) in order to do anything more complicated? For example, if I want to do some http scripting, wouldn't I just be right back at using java syntax to invoke Commons HttpClient? To me, the point of a scripting language is for quickly typed and less forced constructs. And here is another thing, it doesn't seem that there is any incentive for groovy based libraries to be developed wh开发者_Go百科en there are already so many good java one's out there, thus making groovy appear to be a Java dependent language with minor scripting features.
So right now I am wondering if I could switch to Groovy as a scripting language or continue to use a more common scripting language such as Perl, Python or Ruby.
@Zombies, let me show you a quick example from a script I wrote recently:
def fetch(build, toFile) {
new FTPClient().with {
connect ftpServer
enterLocalPassiveMode()
login ftpUser, ftpPassword
changeWorkingDirectory "/var/staging/revision-${build}"
fileType = FTPClient.BINARY_FILE_TYPE
toFile.withOutputStream { ostream ->
retrieveFile "build-${build}.zip", ostream
}
disconnect()
}
}
It uses commons-net API, but I think you would agree that it has a much clearer syntax than comparable Java program. So I don't think using the Java APIs defeats the purpose of having a scripting language. Furthermore, it helps you leverage your existing knowledge of the Java APIs, so is a very pragmatic approach.
One goal of Groovy is to have transparent interoperability with Java. Groovy is by design "a Java dependent language with scripting features". However, I don't think that these features are minor - Groovy has many features that are not found in static programming languages (such as Java).
To summarize: If you don't care at all about Java, then use a more general-purpose scripting language, such as Python or Perl. If you want to use the Java code-base in a script-ish way, Groovy is a good option.
Groovy can be quite handy for scripting. Recently I needed a script to fetch Maven dependencies into a lib
directory and ended up with a groovy script. This snippet parses a pom and gives you a list of jars. Pretty sweet for XML parsing!
#!/usr/bin/env groovy
def pom = new XmlSlurper().parse('pom.xml')
def repo = "${System.env.HOME}/.m2/repository"
pom.dependencies.dependency.each { dep ->
def jarName = "${dep.artifactId}-${dep.version}.jar"
def groupPath = dep.groupId.text().replaceAll('\\.', '/')
def jarPath = "${repo}/${groupPath}/${dep.artifactId}/${dep.version}"
println "$jarPath/$jarName"
}
For example, if I want to do some http scripting, wouldn't I just be right back at using java syntax to invoke Commons HttpClient?
You would be "right back at using Commons HttpClient", but you would invoke it using Groovy syntax, not Java syntax. Groovy syntax is a lot more compact than Java syntax and therefore better suited for scripting. In other words, using Java libraries in Groovy takes a lot less code than using Java libraries in Java.
it doesn't seem that there is any incentive for groovy based libraries to be developed when there are already so many good java one's out there
Rather than developing an entirely new library, a Groovy library author will often provide a "Groovier" API to an existing Java library. Examples include the Hibernate builder provided by Grails, and the HTTP Builder (which delegates to Commons HttpClient).
These Groovy APIs provide a more compact and idiomatic alternative to using the Java API directly.
Groovy "out of the box" replaces a large number of common classes with groovier versions or language constructs, including classes for XML, HTTP requests, accessing SQL databases and regular expressions. For most scripting tasks, you won't have to use Java libraries at all (although you'll still have that option). But if your script uses bare Java libraries, you'll be much farther ahead with Groovy over straight Java. Where Groovy shines is in the "glue" code, such as setting up data structures and file I/O.
The map and list allow you to create Java compatible Lists and Maps; regular Java objects that work with Java classes. Groovy often turns a multi-line Java method invokation with variable declarations and initalization into a one-liner.
Consider this short snippet to load an entire file into a String:
def fileContents = new File(filename).text
versus
String fileContents = "";
try {
BufferedReader reader = new BufferedReader(new FileInputStream(filename));
String line = null;
while ((line = reader.readLine()) != null) {
text = text + line + "\n";
}
} catch (IOException e) {
e.printStackTrace();
}
Exception handling is often not an important consideration in scripts and it can be conveniently ignored.
Groovy's main strength as a scripting language is accessing the enormous library of Java code that's out there directly and conveniently. If that's not your need, groovy still provides a scripting environment about as rich as other languages such as perl, python or ruby.
Groovy rocks, once you get a hang of the very tight syntax, you start to use it for a lot of things you've just done "the slow way".
The other day I was in a discussion which somehow got to wondering how many chars we have in a GUID in one of our systems. Rather than just count the digits, it was easier to just do this:
def str = '92228498-6A2F-DBA2-7A2C-F54B9E607E3A'
int num = 0
str.each {
num++
}
println num
Whack that in a local or shared scripts directory and it'll be there for the future.
精彩评论