Search code examples
design-patternscoupling

Coupling is too high - how to design this class better?


Running FxCop on my code, I get this warning:

Microsoft.Maintainability : 'FooBar.ctor is coupled with 99 different types from 9 different namespaces. Rewrite or refactor the method to decrease its class coupling, or consider moving the method to one of the other types it is tightly coupled with. A class coupling above 40 indicates poor maintainability, a class coupling between 40 and 30 indicates moderate maintainability, and a class coupling below 30 indicates good maintainability.

My class is a landing zone for all messages from the server. The server can send us messages of different EventArgs types:

public FooBar()
{
    var messageHandlers = new Dictionary<Type, Action<EventArgs>>();
    messageHandlers.Add(typeof(YouHaveBeenLoggedOutEventArgs), HandleSignOut);
    messageHandlers.Add(typeof(TestConnectionEventArgs), HandleConnectionTest);
    // ... etc for 90 other types
}

The "HandleSignOut" and "HandleConnectionTest" methods have little code in them; they usually pass the work off to a function in another class.

How can I make this class better with lower coupling?


Solution

  • Have the classes that do the work register for events they're interested in...an event broker pattern.

    class EventBroker {
       private Dictionary<Type, Action<EventArgs>> messageHandlers;
    
       void Register<T>(Action<EventArgs> subscriber) where T:EventArgs {
          // may have to combine delegates if more than 1 listener
          messageHandlers[typeof(T)] = subscriber; 
       }
    
       void Send<T>(T e) where T:EventArgs {
          var d = messageHandlers[typeof(T)];
          if (d != null) {
             d(e);
          }
       }
    }