Home > Anti patterns, Software engineering > Anti-Pattern ‘Validation by Execute ‘n’ Rollback’

Anti-Pattern ‘Validation by Execute ‘n’ Rollback’

February 21st, 2012 Leave a comment Go to comments

Recently in some reviews I saw an anti-pattern. First you have to know, in the code, there was a validation of the data before it was stored in the database. So far so good. But when I looked at the validation code, I saw the following:

public void Validate()

And the persist logic (with some business logic) looked like this:

public void Process()

So, I asked myself, what the Boolean means. Well, here is the method signature:

public void DoProcess(bool bValidate)

Hmm, the code looks quite magic so far and the argument (and the method name) itself is more or less an anti-pattern already. But when I checked the DoProcess method, I saw something more or less like this:

public void DoProcess(bool bValidate)
	using (SqlConnection con = new SqlConnection(connectionString))
		SqlTransaction transaction = con.BeginTransaction();
		// Some business logic here...


Fotolia_20233238_SThe idea behind this code is, if it could be executed successfully, that means a successful validation. If there are any problems during the execution, those problems are the result of the validation. The execution itself wouldn’t be a problem after a successful validation (now I need a drink…).

Doing it better

It’s easy to find bad things, but it’s sometimes harder to do things right. But in this case, the better way is easy. First, you have to separate your business logic from the data access logic. This means following the separation of concern principle.

The next point is, that you’re able to validate your model. So put the logic where it should be. If you use a domain model, the logic to validate an entity has to be on that entity. Or if you have a table module approach, the logic to validate an entity has to be on the corresponding table module.

Side effects

There are also other problems with this anti-pattern. There are some side effects with the data.

As you know, transactions should be as short as possible to prevent lock problems with your data. But if you have combined the business logic and data access logic, your transactions are much longer than needed. To make it worse, this anti-pattern forces you to do it at least twice.

There are reasonable use cases for dirty reads: For example fast searches. In this case you accept dirty reads and you don’t want any locks on your data in the database. Normally, the chance to have a dirty read isn’t that high, but with this anti-pattern the chances to get a dirty read are significantly higher.

If you like this, follow me on twitter…

Categories: Anti patterns, Software engineering Tags:
  1. February 22nd, 2012 at 13:46 | #1

    This code also violates SRP. Usually a boolean flag like the one you showed above is a hint for that.

    Thanks for the post

  1. No trackbacks yet.