Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 224
Judah Gabriel Himango Avatar asked Oct 09 '08 20:10

Judah Gabriel Himango


1 Answers

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);
      }
   }
}
like image 72
Mark Brackett Avatar answered Oct 18 '22 07:10

Mark Brackett