In C# we have Extension methods
.
Extension methods enable you to add methods to existing types without creating a new derived type, recompiling, or otherwise modifying the original type.
An extension method is a special kind of static method, but they are called as if they were instance methods on the extended type.
However in one of our lesser design moments, we started replacing concrete classes which contain business logic and moving them to Extension Methods
.
The advantages seemed neat at first e.g we could replace something like this (very simplified example).
var AddressUtils = new AddressUtils();
AddressUtils.CleanAddress(order);
var ValidationUtils = new ValidationUtils();
ValidationUtils.ValidateCustomer(Order);
with
Order.CleanAddress();
Order.ValidateCustomer();
I.e we were replacing a lot of Stateless instantiable Classes with short-hand static methods (syntactic sugar) that made the code more readable. This has really never sat well with me.
We now have a bunch of static classes with miscellaneous methods in them, the vast majority aren't even generic or interface driven. I.e single use.
Adding to this there is this common notional that static classes are not a good fit for test driven development.
So the alternatives really are
- Go back to concrete util style helper classes
- And/Or Encapsulate the logic in some sort of DI service
- Or add the logic to the Model it self.
- Or having reusable logic sprinkled out over the various services that need to use them.
In regards to the second last option, order (as most of the the models) are actually Data entities, (and that once again) doesn't seem right (or even feasible) to push the business logic down to the domain models
So i'm left with (unless there are some better patterns) helper classes, Extension methods, DI services, some sort of entity based logic, or a unpredictable spaghetti factory.