Sunday, October 2, 2011

Final variables in groovy with dynamic constructors and @TupleConstructor

Up until groovy 1.8, it was not possible to declare variables in final as groovy when using the named constructor. Frequently with simple groovy objects, I would have a class that looks like this:

class Person {
String name
int age
}

It always bothered me that name and age could not be final. While I could declare an explicit constructor, such as

class Person {
final String name
final int age
public class Person(String name, int age) {
this.name = name
this.age = age
}
}

the explicit constructor is something the groovy helps eliminate the need for, and I always felt like it was a hassle to declare.

However, declaring variables final is generally recommended when you won't be modifying the variable, so I was torn. final ensures the variable is not set again when you didn't want it to be. When working with multiple threads, final fields guarantee visibility across threads when the object is constructed.

So in groovy 1.7, the options were to not make the variables final or to declare the explicit constructor.

Groovy 1.8 introduced the @TupleConstructor annotation. By annotating a class, another constructor is created that uses default values for all of the values.

@TupleConstructor
class Person {
final String name
final int age
}

So in this case, a constructor

Person(String name, int age)

is created.

Now both groovy and java classes can use this constructor, and the fields can be marked as final.

Note that the constructor fields are in the order the properties are declared, so be careful when reorganizing classes (and test, test and test some more).

Monday, May 2, 2011

Implementing the Decorator pattern using Groovy's @Delegate

Let's say we want to write a decorator around a List to add a creation time to the list. We've all written something like this before, and it usually looks something like:

public class ListDecorator implements List {

private final List delegate;
private final Date creationTime = new Date();

public ListDecorator(List delegate) {
this.delegate = delegate;
}

public Date getCreationTime() { return createTime; }

public void add(...) {
delegate.add(...);
}

public int indexOf(...) {
return delegate.indexOf(...);
}

// wrap all of the list methods
}


This is very tedious, and we still need to write tests to make sure we actually delegated to the right method.

Enter the groovy @Decorator annotation

// notice we don't need to implement the List interface here
// since we can take advantage of duck typing
class GroovyListDecorator
{
// all of the calls to the list methods will be delegated to this list
@Delegate final List delegate

private final Date creationTime = new Date()

GroovyListDecorator(List delegate) {
this.delegate = delegate;
}

Date getCreationTime() {
creationTime
}
}

And now we can use it like this:
def list = new GroovyListDecorator(new LinkedList())
// these methods delegate to the LinkedList delegate
list.add("abc")
list.add("def")
println list.size() // 2
println list.creationTime // Mon May 02 19:49:55 EDT 2011


And it's as easy as that.

Wednesday, December 8, 2010

Eclipse Hot Swap Debugging

Maybe this is a well known feature, but it was news to me. The Eclipse debugger supports swapping code out at runtime when debugging (JVM 1.4 and later). Ensure Build Automatically is enabled, then run your application in debug mode. When stopped at a breakpoint, change the code you want to change and save the file. The code will be automatically swapped into your application without restarting - pretty cool.

This article http://www.ibm.com/developerworks/library/os-ecbug/ gives some more details regarding debugging with Eclipse.

Tuesday, June 1, 2010

Anti-Patterns

While most good software development teams have knowledge of software patterns, I still don't hear teams frequently talking about anti-patterns. I'm not really sure why that is. It seems logical to me that if patterns are a way of communicating common ways of doing things, anti-patterns should be in a programmer's language to communicate how not to do things, and to identify problematic areas of code. Anti-patterns do also extend beyond code into management, organization, etc, but I will just focus on coding anti-patterns.

One that I see so frequently is copy-paste-mutate. That is, when a developer copies a block of code, pastes it somewhere else, and changes it slightly. Most of it is duplicated and now mistakes are duplicates and testing must be duplicated (if you are testing). If you find yourself copying and pasting, stop. Should the functionality be in an abstract class? Should it be in a utility class? Regardless of where it needs to go, it shouldn't be copied and pasted.

Another recurring anti-pattern is see deals with poor exception handling. It's way too common to see e.printStackTrace() or LOGGER.error(e) (or even worse, an empty catch block) as a solution to error handling. If you can "handle" the exception by just printing it out, maybe it shouldn't be an exception at all. Exceptions should indicate errors (i.e. exceptional cases) and your program generally shouldn't be able to continue to operate normally when one occurs without proper handling.

Wikipedia has a large list of anti-patterns here http://en.wikipedia.org/wiki/Anti-pattern#Software_design_anti-patterns. Take a look and see which of these traps you're falling into.

Monday, April 26, 2010

Eclipse Templates

You may notice in Eclipse when pressing ctrl+space to auto-complete that you get suggestions that are not necessarily code. For example, you can select main to auto create a public static void main(String[] args) method. You can also define your own custom templates (and view all the existing ones) by going to Window > Preferences > Java > Editor > Templates.

This is a nice feature if you haven't used it before. I particularly like being able to define a println template for System.out.println to make it easy to switch between groovy and java. Another common one I define is a logger template to create a logger variable. If you find yourself defining the same lines of code in many places, a template may be of use to you.

If you already use templates, it would be nice to share some common ones you use.

Wednesday, March 31, 2010

Passive Views and View Interfaces

User interfaces are inherently difficult to test since logic buried in the GUI can't really be tested without bringing up the entire system, and this is not really practical for unit (or even integration) tests. It's common to say "Extract the logic outside the GUI" but in practice, I don't see it done as much as I think it should be.
First, let's distinguish between a passive view and and active view. An active view tends to register itself with the model, listen for changes, and update itself. The following code would be typical in an active view:

public class MyView {

public void init() {
model.addPropertyChangeListener(this);
}

public void propertyChanged(PropertyChangeEvent evt) {
String propName = evt.getPropertyName();
if ( propName.equals("prop1") ) {
updateViewWithProp1Change();
}
else if ( propName.equals("prop2")) {
updateViewWithProp2Change();
}
// ... etc ...
}
}

Typically the updateViewWithPropXXXChange methods would read the new value of the property and determine what to display on the view. To give a concrete example, imagine a view that updates a temperature display.

public void updateTemperatureDisplay(double newTempFarenheit) {
if ( mode.equals(FARENHEIT) ) {
tempLabel.setValue(Double.toString(newTempFarenheit));
}
else if ( mode.equals(CELSIUS) ) {
tempLabel.setValue(Double.toString(toCelsius(newTempFarenheit)));
}
}

In this example, the view does the conversion to Celsius. This logic is now difficult to test without showing the temperature display. This view is active. It's fast to write because the logic is contained in here, but difficult to test.
A passive view on the other hand can be thought of as a "dumb" view. It displays what it is told.

public interface MyPassiveView {
void setTemperatureText(String value);
}

public class MyPassiveVewImpl implements MyPassiveView {
public void setTemperatureText(String value) {
tempLabel.setText(value);
}
}
public class MyController {
private MyPassiveView view;

public void updateTemperatureDisplay(double newTempFarenheit) {
String temperatureText = "";
if ( mode.equals(FARENHEIT) ) {
temperatureText = Double.toString(newTempFarenheit);
}
else if ( mode.equals(CELSIUS) ) {
temperatureText = Double.toString(toCelsius(newTempFarenheit)));
}
else { // handle error }
view.setTemperatureText(temperatureText);
}

Now all the view does is set the label text. This is more work but the controller can be independently tested from the view. Notice in this example also the view implements an interface. View interfaces greatly simplify testability and make many of these patterns possible. I think this is frequently overlooked by developers and the view ends up being a concrete class.

There are various patterns that fall along this line, notably model-view-controller, model-view-presenter, and supervising controller all with varying degrees of passiveness. These can all be found on Martin Fowler's website (http://martinfowler.com/), and many other results can be found by a simple search.

Wednesday, March 17, 2010

Launching a process in groovy

Just a quick little groovy tid-bit here. If you've ever launched an external process in Java, you know what a pain it can be. Groovy makes it quite simple. You can execute a process from a string by using the execute method. A simple example would be "ls -al mydir".execute(). That's it.