Always Get Better

Never stop looking for ways to improve

May 9th, 2011

Suppose we are building a Facebook application and have a variable called fb.appId containing our Application’s ID. We want to use that to initialize an FBJS call, but obviously don’t want to hard-code it into our page’s template.

Using the template engine in Play! framework, we can make direct calls to the underlying Java framework as long as we use the full namespace path. Our Facebook Application Id is accessible like this:


${play.Play.configuration.get("fb.appId")}

If we’re making a lot of configuration calls, we can simplify our lives by aliasing the namespace path:


%{
cf = play.Play.configuration
}%
${cf.get("fb.appId")}

Conditional Statements
Let’s go a step further. Suppose we have Google Analytics and only want the JavaScript to run when our site has been deployed to production (I covered a similar technique earlier this year using Ruby on Rails).


#{if play.Play.configuration.get("application.mode") == 'PROD'}
GOOGLE ANALYTICS CODE - WILL ONLY DISPLAY IN PRODUCTION
#{/if}

February 8th, 2008

Here’s a geeky party trick:

Abstract classes in Java cannot be instantiated. Here we’re going to consider ways in which a button can be programmed within a JPanel. ActionListener is used to react to the button event, but ActionLister is an interface (pure abstract class) so in order to use it you have to derive a class from it and implement actionPerformed.

For example, you can’t do this:

ActionListener buttonListener = new ActionListener();

You have to do this:

public class ButtonListener
{
public void actionPerformed( ActionEvent event )
{
}
}

ButtonListener buttonListener = new ButtonListener();
ourJButton.addActionListener( buttonListener );

However, this code is valid:

ourJButon.addActionListener( new ActionListener() {
public void actionPerformed( ActionEvent event )
{
}
} );

What’s going on? It would appear that we are instantiating a new ActionListener and giving it an actionPerformed() method. We’ve succeeded in giving our button a listener without first creating a class to handle the event.

Anonymous Inner Classes

Of course we aren’t really instantiating ActionListener – it was a trick. What this does is create an anonymous inner class only in this part of our code. Check it out – when you compile your code, javac will create extra class files for our ActionListener.

For one-off buttons, using anonymous inner classes is an excellent way of reducing code bloat and improving the readability of your programs. There are drawbacks of course, which I’ll go into detail in another article, another day.