Communicating Technology
November 23, 2007
More than a year ago I watched this Channel 9 interview in which Don Box shares some tips on how to give a great technical presentation. I often catch myself using his advice in areas beyond tech talks. I’m not sure if these are all from that interview, but here’s a list of things that I find useful.
- The Goal: probably a universal truth, but if I’m working on something that will be heard or read by other people, it’s surprising to see how quick I lose track of the initial goal of the work. Do sanity checks. Will this serve the goal?
- The Font: code needs to be readable. I’d say the right code font is Consolas on Windows, or Monaco on the Mac. For God’s sake, don’t use Courier New. The font is the first thing I configure in a fresh IDE install.
- The Size: use the smallest possible example to explain a concept. Have slides with only a few words on them. Say more with less. It’s amazing how good that works.
- The Puzzle: give the audience something to look for. A hidden joke. A mistake on the slides.
- The Humor: nobody is that serious
- The Story: people like stories. They don’t have to be true.
Go Javapolis! :-)
Stay Hungry, Stay Foolish
August 26, 2007
This is an awesome speech Steve Jobs gave in 2005 at Stanford University. Truly inspirational stuff.
YouTube version here.
Builder Pattern Deluxe
July 12, 2007
Update: code available at http://code.google.com/p/garbagecollected/
Yesterday evening I came up with an interesting approach for implementing Josh Bloch’s revised GoF Builder pattern (warning: PDF). After some late night hacking, I can’t help but feel that this is very useful stuff. Take a look at Josh’s presentation first, and then take a look at this:
package builder;
public class SomeObject {
private final String mandatory;
private final int optional1;
private final char optional2;
private SomeObject (SomeObjectBuilder builder, String mandatory) {
this.mandatory = mandatory;
this.optional1 = builder.optional1();
this.optional2 = builder.optional2();
}
public interface SomeObjectBuilder extends Builder {
SomeObjectBuilder optional1(int optional1);
SomeObjectBuilder optional2(char optional2);
int optional1();
char optional2();
}
public static SomeObjectBuilder builder (final String mandatory) {
return BuilderFactory.make (SomeObjectBuilder.class,
new BuilderCallback () {
public SomeObject call (SomeObjectBuilder builder) throws Exception {
return new SomeObject(builder, mandatory);
}
});
}
public String toString() {
return new StringBuilder()
.append (getClass().getName())
.append (String.format ("[optional1=%s, ", optional1))
.append (String.format ("optional2=%s, ", optional2))
.append (String.format ("mandatory=%s]", mandatory)).toString();
}
public static void main(String[] args) {
System.out.println(SomeObject.builder("Mandatory!")
.optional1(35)
.optional2('A')
.build()
.toString()
);
}
}
Console output: SomeObject[optional1=35, optional2=A, mandatory=Mandatory!]
Using a dynamic proxy, the BuilderFactory provides the Builder<T> implementation for a given interface, so that you don’t have to write all that horrible boilerplate code. Often you use a builder when constructors get messy, but Builders with many parameters get messy too. Using this approach you not only save time, you also have the advantage of using a static factory method and having your specific builder as an interface instead of a concrete class. Full source code available upon request; feedback/suggestions/improvements appreciated!
Eat that, setter injection ;-)
My 4 Hour Workweek
July 8, 2007
After Scott Hanselman got me interested, I watched this interview the other week in which Robert Scoble interviews Timothy Ferris. Basically Tim preaches a different lifestyle: live by the numbers. Somehow this stuff always interests me, as I’ve always been keen on self-improvement. Of course I’m always skeptical when it comes to overhyped books or whatever. I’m probably the only guy in the world who didn’t read the Da Vinci Code. I did watch the movie, though. Jesus saves, passes to Moses, scoooores! Right?
One thing that I should do more often is what Robert Scoble said (I think it’s from the GTD book) about writing things down. If there’s something you need to think of, get it out of your head by writing it down. And make sure that it comes back to haunt you at the appropriate time. That’s where paper starts to get messy and cell phone calendars become useful. I started paying attention to it, and it is GREAT for peace of mind!
I’m also thinking about putting up a whiteboard here because it’s great for mind organizing. Often an idea is gone by the time you found your cell phone or a pen and a piece of paper. And even more often I know that I wrote something down, but where? :-) And if it’s right there on your wall, you can’t ignore it. Tasks that you postpone are right there on the wall, and will keep haunting you until you handle them.
On the other hand, Tim’s whole numbers thing might be useful to a lot of people, but I don’t buy it yet. I do like his goal-driven approach. On his website, for example, you’ll find some templates of what he calls a dreamline. I don’t have a printer (shame on me), but I’m putting that dreamline thing on my list, right after “buy printer” and “get whiteboard”.
Listening to podcasts and wasting time on the internet finally paid off. Which reminds me that I really need an iPod so I can stop wasting time at home, and spend some of my traffic jam time catching up with interesting podcasts. If I waste time, I might as well learn some stuff in the process.
Let’s finish up with a quote:
D: I’m putting that on my TODO
J: Is there anything on your DONE?
It’s funny because it’s true.
Guice Thread Scope
June 7, 2007
UPDATE: The reset thing turned out to be a bad idea, I created simple Thread Scope instead. If you somehow seem to need a reset, consider this.
Ever wanted to use Guice’s request scope outside of a web application? Try out my thread scope implementation and let me know what you think. Cast your vote if you want to see this scope added to Guice.
Here’s an example. Create a Module that looks like this:
Injector i = Guice.createInjector(new Module() {
public void configure(Binder binder) {
binder.bindScope(ThreadScoped.class, CustomScopes.THREAD);
binder.bind(ThreadCache.class).in(Scopes.SINGLETON);
// add your custom classes
binder.bind(SomeClass.class).in(CustomScopes.THREAD);
}
});
Each thread is automatically initialized for the scope. To reset it, use the ThreadCache:
@Inject private ThreadCache threadCache
public void someMethod() {
try {
// do stuff in thread scope
} finally {
threadCache.reset();
}
}
I’m thinking about loading this scope’s initialization code lazily (so that you’ll need to execute threadCache.start() or something like that). It currently doesn’t matter for me and the memory overhead is low anyway, but what do you think?
PS: only use field injection for examples ;-)
Consumer JRE Explained (and Confirmed)
May 21, 2007
Chet Haase’s recent blog entry “Consumer JRE: Leaner, Meaner Java” sketches a thorough overview of what we can expect of the “Consumer JRE”. An excellent read!
Next to that I also found Augusto Sellhorn’s blog entry, which offers some more specifics on the installation experience and the upcoming Javascript API. He had the chance to attend the JavaOne “Easy Deployment Is Finally Here” talk by Dennis Gu and Ethan Nicholas.
Now if only the guys at Sun realized what they missed.
PS: Let’s hope the JavaOne sessions will become available online soon. This talk looks promising (among others).
JavaFX in the Browser: What They Missed
May 11, 2007
1. Applets have a bad name
Is it really hard to imagine this: you’re at the water cooler, and one of your colleagues asks you what you’re up to. You admit it: you’re implementing Java Applets. So the other guy just stares at you for a second and starts laughing, guessing it was a joke!
What I’m trying to illustrate here, is that Sun should have waited until they had the “consumer JRE”, and should have launched a new Applet initiative at the same time that new JRE launched. Call it AppletFX, drop the name, whatever… just get that bad taste out of people’s mouths. Which brings me to my second point.
2. They announced it too early
Sun probably felt the Adobe and Microsoft pressure in the same market, so the announced their thing ASAP. Guess what, they had nothing impressive to show. Sure, there’s JavaFX Script. Sure you can draw circles and make buttons spin. Hell no, you can’t use your mouse wheel in JavaFXPad (what gives?). I mean, where’s the candy? The impressive story? The leading vision? The cool feature? The great performance? As they say, you only have one chance to make a good first impression.
3. They forgot to include rich video an sound support.
People come for the bling, but stay for the platform. If you haven’t got the bling, nobody is there to stay. I didn’t hear them announcing anything on the subject. Did I miss that part?
4. Scripting is harder to read compared to XML (for designers?)
Say what you want about XML formats, but people got used to reading XML. Not a lot of syntax to look at, and easily toolable.
Sun is looking at yet another missed opportunity to revive in-browser Java apps. But they do have a nice alternative for creating desktop UI’s now.
JavaFX: The Return of the Bling
May 9, 2007
My summary:
- Sun started the JavaFX initiative, which currently includes JavaFX Mobile and JavaFX Script (formerly F3). The latter one is a scripting language (and associated libraries) for UI design and eye candy, which builds on Swing and Java 2D foundations. Some interesting bits:
- It uses the regular Java JAR deployment techniques: standalone, browser applet, Java Web Start.
- This is Sun’s WPF/XAML. They even cloned XAMLPad.
- It looks to me that it’s possible to use the JavaFX Script libraries in Java too, because they’re regular Java classes. So no obligations there.
- JavaFX Script ships plugins for Netbeans and Eclipse.
- The whole thing will be open sourced (GPL)
- Early next year Sun will release a consumer JRE, which would be a fast and lightweight version of the JRE, targeted at desktop/applet end users. At the same time they will be revamping the installation experience. There’s a related project codenamed “Java Kernel” which will modularize the JRE so that Sun can ship minimal JRE versions more easily. In other words, they will try to fix applets.
Obviously they’re trying to catch up with initiatives such as Microsoft’s Silverlight and Adobe’s Flex (and Apollo). But they still have a long way to go. Coming up next: what’s missing?
It all started with this InfoQ article. Apparently, Sun will announce an early version (alpha?) of JavaFX at JavaOne, an open source RIA platform that uses the F3 scripting language and has a set of UI libraries and a programming model that would rival those of Silverlight or Flex. The F3 programming language itself feels a bit like a mix of Groovy and Javascript 2 to me, but is looks like a powerful solution.
Of course it remains to be seen if it was really needed to have yet another programming language. Scrolling to the F3 spec, I can see one thing that they didn’t get exactly right: integrated query syntax. I’ve seen some interviews and presentations on Microsoft’s LINQ project recently, including the one Anders Hejlsberg gave at Mix 07. Someone in the audience asked “why do you guys put the from clause before the select clause?”. The answer was simple: how would the IDE know how to help you if you start with the select clause? Select it from what? Subtle, but important. But it looks like a nice language, and the type inference thing is what I like to call “dynamic typing done right”. And it has excellent Java interoperability, so there’s a whole universe of libraries available to you. Check out Chris Oliver’s blog for more info on F3.
Although JavaFX looks like a worthy addition to the Java platform, they’ll have to get some important things right:
- Tooling support: GUI builder, IDE plugins for F3, …
- Excellent browser support: easy deployment and fast (Silverlight and Flex got this one right)
I fear that Sun, as the “spec company”, will only implement a part of that story, and will count on the community to complete the picture. Well, we all know that some things just need some company throwing some money at it to get the whole story. Including timing…
I guess I’m exited. Let’s wait for the JavaOne announcement before we draw any conclusions (based on some rumors). But draw ‘em we will ;-)
Update: this blog links to some interesting stuff, including some hands-on exercises. Looks like they’re using Java Web Start for deployment. Where’s the browser integration?
Update: added link to official JavaFX page, lots of info there. The IDE support is there, but they’re using Java’s mechanism for deployment (standalone, Web Start, Applet).
Scripting Guice
May 6, 2007
I really like Guice, a Java 5 style Dependency Injection framework by the bright guys at Google.
People who are used to Spring’s DI config often complain that they don’t like the “compiled configuration” thing (Java Modules) Guice has. In Spring, all your wiring is usually done in XML. So on one side you have compiled Java Guice Modules, a more natural programming model for Java developers, and on the other side you have XML configuration, nicely externalized. And yes, I know the Spring guys plan on having a Java version of their configuration syntax, but it looks just like the XML, so I don’t see any real advantages there.
Anyway, for the Spring users who want to try out Guice, you could externalize your configuration to a properties file, and load it from that. Or whatever format you’re willing to use. Heck, you could even write some code that parses a Spring config file and translates it into a Guice Module.
But here’s another idea: what about using a scripting language for all your object wiring needs? Why create a configuration file if you could use the highly readable Guice Binder syntax? Well, I tried it, and it works great :-)
Let’s start with an example. This one’s about me drinking some beer. So here’s me:
public class Robbie {
private Beer myBeer;
@Inject
public Robbie(@Strong Beer freshBeer) {
this.myBeer = freshBeer;
}
public void startDrinking() {
myBeer.drink();
}
}
And here’s some beer:
public interface Beer {
void drink();
}
public class Duvel implements Beer {
public void drink() {
System.out.println("Duvel!");
}
}
public class StellaArtois implements Beer {
public void drink() {
System.out.println("Stella Artois");
}
}
The @Strong annotation basically means I’d like a strong beer, not just some water with taste. So I created a Guice BindingAnnotation for that, and expressed the binding in a module:
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.FIELD, ElementType.PARAMETER})
@BindingAnnotation
public @interface Strong {}
public class BeerModule implements Module {
public void configure(Binder binder) {
binder.bind(Beer.class).to(StellaArtois.class);
binder.bind(Beer.class).annotatedWith(Strong.class).to(Duvel.class);
System.out.println("Configured using Java implemented Guice Module!");
}
}
So everyone is getting regular beers, unless they specify they want some stronger beer. You could run this code like this:
public class StartGuice {
public static void main(String[] args) {
Injector i = Guice.createInjector(Stage.DEVELOPMENT, new BeerModule());
Robbie robbie = i.getInstance(Robbie.class);
System.out.print("Robbie starts drinking: ");
robbie.startDrinking();
}
}
This prints:
Configured using Java implemented Guice Module!
Robbie starts drinking: Duvel!
Hmm… tasty. Now, let’s get us some scripting. I’ll thankfully use the new Java 6 scripting support, you could probably use the BSF as well. Also, I’ll use Jython for scripting, a Java Python implementation. So I throw in jython.jar, jython-engine.jar (from the scripting site), aopalliance.jar next to the guice.jar. By the way, if you want to know how all this scripting support stuff works, check out Jurgen’s excellent introduction.
Anyway, let’s try binding our dependencies in Python. Create a file called BeerBinder.py that looks like this:
import java
from scriptguice import *
def configure(binder):
binder.bind(Beer).to(StellaArtois);
binder.bind(Beer).annotatedWith(Strong).to(Duvel);
print "Configured Guice using Python method!"
Then we add some scripting magic to our Guice Module, so that we delegate the configure call to the Python script:
public class BeerModule implements Module {
public void configure(Binder binder) {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine python = mgr.getEngineByName("python");
Reader reader = ReadUtil.getReaderForClassPathResource("scriptguice/pythonmethod/BeerBinder.py");
try {
python.eval(reader);
Invocable invocablePython = (Invocable) python;
invocablePython.invokeFunction("configure", binder);
} catch (ScriptException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
}
If we run StartGuice again, the output now looks like:
Configured Guice using Python method!
Robbie starts drinking: Duvel!
Great, it works! Now let’s take it one step further and get rid of the ugly Java / Python mix. Python all the way! Create a file called BeerModule.py:
import java
from scriptguice import *
from com.google.inject import *
class BeerModule(Module):
def configure(self, binder):
binder.bind(Beer).to(StellaArtois);
binder.bind(Beer).annotatedWith(Strong).to(Duvel);
print "Configured using Python implemented Guice Module!"
# Factory method that returns new BeerModule
def getBeerModule():
return BeerModule()
So we created a class called BeerModule, and subclassed the Java class com.google.inject.Module. Jython really starts to shine here. Let’s do some magic to get the thing back in Java:
public class StartGuice {
public static Module getPythonBeerModule() {
ScriptEngineManager mgr = new ScriptEngineManager();
ScriptEngine python = mgr.getEngineByName("python");
try {
Reader reader = ReadUtil.getReaderForClassPathResource("scriptguice/pythonclass/BeerModule.py");
python.eval(reader);
Invocable invocablePython = (Invocable)python;
return (Module)invocablePython.invokeFunction("getBeerModule");
} catch (ScriptException e) {
throw new RuntimeException(e);
} catch (NoSuchMethodException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
Injector i = Guice.createInjector(Stage.DEVELOPMENT, getPythonBeerModule());
Robbie robbie = i.getInstance(Robbie.class);
System.out.print("Robbie starts drinking: ");
robbie.startDrinking();
}
}
It’s been a long time since my last beer, so here we go:
Configured using Python implemented Guice Module!
Robbie starts drinking: Duvel!
Man, how cool is this? Now we have defined the entire Guice module in Python code, and I got drunk in the process. Life just doesn’t get any better, does it ;-)
Now you could take it even further and return an array of Modules or what not, which is probably what you want in a real world app. Oh and one final note: don’t just copy paste this code. Close the Reader and stuff. I’m just being lazy for the sake of the example.
Thanks to Bob Lee and Kevin Bourrillion for creating Guice, the coolest DI framework on the planet.
