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
Related
I have an application with the following layers:
Web API - Provides an access point for external calls to enter the application.
Infrastructure - Provides repositories which allows access to the database.
Service layer - Responsible for different use cases (e.g. 'Add item to cart').
Domain - Contains domain objects with business logic.
You can see how they reference each other, in the drawing below.
I want to add a typed http client, to fetch certain information from an external API.
In what layer/project, should the typed client be created?
My reasoning so far:
The first thing that came to me, was the infrastructure project. But since the infrastructure points towards the service layer (which needs the data from the API), that means introducing an interface on top of the API. This also means that the response object, from the typed client, must be defined in the infrastructure layer (this is where it starts to get messy).
If that is the case, that means that one of the two following must be true:
A) The service layer gets to depend on the API response directly or
B) The typed client must map the response to an object defined in the service layer.
This means that I can either introduce a dependency, in which case I might as well put it all in the service layer. Or I make the typed client more than a typed client, which really feels like a code smell.
Some thoughts about your layering
Based on the your definitions:
Infrastructure - Provides repositories which allows access to the database.
Service layer - Responsible for different use cases (e.g. 'Add item to cart').
none of these have the responsibility to communicate with 1st and/or 3rd party services. It seems like your Infrastructure layer is a data access layer (in other traditional layered architecture naming), whereas the Service layer is the business logic layer.
Where to place
After this little detour let's focus on your question where to place the typed client(s). You can reason about that either of the layers can be good home of the typed clients. I would suggest to make a decision based on the followings:
If you have multiple independent typed clients and most of your business logic calls only one of them OR if the business logic utilizes multiple typed clients but only to aggregate their responses
Then place it where it feels right, It does not matter whether they are defined at the bottom layer or in the middle
If you have business processes / workflows which are typically utilizing multiple typed clients in a specific order OR in a pipeline fashion (one client's response is the input for the other client's request)
Then define them in the same layer as the process/workflow reside, because they are interconnected and most probably you want to avoid that situation that an other layer can use them in the wrong order or just partially
I hope my guidance could be applied for your particular case as well :)
I am learning about DDD and domain-centric architecture design applied to .NET solutions.
However, I am struggling a bit about how to implement it.
I have some examples that came up to my mind recently:
Filter/converting an excel file to another another kind of file json/xml and formatted following some business rules, be it a Console application or a WebAPI
Computing the energy deployed or the distance given some train stations
How to decide what goes into the Application "layer" and the Domain "layer"?
I read:
https://softwareengineering.stackexchange.com/questions/140999/application-layer-vs-domain-layer
https://github.com/thiagolunardi/MvcMusicStoreDDD
https://github.com/rafaelfgx/DotNetArchitecture
https://github.com/EduardoPires/EquinoxProject
https://github.com/ardalis/ddd-guestbook
https://github.com/dotnet-architecture/eShopOnWeb
https://github.com/HudsonLima/Product-API
https://github.com/thangchung/magazine-website
https://github.com/gigiogodoi/Blackbird
https://github.com/JasonGT/DDDBNE2017
https://github.com/felipeolimpos/base-core-ddd-mvc-ef-pg-ioc-proj
https://learn.microsoft.com/en-us/dotnet/standard/microservices-architecture/microservice-ddd-cqrs-patterns/ddd-oriented-microservice
The Domain layer contains all the code that enforces business rules.
It should be technology agnostic (like specific databases - sql, no sql - or protocols - HTTP, REST) and frameworks agnostic. This means that it looks the same whether the Aggregates are persisted in an SQL database or in a NoSQL database, it is called from a HTTP controller or from a console application.
It should be pure, with no side-effects. This implies it should not do any I/O (read or write from any files). It receives all the data it needs as method arguments. For me, passing an infrastructure or application layer as argument to an Aggregate method call is also bad, even it is hidden behind a domain interface, because it can do I/O.
It should not depend on any other Layers. This means no imports or use from other layers (or whatever programming language construct you use in your programming language).
The Application layer is a thin layer that loads an Aggregate from the Repository, it calls the corresponding method on the Aggregate and then it persist the Aggregate to the Repository. It basically glues the Domain with the Infrastructure.
In DDD architecture all the business logics and rules should be within the Domain layer. Application layer is responsible for referring the business logic by accessing Domain layer and do database updates through Infrastructure layer. So it is clear if you are goin to add a business rule or logic it should be Domain layer
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.
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).
I am wondering about the long term advantages (if any) of layering my web app by separating my business logic and data from my web forms. (ie a form, business logic, data not in the same file, but each in it's own class in another folder by itself or combined with other like classes). I like to make everything as modular as possible and to do so efficiently it seems that keeping all the code in one file - in the web form makes organization and reuse much easier. There are certain functions that are used across the site like managing connections that would be in their own classes and files. I am pretty new to c#, sorry if I am messing up the terminology.
Thanks
The separation of code into layers brings benefits beyond just C# language.
If your data access code is kept in a separate layer, it will be easy to adjust it to work with a different database. Database-specific code will be encapsulated in this layer while clients will work with database-agnostic interfaces. Therefore changes here will not affect the business layer implementation.
If your business logic is kept in one place, you will be able to offer its services to other applications, for example, to serve requests made via web services.
If your code is clean and well structured, the maintenance efforts will be kept lower. Whenever you need to change something, you'll know where to find the responsible code, what to change and how to assure the change will not affect the rest of the code.
As for ASP.NET, not following the separation of concerns has caused many projects to turn into a giant code blurb - presentation code performs business decisions, code-behind talks directly to the database whenever no suitable business method exists, database gets written to from many places, dataflow is following multiple paths which are difficult to trace, changes in one path not introduced to all of them will break integrity and cause data corruption => Result? Almost unmaintainable code black box where any change requires more and more effort until it stalls - project is "finished". Technical bankruptcy.
We usually layer our application as follows (each of the layer is in a separate project of the solution and consequently in a separate Dll:
What I would always go for (first) is to have a layered application
Presentation Layer (JUST UI and databinding logic)
Interface Layer to
the Business Layer (defining the
contracts for accessing the BL)
Business Layer implementation (the
actual logic, data validation etc...)
Interface Layer to the Data Access
Layer (defining the contracts for
accessing the DAL)
Data Access Layer
implementation
You can then use some factory for retrieving the corresponding objects. I would take a look at some library, possibly using dependency injection like Spring.Net or Microsoft Unity from the MS patterns and practices.
The advantages are the following:
separation of logic where it belongs to
no business logic in the UI (developers have to pay attention to this)
all of your applications look the same and consequently developers knowing this architecture will immediately know where to search for the corresponding logic
exchangeable DAL. The interfaces define the contracts for accessing the corresponding layer.
Unit testing becomes easier, just focusing on the BL logic and DAL
Your application could have many entry points (web interface, Winforms client, webservice). All of them can reference the same business logic (and DAL).
...
Just could not live without that..