Search code examples
c#sqlarchitecturetransactionsbusiness-logic

Why business logic?


Let's imagine any common operation being executed on website.

After user presses button the application should:

  1. Check conditions whether the operation is allowed or not (user rights, some object's consistency, relations and other things)
  2. Update DB record
  3. Report

This is business-logic layer's concern as it's written in tons of books. In fact, we firstly read data from DB then we write data to DB. And in the case when data were changed by any other user/process during our checkings we will put invalid result into the database. Seemes like the problem should be well-known but i still can't find good solution for this.

The question is: why do we need business logic layer with no opportunity to maintenance business transactions?

You probably would say TransactionScope. Well, how do you prevent read data from its changes by external processes? How it's possible to UPDLOCK from business layer? If it's possible then wouldn't it all be much more expensive than doing transactions in stored procedures?

No way to bring a part of logic to DB - only the whole. Both parts #1 and #2 must be implemented in the same transaction, moreover, read data must be locked until updation has been made.

Ideas?


Solution

  • I really think you are arguing this from the wrong angle. Firstly, in your specific example, there doesn't seem to be anything saying that the change in votes by one user invalidates the attempt of another user to affect an upvote. So, if I opened the page, and there were 200 votes for the item, and I clicked upvote, I don't really care if 10 other people have done the same in the meantime. So, validations can be run by the business layer, and if the result is that the vote can go through, the update can be done in an atomic way using a single SQL statement (E.g. UPDATE Votes SET VoteCount = VoteCount+1 WHERE ID=@ID), or a select with UPDLOCK and update wrapped in a transaction. The tendency for ORMs and developers to go with the latter approach is neither here nor there, you still have the option to change the implementation if you so choose.

    Now, if the requirement is that an update to the vote count actually invalidates my vote, then it's a completely different situation. In this case, we are absolutely correct to use either optimistic or pessimistic concurrency, but these are (obviously) not applicable to a website where hundreds of people may vote at the same time, for the same item. The issue here is not the implementation, it's the nature of allowing multiple people to work on the same item.

    So, to summarise, there's nothing stopping you from having a business layer outside of the DB and keeping the increment atomic. At the same time, you hopefully enjoy the benefits of having your business logic outside of the DB (which is a post in itself, but I'd argue that it's a large benefit).