Should the Data Access Layer Contain Business Logic

Should the data access layer contain business logic?

Data access logic belongs in the data access layer, business logic belongs in the business layer. I don't see how mixing the two could ever be considered a good idea from a design standpoint.

Should Business Logic Layer access the DB/Data Access Layer?

Definitely not the first option, which embeds your business logic in the controller. The problem is not that the controller accesses data objects per se, but that a procedure dictated by business rules has to be followed. This procedure has no place in the controller.

So you should either go with the second option, or possibly make Cancel a method of Order. If you have already written similar code just go with consistency.

is it good to make Data Access Layer a separate layer from service layer

Looking at architecture you are discussing in question, your project must be large enough to justify development cost of it. For small projects this architecture will be overkill.

Assuming your project is large enough, yes; it is always good to separate DAL, BLL and Application layers. Refer this and this.

The benefit is clean separation which improves understanding, given you control over each part and reduces maintenance cost.

On other hand as you said, cost is obvious (another layer, another round of I/O). Yes; that is why my first paragraph discusses about size of project. In large projects, it's a trade-off; you are choosing one over other.

In large projects, primary objective should be maintainability IMO. Understand that premature optimization is the root of all evil. So, you start with good maintainable architecture. Each technology recommends basic rules for improving performance; implement them initially. If you see any performance issue over the time, find and fix it. In fact, due to separated layers, it is easy to find bottleneck.

There are other benefits as well. You can unit test each layer separately. You can work on each layer independently for anything like improving performance, shifting technology etc. Debugging will be too easy.

Pulling out business logic from the data access layer

Based on your description, you should definitely separate both layers right now, when the application is still small. You might feel a BL is useless when you're just accessing and displaying data, but with time you'll find the need to modify, transform, or manipulate the data, like coordinate object creation from different tables, or update different tables in a single action from the user.

The example you provided helps to support this idea, although is quite simplified.

Pablo's answer does offer some good design ideas too: you should definitely use an ORM to simplify your DAL and keep it very thin. I've found NHibernate and Fluent make a very good job on this. You can use the BL to coordinate access using Data Access Objects.

How should my business logic interact with my data layer?

In general, what I use to do is:

Data layer:

For data access, I create an Interface, for each object. Each interface lists all the public data access methods for the object in question. To hold the data, I create container types, for each object as well, which can be structs or simple classes only with data. I also rely on language data set, like lists, to hold my data, so I not linked to a particular database type. After that, I create a class that implements the data interfaces, this class has all SQL and access the database, so in case of change in the data storage technology, this is the only class that will be changed.

Business layer:

Does all the logic with data, how to validate, wich methods from the data interfaces should be called and in which order. This class receives and "send" data to the data storage or GUI, using containers (lists for example) where the data types are my containers mentioned above.

GUI:

Calls business logic methods and show / format data presentation. There's no logic here other than call the right methods of the business logic.

Small code example of a container (C#)

    //Interface for Department class data access. DataStorage assembly

namespace DataStorage
{
public interface IDepartmentDS
{
void Open(); //Open data conection
void Close(); //Close data conection
List<Repositories.Department> List(); //Gets all departments (from data base)
}
}

//This class holds all data regarded a department. There's no logic here. Repositories assembly

namespace Repositories
{
public class Department
{
[Browsable(false)]
public Department()
{
}

[Browsable(false)]
public Department(String Symbol, String Name)
{
this.Symbol = Symbol;
this.DeptName = Name;
}

public Department(Department department)
{
this.Symbol = department.Symbol;
this.DeptName = department.DeptName;
}

[Browsable(false)]
public String Symbol { get; set; }

public String DeptName { get; set; }
}
}

//This class implements the data manipulation itself, accessing the real database.
//However the data exchange outside this class is done via repositories classes and
//Generics - Lists mainly

public class DataStorage : IDepartmentDS
{
//Here I use to put generic functions to connect with the database, format stored
//procedure parameters list etc.

//Implementation of the List method declare in the Department Interface
List<Repositories.Department> IDepartmentDS.List()
{
String query = String.Format("SELECT * FROM {0}", DepartmentTable);
int rows = 0;
DataSet ds = ExecSqlCommand(query, out rows); //this method is private to this class

if (ds == null)
return null;

List<Repositories.Department> list = new List<Repositories.Department>();
foreach (DataRow row in ds.Tables[0].Rows)
{
list.Add(new Repositories.Department((String)row[DepFN_Symbol], (String)row[DepFN_DepName]));
//DepFN_Symbol and the others are just const variables representing the column index
}

return list;
}

}

public class DepartmentLogic
{
public DepartmentLogic()
{
.....
}

public List<Repositories.Department> GetAllDepartments()
{
//Here I create an Instance of the DataStorage but using the Department interface
//so I restrict the access to Department data methods only. It could be a good
//idea here to use the factory pattern.

IDepartmentDS department = (IDepartmentDS) new DataStorage();
department.Open();

List<Repositories.Department> departments = department.List();

department.Close();

return departments;
}

}

This Business logic example is, indeed, very simple, just shows how to retrieve data from Storage layer, but as long as you have access to data, you can manipulate it in the way you want. Just a comment here: maybe this solution should be re-thinked if implemented in a very busy server with thousands of requisitions because it can use lots of memory.

For the business logic and also UI point of view, all data are communicated between modules using general purpose containers like Lists. The link point between all those modules are the containers classes so all the classes are more less well decoupled.

UI makes requisitions to the Business logic classes, so it acts like a service provider. Doing in that way, changing the UI will not affect the classes below to it.

The Business logic requests and send data to the Data storage classes using general purpose data, so changing the data base / storage technology should not affect it.

That's the way I use to do and I'm trying to improve it ;)

Interaction between Business Logic Layer and Database Access layer

would it be bad practice to include the construction of SQL queries in the Business Logic Layer?

Most likely. The business layer should generally be database-agnostic.

I need to implement a procedure that gets data from database DB1, manipulates it, and then writes it into DB2

So you need two data layer objects - one to get the data from DB1 and one to save it in DB2. The "manipulation" can be done in either place (business layer or data layer), depending on the nature of the manipulation. For example, is it purely a data conversion, or does it depend on other aspects of the business layer?

Is a business logic layer necessary if I take logic out of the controllers?

Having a separate project for the domain/business layer has some advantages.

  1. Other layers can also use the domain/business classes you create without having to know about/reference the API layer and its dependencies.

Imagine Your API layer uses AbcCalculator (which you've defined in your API layer). If you want to use AbcCalculator in your Data Access Layer then you'd have to reference your API layer. Then you can't reference your Data Access Layer from your API layer because it's a circular dependency.


  1. When you write tests for your domain/business layer then your test projects won't need to reference the API projects and their dependencies.

  2. A separate project means developers won't accidentally reference objects that genuinely belong in the API layer, in the domain/business layer. This leads to difficulty in separating the layers later on because you end up with circular dependencies.

django models = business logic + data access? Or data access layer should be separated out from django model?

After three years of Django development, I've learned the following.

The ORM is the access layer. Nothing more is needed.

50% of the business logic goes in the model. Some of this is repeated or amplified in the Forms.

20% of the business logic goes in Forms. All data validation, for example, is in the forms. In some cases, the forms will narrow a general domain (allowed in the model) to some subset that's specific to the problem, the business or the industry.

20% of the business logic winds up in other modules in the application. These modules are above the models and forms, but below the view functions, RESTful web services and command-line apps.

10% of the business logic winds up in command-line apps using the management command interface. This is file loads, extracts, and random bulk changes.

It's very important that view functions and RESTful web services do approximately nothing. They use models, forms, and other modules as much as possible. The view functions and RESTful web services are limited to dealing with the vagaries of HTTP and the various data formats (JSON, HTML, XML, YAML, whatever.)

Trying to invent Yet Another Access Layer is a zero-value exercise.

What is the different between Model/Business Layer/Data Access and Repositories in the MVC architecture?

The following snippets are pulled from some tutorials on the MSDN, which you may find helpful:

Data Access Layer

When working with data one option is to embed the data-specific logic directly into the presentation layer (in a web application, the ASP.NET pages make up the presentation layer). This may take the form of writing ADO.NET code in the ASP.NET page's code portion or using the SqlDataSource control from the markup portion. In either case, this approach tightly couples the data access logic with the presentation layer. The recommended approach, however, is to separate the data access logic from the presentation layer. This separate layer is referred to as the Data Access Layer

Business Logic Layer

The Data Access Layer (DAL) created in the first tutorial cleanly separates the data access logic from the presentation logic. However, while the DAL cleanly separates the data access details from the presentation layer, it does not enforce any business rules that may apply. For example, for our application we may want to disallow the CategoryID or SupplierID fields of the Products table to be modified when the Discontinued field is set to 1, or we might want to enforce seniority rules, prohibiting situations in which an employee is managed by someone who was hired after them. Another common scenario is authorization – perhaps only users in a particular role can delete products or can change the UnitPrice value.
In this tutorial we'll see how to centralize these business rules into a Business Logic Layer (BLL) that serves as an intermediary for data exchange between the presentation layer and the DAL.

From a Code Project article, I found this description of the Data Access Layer's purpose to be particularly informative:

The data access layer provides a centralized location for all calls into the database, and thus makes it easier to port the application to other database systems.

I also located this blog post that does an excellent job of illustrating how the Business Logic Layer integrates with repositories:

Sample Image

Finally, here is Microsoft's definition of business logic:

Business logic is defined as any application logic that is concerned with the retrieval, processing, transformation, and management of application data; application of business rules and policies; and ensuring data consistency and validity. To maximize reuse opportunities, business logic components should not contain any behavior or application logic that is specific to a use case or user story.

I wish I could provide my own expert description of these layers, but I am also learning about this subject so I thought I would share what I had uncovered in hopes that we'll both be able to learn something from it. For example problems related to these layers, please refer to the tutorials I have linked above.

web service for business logic or data access layer

The question is too open ended so the answer is: it depends.

What needs do your applications have for the data? Is it just data access or some business logic involved? If it is just accessing of data, do you really want the client to have direct control over it? How similar are the three applications? Do they share functionality or just data?

As I see it there are two main paths you can chose:

1 - expose a web service for the business, with the data hidden behind the web service. This is a good setup if the three clients (I'll call the desktop app, web app and cell phone "clients" since that is what they are) share functionality (i.e. they are different views for the same business model). This avoids duplicating similar business logic in all the clients;

2 - expose the data directly with a web service. This is a good setup if the three clients have nothing in common but just use the same data for different purposes. But in this case, with the three sets of business logic, where are you going to put the logic? In the clients? How will that work for the desktop application (considering you install this desktop app 300 times or so)? You again need some service and the clients to be thin clients not thick ones.

If you take 1) and 2) into consideration you will see that usually it is better to have a service layer in front of your data.

Going back to the "it depends", analyze your special needs first and only then choose the solution that is best suited for your situation.

How about a point 3? make your data access layer into a library (.jar, .dll or whatever technology you are using) and make that available to the (1? 2? 3?) business web services that serve your clients?



Related Topics



Leave a reply



Submit