When inheritance is not enough

16. September, 2010

Ever had the problem that inheritance just wasn’t enough? For example in this case:

package core;
public class Main {
    public static void main(String[] args) {
    private static void sayHello() {
        System.out.println("Hello World!");

Say you need to override sayHello(). What are your options?

You could edit the source. But if you only have the bytecode?

You could decompile the bytecode. But what if you need the same change in several places?

Eventually, you’ll have to use copy more or less code around because Java just doesn’t offer enough ways to combine code. The solution? Object Teams. See this article for a solution of the problem above.

What is Object Teams?

In a nutshell, a team is a group of players which have roles. Usually, the roles are distributed by way of the strengths of your players. Slow and sturdy ones will be defense. Quick and agile players will attack. The calm ones will do tactics.

OT/J (the Java implementation of Object Teams) does just that: You define teams and roles and then apply those to existing Java code. Let’s take the Observer pattern (you know that design patterns are workarounds for flaws in the language’s design, yes?).

The problem with this pattern is that you can’t apply it retroactively. You must modify the involved classes to support the pattern even if they couldn’t care less. That leads to a lot of problems. Classes which don’t need it must still allocate resources for it. It clutters the API. You can’t add it to classes which don’t support it. If a class only allows you to observe some behavior, you can’t change that.

OT/J fixes all that. The OTExample Observer shows three classes which could make use of the Observer pattern but don’t. Instead, the pattern is retrofitted in all the places where it’s necessary. This allows for many optimizations. For example, you can create a single store for all your observers (instead of one per instance). The API isn’t cluttered. You can observe almost any change.

%d bloggers like this: