I found it rather common that developers have only a vague idea of what business logic is. I also sometimes find it hard to describe it myself, even though I’ve spent many hours of my career working with it.
So let’s try to clarify things. Business logic is core logic, that doesn’t have anything to do with technology. It is the logic that can be found as rules in the business even though there were no digital system implemented. What is considered as core to a business, is the activities that they gain money of.
Let’s take the example of a booking that gets cancelled. Business logic are the rules that kicks in with freeing up resources (hotels, cars or whatever is booked), confirm cancellation to customer, and refund money. Technically how this is done; by updating a database, which technology that is used to send an email or which payment solution that is called to refund the money, is not business logic. The technology should be exchangeable.
Business logic should be kept separate from the other logic in the system and it is worth a considerable effort to have a lot of automated testing here to verify that the rules are not broken.
Business rules vs. Use case
Business logic is often divided into two different types: Business rules and Use cases. First, I will address that there might be some naming confusion here, when it comes to business rule vs. business logic. The business rule is something that exists in the business even without a computer, while the business logic is the code that implements the rule.
When implementing business rules, it is very common that it is some kind of flow in which the rules are called. This flow can be implemented in something called Use case. Other names might be Service or Domain service.
Use cases are easily mapped to the requirements which are preferably defined as test cases. If implementing automated acceptance tests following the test cases you get a good assurance that the functionality that you have agreed with the customer or business is working.
Use cases are classes containing the flow for a use case. They can call repositories to save data, or they might call the domain model classes that performs the business rules.
E.g. when a booking is cancelled the hotel rooms should be made available to other bookings. It is the responsibility of the use case to make sure that this is included in the flow, but it is the domain model’s responsibility to know how a hotel is marked as available (maybe by changing the status).
As I wrote earlier, there is much value in automated testing of business logic to make sure that these rules work according to spec. Write acceptance tests testing the Use cases, and write unit tests that tests the business rules:
As we know reality is often a lot more complex that these simple examples. But this can be used as a starting point from which we continuously search for more knowledge. Why not continue by reading this blogpost by Uncle Bob?