Ajax Experts Unite!
There will be a Sun Certified Ajax Developer exam coming out soon.
They need help deciding what weightage to give various topics, so a bunch of experts are needed to give their opinions in a survey-bobber-thingy.
I am not an Ajax expert, so I will not be taking the survey. However, if you happen to be an Ajax expert, please take a couple minutes to take the survey.
http://certification.sun.com/sesCert/
Thanks!
poking Unit with a stick (Scala)
Scala has a thingy called Unit. For those coming from Java, Unit is similar to void but it is an actual type.
By my understanding, there’s only one actual instance of Unit ever and its value is ().
If you go to the Scala interpreter (type scala in a command prompt if you’ve downloaded Scala) you can assign Unit to a variable… er, um value in a few different ways.
One way is to simply create a value and assign () to it:
scala> val x = ()
x: Unit = ()
Another way is to make a value typed as Unit. You’re allowed to assign anything to it because pretty much any object in Scala can be automatically converted into Unit:
scala> val y: Unit = “turn me into Unit”
y: Unit = ()
I suppose the automatic conversion is because Scala methods return the value of the last expression. If Scala didn’t do this trick, we’d have to end every Unit-returning method with a gratuitous ().
Yet another way to end up with a Unit is to create a method without an assignment:
scala> def z(){“turn me into Unit too”}
z: Unit = ()
What’s this I say about a method without an assignment? Well the method z() I wrote above looks like a normal method to many folks (especially Groovy people). However, in Scala, most methods are created with an equals.
scala> def a() = “hello”
a: ()java.lang.String
Skipping the = is like automatically typing the method return as Unit, as if the z() method above were written as:
scala> def z(): Unit = {“turn me into Unit again”}
z: ()Unit
One weird thing I found with Unit is if I try to call getClass() on it:
scala> ().getClass
res1: java.lang.Class[_] = class scala.Predef$$anon$1
So it appears (), or Unit, is an anonymous inner class of something called object Predef.
Predef is a neato object. It pretty much is a way to get what appears to be a bunch of keywords and methods built into the Scala language, like println() and assertions.
Looking through the Predef source code, after being quite tickled by the ASCII art in the Scaladoc, I found the answer to another question I had about Unit – I had seen once in the Artima book unit with the lower case ‘u’. I originally thought it was a typo but tried it out in code and it seemed interchangeable. Line 36 of Predef, though the line is deprecated explains where unit (lower case ‘u’) comes from.
This was my experience digging into Unit in Scala. Try it out yourself and see what you can discover. Maybe you can uncover why ().getClass returns that weird Predef$$anon$1 thing.
Unsolicited LinkedIn Recommendations
Inspired by Gayle’s post, I wrote an unsolicited LinkedIn recommendation a few days ago. I found one of my previous managers on LinkedIn and just decided to recommend him. He was a great manager/architect/tech lead, so he deserved it. I wasn’t looking to get anything from it – I just thought he’d appreciate it, and I was hoping to make his day (or at least his evening, or hour, or something). I’m not sure how he reacted.
A friend and I were discussing this, and he told me he wouldn’t want an unsolicited recommendation. I never asked why – maybe he thought I would expect some sort of payback. Hopefully he’ll speak up in the comments. ;)
I, on the other hand, would love to get an unsolicited recommendation on LinkedIn. I’d be really excited about it (especially since LinkedIn keeps showing me that my profile is only 80% complete). And I think it would motivate me to pay it forward by recommending someone else. And pretty soon, everyone would have a recommendation…
So how would you react if someone gave you an unexpected recommendation on LinkedIn? Would you be thankful, excited, appreciative? Or would you wonder why they recommended you (maybe they’re trying to get something from you…)? Would you think it was a waste that they wrote it now, when you’re not even looking for a new job? Would you wish they had waited until the right time?
How to use Groovy without management finding out
I hang out with Ruby guys and gals when I can. These folks are such a blessing to my brain. If you don’t have Ruby friends, find some. Google for “yourcity ruby brigade” to find a Ruby user group in your area.
I’ve often heard Ruby friends talk about utilities they wrote in Ruby that essentially generate boilerplate Java code, and I used to shudder at the thought.
I always figured “You have a great language that can do so many yummy things, why are you using it to write icky code!?”
I think I’m beginning to understand now: The icky language (sorry for the blasphemy, but yes, I mean Java) runs faster. It’s also more likely to be accepted by the governors in your projects. If you don’t know what I mean by governors, they’re the poor folks that take the heat and lose bonuses when stupid geeky experiments with unproven technologies ruin a project. These folks love the status quo. And bonuses. Your geeky technologies pose a threat to both.
Groovy noobs and doubters ask “How can I get management to approve using Groovy in my project?” Well, you can write Groovy scripts that no one needs to know about. Write scripts that generate Java code.
I’m not completely off my rocker.
Grails does some cool code generation to write Groovy views and controllers based on your tiny li’l POGO domain classes. It’s so awesome not to have to write boilerplate code or have to start everything from scratch. I can literally create an entire CRUD webapp in a couple minutes, even with a couple beers in me (which, for the record, only happens at home on my own time – I swear). Why code generation is awesome: Doing tedious code manually from scratch is like a coding limbo… never really touching heaven or hell but it passes the time.
Code generation good. Hulk like code generation. Tedious code make Hulk angry! Hulk smash!!!!!
Just to play around and set my first goal low, I challenged myself to write a Groovy script that creates a Java constructor. All my favorite IDEs do this for me already, but I’m not going to let practicality get in the way of fun… certainly not when I’m coding on my own time at home! Time to play!!!
class Person{
private String firstName;
private String lastName;
private int age;
}
void constructor(Class clazz){
def props = clazz.properties.declaredFields.findAll{
// filter out the properties I do not want
!it.toString().contains("static") &&
!it.toString().contains("metaClass")
}.collect{
// I want the property type and name
[it.type.toString().split()[-1].replaceAll('java.lang.',''), it.name]
}
// dump out the constructor!!! yay!!!
print " public ${clazz.name}("
print props.collect{"${it[0]} ${it[1]}"}.join(', ')
println "){"
props.each{ println " this.${it[1]} = ${it[1]};"}
println " }"
}
constructor(Person)
All I have to do is paste in a new class definition like I did with the Person class and call my dandy new constructor() method, passing to it the name of my class. In Groovy I don’t have to say Person.getClass() or even Person.class – just plain ol’ Person is good enough.
My console dumps out:
public Person(String firstName, String lastName, int age){
this.firstName = firstName;
this.lastName = lastName;
this.age = age;
}
Not too shabby.
Keep in mind the DRY principle. Your first priority is to write Java code without any duplication. In most cases you can avoid duplication by simply following basic OO principles.
If, however, boilerplate code seems like a necessity, consider generating it.
Groovy Strings n Things
I’d like to take a moment to speculate on one of our previous posts, A quirk in Groovy maps and GString coercion.
This post brought up a good example of some buggy behavior in Groovy when it comes to GStrings and Maps. However, I don’t think the problem is in the Map, but in mixing/matching java.lang.String’s with groovy.lang.GString’s, and in particular on existing Java class methods that expect Strings. Taking the two examples from the previous post..
Exhibit A:
println map["$aVar"] //still good, this outputs x.
println map.get(”$aVar”) // oh snap! this outputs null!
Exhibit B:
println ‘a’ == “$aVar” // true
println ‘a’.equals(”$aVar”) // double snap!! it’s false!!
I think there’s a pattern..
In the first part of both of these example, we’re taking advantage of the operator overloading that Groovy provides and mix/matching java.lang.Strings and groovy.lang.GStrings, which seem to play nicely together in those cases. It appears that the GStrings are being evaluated before being coerced into Strings. The coercion must be happening at runtime for the dynamic GString to have it’s $value translated and put into the resulting String.
However, in the later case of both of these examples, we’re calling existing methods on existing Java classes (java.util.Map and java.lang.String). These methods take Strings not GStrings. In these cases, it looks like Groovy still coerces these GStrings into Strings, but my hunch is that it must do so at compile time in order to play nicely with statically typed Java methods on statically typed java objects. This would mean that it wouldn’t have enough information at that time to replace the $aVar with it’s dynamic runtime value and therefore doesn’t know what else to do but use the literal String value.
This is all speculation of course, but this model makes sense of what we’re seeing here. Is there anyone who knows enough about the internals of Groovy to confirm or deny this speculation?
The Executor Framework
It’s great. It allows you to handle concurrency in Java (or Groovy) without directly using the Thread class.
I first heard about the executor framework in Effective Java (Second Edition) (Item 68: Prefer executors and tasks to threads) and became really interested in it, decided to investigate further, and gave a presentation on it for my coworkers.
The Executors class (new in Java 5) provides a bunch of static factory methods for creating executors. With an executor, you can submit a task (Runnable or Callable) that will be performed by that executor. Here’s an example:
ExecutorService executor =
Executors.newSingleThreadExecutor();
executor.execute(runnable);
executor.shutdown();
As you can probably guess, this will create an executor which has a single thread. That thread will take the runnable and call its run() method. If the execute method is called multiple times, each runnable that’s passed in to the method will be placed on a queue. When the executor’s thread is available, it’ll pull the first runnable off the queue and run it. When that one finishes, it’ll grab the next one, and so on.
If a single thread isn’t enough, you can do the following:
ExecutorService executor = Executors.newFixedThreadPool(5);
for (Runnable runnable : runnables) {
executor.execute(runnable);
}
executor.shutdown();
This would create a thread pool with 5 threads that can execute the runnables. Again, the execute method places each of the runnables on a queue, and whenever one of the 5 threads is available, it pulls the runnable off the queue and runs it. That’s it! It’s so simple.
If you want to schedule your tasks to run at certain intervals, you can do this:
ScheduledExecutorService executor =
Executors.newSingleThreadScheduledExecutor();
executor.scheduleAtFixedRate(runnable, 0, 1, TimeUnit.MINUTES);
executor.shutdown();
This will submit a task to be executed every minute. The single thread in the executor will run the task right away, and then again every minute. The ‘0′ above indicates the initialDelay – that is, the number of units to wait before the first invocation of the runnable. The ‘1′ indicates the number of units between each invocation of the runnable. And, of course, TimeUnit.MINUTES indicates that the units for the ‘0′ an ‘1′ should be minutes.
If you’re using Groovy, it’s even easier because you don’t have to implement Runnable – you can just pass a closure to the executor (since Closure implements Runnable).
There’s no longer a reason to create threads directly in Java. The language now provides an easy way for you to run tasks in separate threads without having to micromanage them.
A quirk in Groovy maps and GString coercion
I slipped into my old Java ways recently and lost a bit of Groovy magic in the process. I was calling the get method on a map and getting null back, though I was quite confident I should have gotten a value from the map.
Let’s start with a simple map in Groovy:
def map = [a:'x',b:'y',c:'z']
Now we can print out the value for key ‘a’ with magical Groovy syntax:
println map['a'] // this outputs x
Or we can slip back into our old Java ways and it will still works.
println map.get(‘a’) // this also outputs x
But what if we want to look up a value using a GString with an inner variable instead of the normal String?
def aVar = ‘a’
println map["$aVar"] // still good, this outputs x
println map.get(“$aVar”) // oh snap! this outputs null!
As you can see, using the Java style of .get() using a GString that contains a variable doesn’t work.
But… wait a second! Aren’t ‘a’ and “$aVar” supposed to be the same thing in Groovy!?
println ‘a’ == “$aVar” // true
Not entirely. Yes, you learned that == in Groovy is the same as calling .equals in Java. But check this out!
println ‘a’.equals(“$aVar”) // double snap!! it’s false!!
So == obviously isn’t exactly the same as .equals – if you check out the Groovy Operator Overloading page, you’ll see a little sidenote:
** Note: The == operator doesn’t always exactly match the .equals() method. You can think of them as equivalent in most situations. In situations where two objects might be thought “equal” via normal Groovy “coercion” mechanisms, the == operator will report them as equal; the .equals() method will not do so if doing so would break the normal rules Java has around the equals method. Expect further improvements to Groovy over time to provide clearer, more powerful and more consistent behavior in this area.
In case you’ve read that sidenote before but you didn’t know what it meant by “coercion” mechanisms, now you know.
Keep all this in mind next time you’re dealing with a map in Groovy. Stick to using the Groovy array-ish square brackets instead of using the traditional .get() and you’ll avoid a potential headache.

Recent Comments