I am a little confused about the definition of the business logic in programming because I used to develop without paying an attention to any of these terminologies but now I want to be a good developer.
While I was reading in Wiki about the definition of the business logic I have read the following definition:
In computer software, business logic or domain logic is the part of the program that encodes the real-world business rules that determine how data can be created, displayed, stored, and changed.
and in another website I have read the following definition with example:
Business logic is that portion of an enterprise system which determines how data is:
Transformed and/or calculated. For example, business logic determines how a tax total is calculated from invoice line items.
Routed to people or software systems, aka workflow.
So I am wondering about which part of the MVC represents the business logic, is it the controller or the model or another part could be in the MVC?
I know that the controller is responsible for sending commands to the model but is it responsible for applying the rules of the business?
For example let's take the above example of the tax:
Suppose that we got the invoice data from a form in a view, the data will be directed to the controller but where the tax will be calculated, will we calculate it in the controller or will we ask for the help of an external class to compute it or will we compute it in the model before updating the database?
Could Example would be appreciated.
You can put the tax calculation logic in the Controller, but you're better off putting it in the Model as it is more loosely coupled. It is reasonable to want to calculate tax on lots of pages, so don't put it in lots of controllers, put it in a model that can be re-used.
If you hear someone talking about "Fat" Controllers vs "Thin" Controllers, that is what they're talking about. Most devs will advocate having very little code in their controllers (making them "thin") and really just acting as a relay/orchestrator off to the Model.
I do think the term Model is a bit confusing though because in Service Oriented Architecture (and functional languages for that matter), they stress trying to have "dumb" objects that don't have any functionality and they frequently refer those dumb objects as "Models". But when it comes to MVC, the "Model" really refers to the Business Model, which incorporates dumb objects that hold values AND the services that work on top of them.
In Enterprise software development, must of time we use N-tier applications. They are 3 or more tiers.
1- Data tier:
2- Application tier (business logic, logic tier, or middle tier)
3- Presentation tier: it is a layer which users can access directly such as a web page, including simple control and user input validation or an operating systems GUI. , .
MVC is one of the seminal insights in the early development of graphical user interfaces, and one of the first approaches to describe and implement software constructs in terms of their responsibilities
This said that MVC is use as a presentation layer. They are others like MVP, MVVM..
Sometime time in small application, an MVC structure is use to separate layer where the model is use as data layer, the controller as Logic layer.
Related
I am fairly new to Arhitecture Designs in OOP ( I'm coming from programming robotics, so it's a bit of a struggle ). The team that I am taking part of is creating a rather large application and the Leading Project Manager presented us with the requirements and in that requirements we must use Layers in creating the modules. The technologies we are using are C# WinForms and Oracle for the data-store.
My module consists of User Administration and I have tried to separate the logic from the implementation, so I have the following arhitecture:
Business Layer
Data Layer
Presentation Layer
I am using the Repository Pattern and IoC with EF and everything looks and works fine but now my boss has told me that I need to seperate the Presentation Layer from the Data Layer completely. The problem consists that from the Presentation Layer I use IoC and if I want to create a User object for example I do the following:
_userRepo.InsertNewUser(new User { props here } ); .
So this is incorrect because I access the DAL directly. My boss has told me that I need another layer that isolates these kind of calls and implement Business Rules ( ?! )
I have searched and researched the internet and I found nothing of help ( mainly because everything is filtered here at work ).
I think my boss wants something of a Domain Layer / Service Layer but I have no ideea how to implement it in the current design. I can post the project without any problem, any sensitive data will be removed from the code.
Any help would be appreciated.
I'm posting this as an answer, even though it might be opinion-based, and even though I cannot read your boss's mind :-)
Fundamentally, I think what your boss wants is to reduce dependencies between all layers. The architectural pattern you choose to do this, depends on the application at hand. What you described looks like a three-tier architecture. Let us briefly recall how a three-tier architecture looks like, and how things are supposed to work:
The presentation tier displays information and serves as a boundary to the user.
The application tier (or business logic) controls the functionality of the application. In particular it processes data and distributes it to the other tiers.
The data tier, containing the data access layer (DAL), stores or retrieves data. It should keep your application independent from the storage solution at hand. It will usually work with data access objects (DAOs).
There are different schools of thought when it comes to which tier should know which other tiers. But from what I read, I think you are supposed to promote the business logic as kind of mediator. This means, the business logic knows the presentation tier and the data tier, but the other tiers do not know each other. I try to clarify this by going through two sample scenarios:
A. Display an existing user
Business logic asks data tier for a specific User DAO, e.g. the one corresponding to id==123.
Data tier returns the User object.
Business logic reads the values stored in the User object and sets the values in the presentation tier accordingly, e.g. the firstName, lastName etc. It does not forward the User itself, only the contained values.
B. Create a new user
Presentation tier collects all values necessary to create the new user.
When "submitting", these values arrive in the business logic (e.g. IoC).
The business logic tells the data tier to create a new User object with the values it got from the presentation tier.
The data tier creates and stores the object.
What creates dependencies between the different tiers are the DAOs. I.e. if your presentation tier was to instantiate a User object, it would need to import a class belonging to the DAL (which is not what your boss wants).
So what you can do instead is to leave all the communication between presentation tier and data tier to the business logic.
As an alternative in scenario B, you can also make the business logic create the User, so that your DAL methods get simpler.
As I said in the beginning, there is no one way of doing it. If you need more specific information or have further questions, don't hesitate to ask.
Thank you for the all the answers and guidelines so far.
I think what my boss wants ( I didn't get reach of him because he is in DE and I am in RO ) is to fully separate the concerns between layers, something like the Model-View-Presentation Pattern, so that the Presentation Layer ( UI ) will not directly access the Data Layer. It can access it but through an intermediary layer.
I added a Domain/Service Layer to the application and now the Presentation Layer calls the Service Layer and the Service Layer calls the Business Layer and creates the user / group objects.
The following thing is, he said something about Business Rules that this Domain Layer should include. What are these Business Rules, an example would be appreciated?
The only think I came up for Business Rules were some Validation Rules, suchs as: Before you call: return userRepository.GetUserName( User user ) check the User object passed as a parameter that is not null, or similar checks.
So now the "mechanics" are:
In the Presentation Layer I inject into the constructor the IService object and then I use the IService object to call a method for example "GetAllUsers()".
The IService per-se is in fact a "copy" of the User Object's Repository class so when the IService object calls "GetAllUsers()", there is a exact named method in the IService classes that will do: "return _userRepository.GetAllUsers()" - in this way the Presentation Layer calls object specific methods through an Intermediary Layer and this Intermediary Layer will have direct access to certain methods of the DL.
I hope I made my self as clearly as possible. I will provide screenshots if necessary.
As I stated before, I'm just beggining to have experience with Arhitecture Design, since in the robotic fields there is no such thing, so please do not throw so many rocks :D
I want to know the right concept about it. If I have a MVC application with Repository Pattern, where the BL should be?
Should it be inside the Model? Model should have all the business
logic before call the unitofwork to insert or not the data into
database?
Should it be in the controller? Before call the model?
Should I have a service layer to do the business logic and decide if
I should call the Model to call the UnitOfWork to save the data?
A good explanation will help a lot too.
The short answer - it depends. If it's a fairly complex or sizable application, I like to create a service layer project with the repositories as dependencies. If it's a small application, I'll put the logic in the controller. In my opinion, if it takes more time and effort to create the service layer than it would be to create the application (i.e. one or two controllers), then it doesn't make sense to me to go that route. You also need to consider the likelihood that the application will grow. What might start small could grow into something much bigger and in that case, again, it might be more beneficial to create the separate service layer.
The third one... and then some.
Your application structure could look like this (each in different projects):
Data storage layer (e.g. SQL database)
ORM (e.g. NHibernate or Entity Framework)
Domain (including abstract repositories and entities)
Service layer (and optionally business)
MVC application (which has it's own models relating to the entities)
but there are many ways to go about this depending on the complexity and size of your application.
There is no "correct" answer to this question, it is primarily opinion-based. You can read about my opinion in the following project wiki:
https://github.com/danludwig/tripod/wiki/Why-Tripod%3F
https://github.com/danludwig/tripod/wiki/Dependency-and-Control-Inversion
https://github.com/danludwig/tripod/wiki/Tripod-101
https://github.com/danludwig/tripod/wiki/Testing,-Testing,-1-2-3
https://github.com/danludwig/tripod/wiki/Command-Query-Responsibility-Segregation-(CQRS)
Another piece of advice I would like to offer is never put any business logic in viewmodels or entities. These classes should not have methods, only properties to contain data. Separate your data from behavior. Use models for data, and other types for behavior (methods).
In my n-tier .Net Application I got next layers:
Data Access Layer (EF)
Business Layer (Validation & Business Logic)
Presentation Layers (1 MVC Controller and many API Controllers)
I found, that my Business Services only validate business objects, call CRUD DAO methods and return results to Api Controllers.
So, I doubt: may be Web Api Controllers should be used as Business Services?
Interesting, just answered a similar question...
So I woudn't do it I were you.
Here's just a few disadvatages of the approach from the top of my head:
Performance - a redundant HTTP roundtrip in Web MVC project.
Separation of concerns - most of the time the functionality provided
by API differs greatly form UI for the same project/application. You
might want to limit the API to a few methods with a strict contract.
In case you want Web API to be a layer between Web MVC and your DAL
you will have to expose all functionality you need for UI as well.
Also you might want to have different authorization and
authentication mechanisms. Very often API exceptions handling is
also different as well as input validation.
Maintanance - everytime you need to make a change required for UI
only you have to make sure it doesn't brake your API clients. Also
API versioning is a very important topic and mixing it with most UI
changes makes this process even more difficult.
Probably for now you application is not that complex but from the design perspective your solution is much more flexible now than it will be if you decide to put Web API between your UI and DAL layers.
N-Tier applications and multi-layer are not popular among the new wave of developers. Keep in mind, that just because something is not popular, among a group, does not mean that it does not have merit.
Pros of MVC:
Separation of Concerns
Unit Testing
Does a multi-layer MVC application using a Web.API have merit:
I know this will be met with some discontent and disagreement. However, my concern is that single purpose application developers are not giving consideration to enterprise development. Enterprise development, load balancing, manageable code maintenance, and true Separation of Concerns are only possible with multi-layer applications that can easily lend themselves to N-tier.
Many developers are operating in environments that demand that they design and implement data structures in SQL, create and maintain models and CRUD functionality, develop controllers and design good looking and friendly views. The MVC model utilizing Entity Framework makes this a manageable task for these small to moderate platform developers.
In the Enterprise, separating the Business and Data Access layers from the User Interface makes real good sense. Right now MVC is a popular and very functional platform for efficient and usable User Interface development. What will be the UI platform in ten years? Separating the UI from the other layers gives more life to the work spent developing the business logic. Not to mention, that it allows for accessing data on multiple platforms today.
Multi-layer MVC using Web.API has these advantages:
True Separation of Concerns
Supports Unit Testing
Makes the Business logic and Data Access logic more scalable and reusable than MVC alone.
Supports data processes without page refresh. (REST)
CONS:
- Does not easily support use of Entity Framework. (Which is not ready for the enterprise yet anyway)
You could have your code as part as your model, and that would even be considered as good separation of concerns since MVC is build for that.
But what my preferred thing to do is keep logic in a Business Layer of it's own. The reason for that is, I think, better separation of concerns. I like using IoC, so there might be different configurations that I route thought different running solutions. Or, I might have another UI/API/Project that uses the same logic layer.
As for the overhead, it has a little overhead, but I think worth the trouble comparing to the actual overhead in code it creates.
I agree with others here, looking into using strongly typed views, the controllers would only create an instance of the viewmodel and send it on to the view. The view model then is the intermediary to the data services layer. I personally create all my entities using EF in a different project just to separate function. The view model can either call EF directly or you can add another layer of pre-canned EF queries which the Viewmodel uses just to populate the view collections. This would look like this:
[View]-[Controller]-[Viewmodel]-[Optional repository and interface to EF]---[EF]
In the interface to EF you would catch all DB errors when trying to get information and post back to the view according to your design.
The beauty of strongly typed views is that they post back and forth from the View and can contain methods which you can call at will. Because they are a pseudo model for the view, they can also have properties specific to the view which may be used at the business layer. I pass view models around quite a bit were warranted. (After all they are just a pointer)...
You can implement business logic/validation/calucations in the actual model/entity classes rather than ApiControllers, otherwise you will end up with so much code in your controller which is not really a good thing.
Also you can use DataAnnotations Attributes to perform your validation which sits outside of your controller. for.e.g. http://msdn.microsoft.com/en-us/library/ee256141(v=vs.100).aspx
I write layered application with complex domain under the hood. On the server side, there is a complex class document with, for example, Price attribute. Price is calculated by strategy-pattern classes like ManualEnteredPrice, DistributedPrice, DiscountedPrice and others.
In unit-tests, everything is OK, price is calculated, documents load and store in the database and so on.
Now I would write rich client (winforms) and web portal (javascript) for manipulating documents. I use DataTransferObjects for projects and pass data through WCF from the service layer for the client. In client, I build some kind of viewmodels (bindings in forms and knockout in web) from data transfer objects. And I have to write again the price calculation logic for presentation purpuses. Some radiobuttons for strategy choosing, some controls for data entering and similar Price-strategy-classes for calculating price to display it. And then, when I pass DTO back to the server, I don't use calculated price, because I cannot trust to its value. I must fill some fields in the document and recalculate Price again.
So, I have two different class hierarchies, doing the same things - price calculation.
Is this a correct? Maybe there is another approach? This is very often the situation, when same logic is in the domain and on the client. How do you project this architecture?
I cannot reuse domain in client, because client's classes have some differing fields or additional fields or behavior.
I cannot pass only price calculation to the service layer, because it depends on document state, status, many other document contents. Should I pass whole document for price recalculation to service and then receive and set price in viewmodel?
How do you implement the presentation logic, that is same as domain logic?
I think you got the right approach. As you probably understand, making an architecture decision has some trade-offs. Following this specific approach, you have many benefits (data integrity, separation of concerns, minimum code dependencies etc). On the other hand, you repeat a lot of logic and you think that perhaps this is not very easy maintainable.
I would choose to follow your approach because I suppose that the only dependency between the layers is logical. This logical dependency cannot be thrown away. On the other hand, following your architecture has minimized the code dependencies, which is the primary concern of any software development architecture.
Hope I helped!
Almost all examples of DDD within the Alt .NET community are applied to web development; what I would like to see are some examples of DDD applied in scenarios where the client handles most of the business logic and the server is simply a web service for CRUD using DTOs [1].
I'm currently working on a product that has an anemic domain model. Coming from years of web development, this sort of thing would typically make me cringe; however, I'm not sure how I would go about structuring this code around the DDD principles. In a web app, I have direct access to the database at the point where I handle business logic (implemented within my domain model, invoked by the controllers), which means that I can easily have a rich domain model and use an ORM for CRUD. But, in my current project, DTOs are the only sane way to transfer data. 80% of the business logic is implemented in View Models (this is a WPF app), the other 20% percent is located in stored procedures - and 100% of the DAL is hand written ADO .NET. There's really isn't a lot of business logic implemented within the web services, so there aren't any "entities" to be found in the solution - they're all DTOs.
How could I introduce DDD into this sort of client/server architecture? What sort of experiences have you had, and what approach did you take? What patterns would you suggest? I haven't had much time to grok CQRS, but something tells me it could related - is that so?
Foot notes
Perhaps this is the wrong question to be asking. In this type of client/server WPF scenario, would it make sense to follow the web app paradigm, where 99% of the client's focus is on display logic?
This is funny, because I often wonder how DDD can be applied to web development.
I don't mean this to be a comprehensive answer to your question, but you might find something useful among the responses to an old question of mine: Should I map a DTO to/from a domain entity on both client and server sides?
As a very general answer to your question, I'd say that you could move logic out of the view models and into a client-side domain model (since it sounds like the server side is working just fine without any concept of a domain model). You'd use the DTOs coming out of the web service to "hydrate" these entities.
If you're creating a smart client, then you want to leverage the ability to maintain state and perform logic directly in the client (so, "no" to the footnote).