Refactoring To Smaller SRP Service Objects

Currently I’m going through a very procedurally driven code base and attempting to break code out into smaller service objects called by the main class.  The code I’m working with deals with creating, validating, fetching and saving orders for our products.   I’m doing this refactoring for a couple of reasons.

First of all I want to have code collected into service objects that have similar functionality.  Ideally I’d like each service class to comply with SRP, and have only one reason to change.   There are many methods in the original code base that deal with creating orders, so I’ve factored those out into an “OrderBuilder” class.  This class is concerned with putting an order together.  I’ve broken out code that has to do with persisting an order into an OrderDataManagement class.  Not only does this better adhere to SRP, but by doing this it seems easier for me to find the code I’m looking for.  Business rules for building an order are in the “OrderBuilder” class instead of buried in a much larger “OrderManagement” class.

The second reason I’m doing this is to make things easier to test.  In the original code I could mock a data connection, but if I wanted to test anything else I had to account for everything  going on around the behavior I was testing.  By breaking out the code into smaller more cohesive and less couples service objects I can mock the behavior I’m not interested in, and focus soley on what I’m trying to test.  This is allowing me to add tests for new or changed functionality much faster, and tests aren’t nearly as brittle as before.

So far so good, hopefully I’ve made things better, we’ll see how I feel in a few days.

Leave a Reply

Your email address will not be published. Required fields are marked *