Home > database >  How to represent dependency injection with generics in UML class diagram?
How to represent dependency injection with generics in UML class diagram?

Time:03-09

I'm having trouble representing the following piece of code in a UML class diagram:

public class Test {
    // something
}

public class Bar<T> {
    private T item;

    public Bar(T item) {
        this.item = item;
    }

    // something
}

public class Foo<T> {
    private Bar<T> bar;

    public Foo(Bar<T> bar) {
        this.bar = bar;
    }

    // something
}

public class Caller {
    private Test item;
    private Foo<Test> foo;
    private Bar<Test> bar;

    public Caller() {
        item = new Test();
        bar = new Bar<Test>(item);
        foo = new Foo<Test>(bar);
    }

    // something
}

As of now, I thought to represent it this way:

This Way

Since I know you can't directly bind an association, but you need a bound class first. I don't know if it's correct and, if it is, wouldn't this result in a much more complex diagram when there are more classes?

CodePudding user response:

Complete your diagram?

The assumption that an association cannot be bound seems unfounded. According to the UML specs, a classifier can be templated, and a template can be bound. This is straightforward for classes. Associations are also classifiers, and I found no evidence that the general rules don't apply to them.

You may therefore very well complete your diagram if you think it increases readability. Use the same notation: add an association between Foo_Test and Bar_Test, as well as a «bind» arrow from that association to the template association (btw. it may seem weird to link with an arrow two lines, but even if it’s rate, it’s legit; generalization are also possible for associations, see enter image description here

Ideally, the bottom part would be in a separate diagram. But if you keep it,, you may avoid the association between Bar and Test (since it is deduced from a item: T in the template), unless you think it is important.

  • Related