Java – Improving Cohesion and Coupling of Classes

couplingjavaobject-oriented

I am given this set of code and need to suggest ways to improve the code's cohesion and coupling of the classes. But I thought these classes are quite well de-coupled since it looks like they are making use of events. And in terms of cohesion, all the init() calls are placed together, everything seems quite alright to me.

public class A
{
    private C t;
    private B g;
    public static void main(String args[]) {
        // Creates t and g.
        t = new C();
        t.init();
        g = new B();
        g.init();
        g.start(this);
    }
    pubic void update (Event e)
    {
        // Performs updating of t based on event
    }
}

public class C
{
    public C() { ... }
    public void init() { ... }
}

public class B
{
    public B() { ... }

    public void init() { ... }

    public void start(A s) {
        e = getNextEvent();
        while (e. type != Quit)
            if (e.type == updateB)
                update(e) ;
            else
                s.update(e) ;
        e = getNextEvent();
    }

    public void update(Event e) { ... }
    }
}

Are there still ways to improve the classes cohesion and coupling? It looks ok to me but I think I am missing something out.

Thanks for any suggestions on this.

Best Answer

Is the updating of t in A similar/the same as the update method in B?

If that's the case, then you can move that update logic into C.... but then you'll notice that B and C are duplicating behaviour... and can be 1 class instead, or at least can implement shared behaviour from a separate class (depending on what's in 'start()')

Reducing the coupling at that point, you can create an interface that defines init and update functionality (again, possibly 'start' as well... post the content and we might be able to better work with it).

I also wonder what init does, because if 'start' can't be called (and doesn't throw an exception if init isn't called) until init is called, then the object is possibly in an invalid state after construction. You might be able to take the logic from init and put it into 'start' or the constuctor.