Business Layer in 3 tier Architecture - n-tier-architecture

I went for an interview, and was asked to show up my Business layer architecture. I have some idea about 3 tier architecture but really no idea, to what to write in front of interviewer.
So suppose my project deals with Employees of an organization, then what would i have written there. Will it be any kind of diagrams i should have made or some coding part. I worked in C# framework 3.5. I really don't understand what else to mention in this question, so please let me know if something is required.Thanks.
Edit
I worked in winforms.
I know what Business layer is, but was not sure what to tell the interviewer as business layer has codes and obviously my project was a bit big, so there were huge numbers of codes. So what i should have written there??

a 3 tier Architecture is composed by 3 Main Layers
PL Presentation Layer
BLL Business Logic Layer
DAL Data Access Layer
each top layer only asks the below layer and never sees anything on top of it.
When They ask you about How will you build your BLL, you can write something like:
namespace Company.BLL
{
// let's create an interface so it's easy to create other BLL's if needed
public interface ICompanyBLL
{
public int Save(Order order, UserPermissions user);
}
public class Orders : ICompanyBLL
{
// Dependency Injection so you can use any kind of BLL
// based in a workflow for example
private Company.DAL db;
public Orders(Company.DAL dalObject)
{
this.db = dalObject;
}
// As this is a Business Layer, here is where you check for user rights
// to perform actions before you access the DAL
public int Save(Order order, UserPermissions user)
{
if(user.HasPermissionSaveOrders)
return db.Orders.Save(order);
else
return -1;
}
}
}
As a live example of a project I'm creating:
PL's are all public exposed services, my DAL handles all access to the Database, I have a Service Layer that handles 2 versions of the service, an old ASMX and the new WCF service, they are exposes through an Interface so it's easy for me to choose on-the-fly what service the user will be using
public class MainController : Controller
{
public IServiceRepository service;
protected override void Initialize(System.Web.Routing.RequestContext requestContext)
{
...
if (thisUser.currentConnection.ws_version == 6)
// Use old ASMX Web Service
service = new WebServiceRepository6(url, ws_usr, ws_pwd);
else if (thisUser.currentConnection.ws_version == 7)
// Use the brand new WCF Service
service = new WebServiceRepository7(url, ws_usr, ws_pwd);
...
}
}
In the code above, I simply use Dependency Injection to separate the knowladge of the other layer, as at this layer (the Presentation Layer as this is a Controller in a MVC project) it should never care about how to call the Service and that the user uses ServiceA instead of ServiceB... What it needs to know is that calling a IService.ListAllProjects() will give the correct results.
You start dividing proposes and if a problem appears in the service connection, you know that's nothing to do with the Presentation Layer, it's the service Layer (in my case) and it's easy fixed and can be easily deployed a new service.dll instead publishing the entire website again...
I also have a helper that holds all Business Objects that I use across all projects.
I hope it helps.

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. Business logic can be further subdivided into the following two categories:
Business Workflow. After the UI components collect the required data from the user and pass it to the business layer, the application can use this data to perform a business process. Many business processes involve multiple steps that must be performed in the correct order, and may interact with each other through an orchestration. Business workflow define and coordinate long running, multi step business processes, and can be implemented using business process management tools. They work with business process components that instantiate and perform operations on workflow components.
Business Entity Business Entity entities, or—more generally—business objects, encapsulate the business logic and data necessary to represent real world elements, such as Customers or Orders, within your application. They store data values and expose them through properties; contain and manage business data used by the application; and provide stateful programmatic access to the business data and related functionality. Business entities also validate the data contained within the entity and encapsulate business logic to ensure consistency and to implement business rules and behavior.

Business layer layer that responsible for all business logic. For example
you have Organizarion so organization and collection of employee.
In employee object need to implement some restriction or some rules.
This rules will be implemented in this layer.

3 Tier is as follows,
Your presentation in one layer.
Your application logic in other layer -- called business layer.
Your Data Access classes in third layer. -- called Data Layer.
Webforms will be presentation layer
So for employee class doing anything in ASP.Net code behind file can be considered business layer per my understanding as you are applying business rules using if/else and so forth.
Data Access classes in App_Code folder would be Data Layer.
In case of desktop apps form designs would be presentation layer, form code will be business layer and anything related to accessing database would be data layer.

A 3-tier architecture is a type of software architecture which is composed of three “tiers” or “layers” of logical computing. They are often used in applications as a specific type of client-server system. 3-tier architectures provide many benefits for production and development environments by modularizing the user interface, business logic, and data storage layers.
Business Logic Layer: Business logic is the programming that manages communication between an end user interface and a database. The main components of business logic are business rules and workflows.
A Business Logic Layer (BLL) that serves as an intermediary for data exchange between the presentation layer and the DAL. In a real-world application, the BLL should be implemented as a separate Class Library project in App_Code folder in order to simplify the project structure. below illustrates the architectural relationships among the presentation layer, BLL, and DAL.
The BLL Separates the Presentation Layer from the Data Access Layer and Imposes Business Rules

Related

In multi-layered architecture, can I skip the business layer for crud operations?

We have 3 layered application where every call from the service layer goes to the business layer and is persisted by the data layer. Components of each layer can only call the layer below;
However because we have hundreds of entities and we have lots of services related to crud operations so many controversies raised on our team.
Some believe for the sake of maintenance and ease of development it's better to call data access from crud services which just doing crud operation and bypassing business layer.
On the contrary some saying we have to create wrapper for data access of each entity in business layer and call these wrapper from services and never allow services to call data access layer.
In your idea which way we should take? Is it ok for crud services to call data accesses and bypassing business layer?
If there is no business logic to perform, there is no reason to enforce a business layer. The 3-tier architecture is not an arcane protocol, just a best practice that was formed assuming business processing.
In a current application we are often accessing DAOs directly from JSF controllers when there is no business process involved. The idea was given by a java champion who stressed the idea that simplicity is paramount.
If you are worried about future modifications that may require adding business logic. I think of the issue this way: The additional business logic would be added to the business layer anyway, including data access, so there is no difference here.
CRUD code is mostly very simple. So the change in the service would amount to reroute a single call or a couple of calls fron the DAO to an EJB - a simple refactoring. The CRUD code itself would still remain, but will be pushed into the EJB - another simple refactoring.
This is not perfect, but IMO better then the alternative: having an empty indirection layer. This adds complexity that serves no purpose. The business object would do nothing but forward the calls to the DAO.
There are two code smells that I think apply in this case: contrived complexity and feature envy.
I am not saying that DA in the business layer is somehow a code smell. What I mean is that having a business object that does nothing else but proxy the DAO is a smell. It's the same with complexity - an added data structure / architectural layer that serves no own purpose - there seems to be a DAL in your application already.
Another aspect for your consideration would be - how surprising is it for a developer to see a service that uses a DAO directly? Having 5 services where 2 of them access DAO directly is different from having 100 services where only one service accesses the DAOs directly.
In the first case the code simplicity would outweigh the added conceptual complexity (2 concepts for a single thing), in the second case, I would rather stick with the business layer - the surprise (also called the WTF-effect ;) of doing it differently just once would be too big.
In my opinion, having call CRUD services bypassing the business layer will start converting the current service layer into a business layer as you increase the functionality. So your service layer will act as the business layer too, if you are fine with it.
In most cases, you deal with an entity and probably that could involve many data layer crud calls, on one update for example. A business layer is recommended for this purpose. And business layer is the place to execute any business rules, caching or call other business services if required. This will keep the upper layer simple and pass through.
I will not bypass the business layer. Even though it might look like you are only proxying the call for the DAL into the BL, and even though this may be a case of very simple CRUD operation, the BL can encapsulate the validation logic required for the operation. Validation logic can be performed on the BL and proxying to DAL will only be performed if the validation conditions are met.
If you only have CRUD operations, you can use Data Services to publish your data sets as web services. A good example to this is WSO2 Data Services http://wso2.com/products/data-services-server/

Purpose of the service layer

Am I correct in thinking that the purpose of a service layer includes the following?
thinning out of domain models (i.e. movement of certain functions like in caching, instantiation)
reduction in dependencies from domain models
API minimisation
Traditionally (when not using Domain Driven Design) the service layer, or 'business layer' as it is also called, is where you code all the business logic for your application. So, for example in an application that deals with giving out bank loans, the service layer is where the code goes that decides whether or not a certain loan should be given.
Obviously, the service layer would require some information about the applicant of the loan to be able to make a decision on her credibility. To retrieve this information, the business layer calls the 'data' or 'repository' layer, which deals with extracting and storing information into the database.
The service layer does not deal with matters like persistence or other infrastructural concerns.
If your design is domain-driven, anthares' answer is true.
In terms of domain-driven design for example the domain service layer is used for operations that cannot be defined in the context of you Domain objects. For example if you have an object CreditCard, a suitable operation in your service layer would be Issue a new Credit Card.
In bigger application is used the pattern Anemic Domain Models, where the domain objects are used only as data containers and the whole business logic is in your domain service layer (this is sometimes refered as anti-pattern, but may be very useful in big solution, with adding another abstraction layer).
In difference solution architectures and patterns, service layer may have difference purpose, though.
Service Layer as the name suggests provides services that are not directly responsibility of any other domain object.
Service Layer also helps in decoupling of responsibilities. Service Layer forms the middle part between Database/persistence layer and the Client/UI/Web layer.
Properly designing the Service Layer allows it to be used from any client be it a Web Client or a Web Service (SOA) or Mobile device.

Can you build a RESTful Business Logic Layer?

I've built a RESTful service for the Data Access Layer (DAL) of my architecture:
POST http://example.com/data/User
GET|PUT|DELETE http://example.com/data/User/{UserId}
However, for the Business Logic Layer (BLL), a second non-RESTful service is used:
POST http://example.com/accountapi/register
POST http://example.com/accountapi/login
This BLL service, instead of making calls to the DAL service, it talks directly to the database.
How would you improve this architecture?
Should the BLL service call the DAL service ?
Should I drop the DAL service and only expose the BLL service ?
Should I, somehow, inject business logic on my RESTful DAL service ? If yes, how ?
To answer the main question. No, not really. To answer the secondary questions. None of the above.
REST based architectures do not fit nicely into the standard 3 tier model. The simplistic view of the three tiered model looks like this:
Presentation Layer <-> Business
Logic Layer <-> Data Layer
Consider for a moment breaking the presentation layer into two parts,
Rendering Layer <-> User Interface
Content <-> BLL <-> DAL
If you think about a regular Web application, the browser takes HTML, CSS and Javascript content and renders them visually in a browser. It is the User Interface Content layer that the REST constraints apply to. This is most obvious if you think about the hypermedia constraint. REST interfaces are mean to be navigated just like user interfaces are. REST interfaces return representations of resources.
REST interfaces should return user interface content that is independent of how the user interface will be displayed.
REST Client <-> REST Interface <-> BLL <-> DAL
In my opinion REST clients come in two forms, either very thin media type rendering engines (e.g. Web browsers) or screen scrapers (spiders, mashups). I use the term "screen scraper" loosely because if you choose your media-types wisely it should be trivial for the client to scrape the data out of your user interface content.
Any attempt to expose Business Logic Layers as REST interfaces usually has a few effects. Developers end up asking how to do transactions in REST. They end up creating huge amounts of coupling between the client and the BLL interface because of the need to expose semantically rich representations. They forget all about the hypermedia constraint, because much of that linking information is not available in the business logic layer. And they start to complain about the performance overhead of HTTP and text based content types.
(1) Avoid having your (non-REST) web service business logic layer make further (RESTful) HTTP requests onto the data access layer. Doing so of course would be less efficient than making direct method calls. But much more importantly, it would require you to deploy the BLL web services and the DAL web services onto separate web server instances (or separate clusters). Otherwise you can have a case where all your HTTP worker threads are busy trying to serve up BLL responses, and each is blocked waiting fruitlessly for a free HTTP worker thread to serve it a DAL response. This can lead to stalls (if you do timeout/retry processing) or outright deadlocks (if you don't).
(2 and 3) If your web service clients need both business logic and data access, provide those as a unified set of services. Internally they both depend on the same data access layer method calls: it's just that the data oriented web service implementations make just one data access layer call while the business logic oriented web service implementations may make many DAL calls. You do most definitely want to structure the BLL and DAL layers separately beneath the web service layer though.
I like to think of the web services as just the part of the presentation layer oriented towards "users" who happen to be other programs.
If this is the same application, then you should probably have the BLL layer call the DAL layer directly in code instead of using a service call again. That would keep it more performant while keeping the fundamental purposes of the code separate (high cohesion).
Probably so. Your services should generally be course-grained components that perform a business function. Saving a user in the database isn't a business function, it's a specific implementation. The Register function abstracts that notion into a business function. The BLL layer can then enforce things like password strength, password encryption, uniqueness of usernames, etc. that aren't directly related to data access.
Probably not. See #2.

In the webservices model are there still basically 3 tiers as the client-server model had?

The basic client-server model (even when implemented using questionable interfaces) had a presentation layer, a business layer, and a data layer. Are the directory and discovery methods using webservices models considered a entirely new layer? I would argue that the discovery layer is actually just expanding the role of the data layer to include information on where a service can be found. I am struggling to understand the interplay between webservices and the MVC framework and I am trying to understand the bigger picture as to where the directory and discovery components fit into that framework.
I would say that there is an additional layer -- the service layer -- that sits between your business layer and the presentation layer or your business layer and the data layer depending on whether you're doing a thin- or thick-"client" implementation. This layer would encapsulate service discovery and delivery, including marshaling/unmarshaling data for transfer. See Fowler's Principles of Enterprise Application Architecture Service Layer description. In his concept the service layer sits between the business layer (domain model) and the presentation layer (UI). This concept would apply to a thin-client or web-based client implementation.
I would say there are not basically 3 tiers in the web services model.
Web services is essentially SOA (Service Oriented Architecture), which can imply a multi-tier (n-tier) model. It refers to distributed computing and could be scaled up to a massive system with hundreds of "tiers".
I would agree with you that conceptually, getting your data from a service as compared to a database, could be similar to getting data from other data sourced like databases, etc., and that this could be conceived of as an additional function of the data access layer.
Of course it also depends on semantics. Often "tiers" refers to discreet parts of the overall system (i.e. front-end, middle-tier, back-end data sources, other tiers such as integration with web services, etc.); while "layers" often refers to the vertical layers in the code such as presentation, controller, business logic, data access, etc.

UI, Business Logic Layer, Data Layer and where to put web services

We are developing a web application. We want to possibly reuse the work we do here for a different application that will use the same database, and use the same business rules for reading and writing to said database.
Which design would be more correct
Having the UI call web services, which would use business objects containing the business logic, which would talk to the data access layer.
Have the UI use business objects containing the business logic, which would call web services, which would then talk to the data access layer.
Have the UI user business objects containing the business logic, which would talk to the data access layer.
Don't mix logical design with physical design. Logical design operates over layers and physical design - tiers. Web Service is not a layer. It is simply a tier.
In logical design there is standard approach: UI layer-> BL layer -> DAL
In physical design all layers can reside within one client-side application connecting local database, or can be distributed over the remote tiers. But for distributed applications usually is added one more layer: Application layer, which hides from BL layer communication over the wire.
I would say the 3rd one. I tend to think of web services as another presentation layer.
Think of it this way: you have a web UI, which calls your business layer code to do things like create a new user (User.Add), find all products that match a given description (Products.FindByDescription), etc.
You can now re-use that same business layer code to build a set of public-facing web services for 3rd parties to make use of. There can be a method which adds a user - that calls your internal User.Add() method, another one to find products, etc..
What you get is a parallel set of presentations/interfaces to the same underlying data and business logic.
Behind the scenes (totally out of the scope of web services or UI layers), the business layer calls a data access layer that takes care of physically querying the database. If you were to change to a different DBMS, you should ideally (and in theory) be able to rebuild the data layer for the new database and have everything simply work.
Your business layer contains the rules like a username has to be 4 to 15 characters long; users are only allowed to search for and load products that are at a store they have access to; etc.
If you decide to change a business rule - like a user is allowed to search for products in any store in their state - then you change it in once place, and don't have to touch the web service or UI to make it work.
From your description, you haven't provided a reason why you would need the use of a web service layer. Assuming your database is reachable by your UI system, i.e. within the same network behind your firewall, a basic business-object layer that your website UI code (server-side, I'm assuming) will employ meets your requirements.
Bring in a web service tier when the distance between your UI system and your data layer starts to cross boundaries that a Data access layer or Business logic layer would begin to encounter difficulties.
In terms of the design being "correct" or not, it's not really possible to give a 100% answer to the correctness of a design without the full context. What are the requirements (functional and non-functional)? What design goals do you want to fulfill? How important is each goal?
The only goal your question mentions is that you want to reuse the business logic with another application. When I want to reuse the business logic of an application in a standard way I choose web services. So based solely on your one requirement I would say that option 1 ( UI->Web Service->Business Layer->Data Layer ) is a good choice.
Logically, web-services belong in the UI layer. Think of "User" being not only a human but another system and it becomes clear. Maintaining strict separation of concerns between these logical layers will allow you to easily implement and maintain your application.
Check Out: http://www.icemanind.com/layergen.aspx
The way it should go is, you have your UI layer on top, your data layer on the bottom and your business layer in between the two. Each layer can only communicate with the layer below it. So the UI talks to the business layer only...the business layer talks to the data layer only. Your UI should never talk with the data layer and your data layer should never interact with your UI.
Unless you have a reason to use a web service, then I wouldn't.
Do you hear anything about Service layer ? I think you can use a service layer for your transactions and operations and using a facade layer helps you to isolate and manage accessing from UI to data access layer directly or indirectly after visiting the Business layer . it depends on your requirements.