Search code examples
javadesign-patternsarchitectureoverridingdelegation

Java - Is delegation the good solution in this case?


Here is my question :

I have a huge class (HugeClass) and I wanted to split it into several little classes (LittleClass1, LittleClass2, ...). I heard about delegation. It sounds good, but I think it cannot works in my case. Indeed, my little classes need some of the attributes of HugeClass:

public class  HugeClass
{
    // Attributes
    private Object object1;
    private Object object2;
    private Object object3;
    ...
    private Object objectN;

    // Delegation 1
    private LittleClass1  little1 = new LittleClass1 ();

    // Function delegated in the LittleClass1
    public void  delegated1 ()
    {
        little1.delegated1 ();
    }

}

Here an example of a Delegation class :

public class  LittleClass1
{
    public LittleClass1 ()
    {

    }

    public void  delegated1 ()
    {
        // Here, I need object1, object3, and more to work !
    }

}

The number of attributes needed by the delegated1 function can be large. So I think using the constructor of LittleClass1 is not very convenient.

And because LittleClass1 override only one method of HugeClass, I don't think that LittleClass1 should extends HugeClass.

Do you have an idea of a solution ? Using another pattern ?

Thanks !

Update

Delegated functions might need not only instance variables, but also instance functions :

public class  LittleClass2
{
    public LittleClass2 ()
    {

    }

    public void  delegated2 ()
    {
        // I need object2 and delegated1 to work !
    }

}

Giving HugeClass to the constructor might solve this problem. But is this a good solution ?


Solution

  • Breaking up a huge class into smaller classes is generally good to improve the maintainability, testability and overall quality of the code. The smaller chunks should be easier to reason about in isolation. What you want is to look for semantically distinct features of the huge class, and split them apart, first by extracting methods, and then by extracting classes. You're not necessarily looking for a pattern, as much as looking for refactoring techniques, like the ones in the books Refactoring and Working Effectively with Legacy Code.

    Now, if your little classes seem to share too many of the instance variables of the huge class, maybe you should take a step back and start with some low hanging fruits, like code that doesn't depend on too many variables; or try to find a grouping of those variables that semantically make sense to be encapsulated in a new object, what would decrease the number of these free variables and increase the quality of the design, as finding the latent concepts in the design make the code more explicit and understandable.

    UPDATE: by the way, inheritance is really not a good idea. You want to decouple the concerns, and inheritance is just another more subtle way of coupling.