How many types is too many for an object?-Collection of common programming errors

A class could extend 12 interfaces, but if those 12 contracts represent an intersection of behavior such that the object still has just one responsibility, that is A-OK. Time and again, in large enterprisey projects the pieces which are most difficult to maintain are the classes which try to do too many different things. Here’s an example:

An application which does routing and recommendation for first responders (police, fire, etc) has a class Mapping, which does:

  • geocoding and reverse geocoding (turning lat & long into an address, and vice-versa)
  • drawing the map image to screen, with traffic and routing ‘highlights’
  • finding routes between different locations
  • analyzing traffic patterns provided by third party data sources

The original designer of the system must have thought “well, these are all map & location related tasks, so yeah this should be one class”. Unfortunately, this made it impossible to change one of those bits of functionality later because everything was so tightly coupled.

Find seams in the functionality provided by various components in your application. Separate those seams into cohesive contracts (interfaces) between the components, where each unit is capable of providing a valuable ‘service’ (not in the webservice sense) to its consumers. To go back to my previous example, we eventually broke up the Mapping class (Project Yoko) into:

  • Geocoder
  • MapRenderer
  • RouteRenderer
  • RouteBuilder
  • TrafficRenderer (inherited from RouteRenderer)
  • TrafficDatasource

The individual components had runtime resolved dependencies, which allowed us to introduce Unit and System Tests, finding several bugs in the pre-existing routing logic, besides providing a host of other benefits. In general, if you can see a logical separation of responsibilities in a class, you probably should break it off.