Excommunicating Your God Classes

God classes are classes that have too many responsibilities. They do too much and have too much knowledge of other parts of the application. I'm not going to explain what dependencies are. :)

I have realised that I tend to create god classes with too many dependencies because I have a strong subconcious desire to avoid ending up with lots of classes. So I try to group things into related classes, even when they are not very closely related (low cohesion).

Consider the example of a fleet tracking system. I have to add functionality to allow the user to dial a vehicle. I already have a VehicleController so my instinct is to create a VehicleController.Dial(vehicleIdentifier) action. The trouble is that dialling actually has very little to do with vehicles. Dialling is accomplished by making a http GET request to a third party. The Dial action method does not require any of the dependencies that the VehicleController class already has.

My final design has a new controller, DiallingController with a Dial action method. DiallingController has just one dependency, System.Net.HttpWebRequest to make the request. This design has higher cohesion and is easier to test. The downside is that it does lead to lots of classes, but I think that is the cost of good design and it is well worth the price.

Here is my new rule:

never add code to a class unless the code requires most of the dependencies of the class.


Comments

Comments are closed