In my project’s core library we have a very big class, which is tending to become a God object. One of the reasons is that, over a period of time, tasks which should have been in different modules have been put into this class. For ex –
class HugeClass{
public void DoModuleXJob(){}
public void DoModuleYJob(){}
}
One of the problems in refactoring and moving the unwanted, module specific behavior out of this class is that it will be a lot of work for Module X and Module Y to change their code.
As a work around I was thinking about converting these methods into extension methods and then move them to their concerned modules. For ex –
// in module X
static class HugeClassExtensions{
public static void DoModuleXJob(this HugeClass instance){}
}
// in module Y
static class HugeClassExtensions{
public static void DoModuleYJob(this HugeClass instance){}
}
I found that this does not create any compilation problems, as long as Module Y is not using DoModuleXJob and vice-versa, which I am sure about.
Is this a good solution and are there any better methods in such a case?
This is not a bad intermediate step, as it at least gives you a way to partition out the functionality and prove that there are no method inter-dependencies between the extension ‘modules’. That’s a great first step toward creating true subclasses, though it’s still not ideal (you can’t instantiate the module classes individually for unit testing.)
Once you have this partitioning, it should make it easier to create new classes, as you’ve already identified the module boundaries. The process would go like this:
The parameter passed to the extension method becomes a field on the new class, which is set in the constructor.
All of the extension methods become methods of the new class.
You can now extract an interface for the main class, so the sub-classes no longer depend on the full implementation. In some cases, you might be able to further reduce dependencies by breaking the functionality into multiple interfaces
Now that you have dependency isolation through interfaces, you can write unit tests for individual modules.