Today I want to talk about handling your waste properly.
Keep your waste in a trash can
Do not let waste pollute your code. Do not mix infrastructure with business logic.
All starts with the single responsibility principle. When implementing business logic, questions arise. Can this still be considered 'single responsibility'? Or do I need to split the calculation? There are compromises to be made. And as long as the result is readable, it is sound approach.
This is not the case for infrastructure code. Even minor leak of infrastructure into your business logic makes huge damage. Your logic becomes
- Difficult to test
- Difficult to maintain
- Fragile
Let's take an example here. We have a calculation, which needs to read current price from a WCF service.
interface IPricingEngine
{
decimal GetPrice(string isin);
}
class Calculator
{
public Calculator(IPricingEngine pricingEngine){/*....*/}
public ResultType Calculate()
{
/* .... */
var price = this.PricingEngine.GetPrice(isn);
/* .... */
}
}
This is correct. In real world, the pricing engine is not likely to be so nice. You might need to authenticate your calls. You might need to have a connection pool. You might need to try backup url or a different API version. You might want to log all calls.
This is all infrastructure. To implement any such requirement, you should never modify the Calculator class. Everything should be hidden within the IPricingEngine implementation.
Recycle
So you have IPricingEngine service contract and plain WCF client. Now you need to add all the infrastructure bits and pieces to make it work.
Wait... Logging... Connection pooling... Authentication.... Sounds quite independent on pricing engine, right?
Right, you will need most of them again for your next service.So make your waste recyclable. Make your infrastructure reusable. The most efficient way to build reusable infrastructure components is interception. See decorator and interception design patterns.
What's in it for me?
Your business logic is protected from all infrastructure peculiarities. Clean. Easy to change. Easy to test. Easy to fix.
Your infrastructure is a set of composable and reusable components.
There is no coupling between business logic and infrastructure. They can and will evolve independently.
No comments:
Post a Comment