This tutorial series assumes you are familiar with golang, as we will be using it thorough this article series.
independence of external agencies rule means to keep your codebase loosely coupled from external services, APIs, or third-party systems
Basically what you want to do is depend on interfaces, not implementations.
You want your core logic to:
Your business logic should depend on interface and not on implementation.
Lets say we want to include stripe payment processor for our Orders.
This would be a good example on how to do it:
type PaymentProcessor interface {
Charge(amount int) error
}
type OrderService struct {
payment PaymentProcessor
}
func (s *OrderService) Checkout(amount int) error {
return s.payment.Charge(amount)
}
Than instead of calling stripe directly from a service you would implement your interface:
type StripeClient struct{}
func (s *StripeClient) Charge(amount int) error {
// call Stripe API here
return nil
}
Now stripe is just a single implementation that you inject:
service := OrderService{
payment: &StripeClient{},
}
By doing interfaces, you enable yourself to easily mock it during tests:
type MockPayment struct{}
func (m *MockPayment) Charge(amount int) error {
return nil
}
What are the benefits of coding it this way:
We’ve learned a bit how to handle external api calls. We’ve also learned about best practices about them - handle them through interfaces. We’ve also learned why it matters.