Good morning, guys, I need some advice.
I’m creating the output templates for my APIs but I’m very confused about the name of the classes.
For example, I have an entity called User.
In the output model I must return a list of User but it must not center with the entity but with another model created by me for output.
Well, I don’t know what to name this last class I told you about.
I cannot call it User because it conflicts with the real entity.
Tips?
There should be at least 3 layers of objects in your code, ViewModel, Dto and Entities.
Each layer should only be able to see the layer directly below it.
So, your service layer, can read Entities from your data layer, but if it exposes any objects, they should be in a Dto.
Then, your presentation layer (UI/API etc), will read from the service layer (DTO), and expose it's objects as ViewModels.
In many cases, this means that all 3 objects (Entity, Dto & ViewModel) have the same repeated properties, but this is to be expected, especially in smaller or newer projects.
This should then solve your naming problems.
Data layer: XXXEntity
Service layer: XXXDto
Presentation layer: XXXViewModel
This explanation is very simplified, and you could solve this problem in many different ways (you could use namespaces instead of class suffixes for example).
The guidance I try to work by is that naming should reflect intent - whereas a User just represents the concept of a 'user' in your domain, an API model is intended to be an API payload containing user information. In your position, I would consider something like UserApiModel or UserPayload.
*As an added note, for my money, the thing that matters the most here is consistency - no matter what you pick, what makes sense to you now may not be the most intuitive thing to you (or anyone else) maintaining the code later. As long as you apply your naming convention consistently across all your API models, don't stress too much about finding the 'right' one - just pick the first one that seems good enough, and keep rolling.
Related
Recently, I'm learning MVVM design pattern!
In my way, I write the database function in the model, and let the viewmodel to call the database function in the model, then the viewmodel get database data and set to the viewmodel notfiypropertychanged. This is my way that I currently use!
There are some question confused me about model,
I read many article that told me model just a contain data and not more business logic, and here is my question, if model just a data container and I need to let my viewmodel to call the database then get data and set to the model, I think this way is very strange and the viewmodel code is make heavy in it. Is anybody have another method to do it? Thank you!
The Model:
"model just a contain data and not more business logic"
A model is a class which describe an entity within your domain logic. What is a domain? Starbuck's domain is coffee beverages and employees (among others), Ford's domain is cars, assembly lines, and employees. NYTimes's domain is articles, issues, supply routes, subscribers, etc, etc.
A model contains data AND logic. You can have multiple models to describe your domain.
You can place your data calls in your model, but it's more common to have helper classes, data access layers (DAL), keeping all your database calls in one place, and not spread them around.
The ViewModel:
The viewmodel sits between your domain model and your view. It's a class which expose properties of the model and represents the state of the view. The viewmodel may only exposes a subset of all the properties in the model that the UI needs to display, but it could also add properties of its own, for example; is the user in edit mode? have changes been made that needs saving? etc. The selling point with MVVM is that the UI binds to these properties on the viewmodel which is a mechanism to keep the UI up to date with changes, and this extra layer of abstraction conveniently decouples the view to any logic in your model making it more robust for code changes in either direction and testable. There's more to say on this topic, but I'll leave it to you to read on up it.
There are many good resources and info on the MVVM pattern; from blogs Model-View-ViewModel (MVVM) Explained, to Microsoft The MVVM Pattern and here on SO.
If you prefer videos, Pluralsight have good video tutorials on the MVVM pattern
Practical MVVM and WPF MVVM In Depths. They have a free 30-day trial.
"just a data container"
Such classes that only hold data to be passed around are often called Data Transfer Objects (DTO). It's common to keep them small and return collections of these from fetch database data method calls.
I've done some research in this and also found it quite confusing. First thing I like to point out is that code-patterns are abstract. Meaning that you have loads of different way to implement it / tweak it.
What most people have told me is that in "real-life" applications you usually have layers of services.
One of these services is where you get data from a database.
The Model job (in my opinion) is to give the developer knowledge about the database data and structure. One Model to one database-tabel.
It also helps in checking if the data is correct (Format checking, Type of data and so on) before sending it to the DB.
There isn't a clear answer on how to use model. I've seen loads of different implementations, and they all have been implemented for specific tasks.
Yes it might come out that some ViewModels become heavy-loaded with code and functions to perform, but then it might not be because of the code-pattern. It can be because of poor structure in code. At my work right now I've found a ViewModel that contained over 3000 lines of code (Which is WAY to much). This could easily be seperated into atleast 3 different ViewModels and Views, but as I said, poor code structure causes problem.
One thing I recommend for you to read up on is
IoC - Inversion of Control
DoP - Dependency inversion principle
DI - Dependency Injection
Hope this helps in someway explaining your question.
I read many article that told me model just a contain data and not more business logic
A model may be represented by a service, a database access layer or a business layer so there is nothing wrong with your current approach. The business logic does belong to the model.
But sometimes people tend to refer to a "child" type as a model. For example, if your view model exposes a List<Item> property, the Item class may considered to be a model. Perhaps your confusion comes from this.
This kind of classes (Item) typically implement the INotifyPropertyChanged interface to provide change notifications and are effectively rather just "nested" view models that don't contain any business logic though.
Hope that makes sense.
In DDD, many models are there:
Domain model, which is used in busiess or application layer.
Data access model, which is used in data access or data repository layer.
Data transfer model (DTO), which is used in presentation layer.
Beacuse of them, the disadvantages raise:
They violate the DRY principle, beacuse many duplicate fields exist between them and can't avoid.
They need a lot of irritable mapping to conversion between different layers.
How can we reduce the irritable Models?
Ultimately, it is about choosing your battles. One of the main considerations in a Domain-Driven solution is that it is focused on isolating and encapsulation of the domain. That means that, by that very premise, you are not going to want to use it as an approach in every single project. You need to have an inherent complexity that you are trying to reduce, and you do so by modeling the needs of the business and the needs of the application independently. This means that you are not creating a single system, but one or more systems (your application or applications) that are utilizing a consummate subsystem (your domain).
Personally, I do not have the three types of data-bearing classes that you describe in any of my projects. Instead, I have only my domain model and a view model representation based on each distinct UI requirement. I have found that the need to have a separate set of persistence classes to be superfluous. There are several ways to eliminate the need for persistence classes, such as POCOs with code-first EF, object databases/NoSQL, and separation of your read model and write model. I opt for a combination of the last two, personally, in most cases.
The translation layer between the domain and application/UI is something that I find to be required, because the "truth" that the domain represents is infallible. But, in order to attain a usable interface into the domain, the application will sometimes have additional or differing requirements to the domain. That means that this translation layer is not just about field mapping, it is about encapsulation of differing concepts and isolation of usage scenarios.
Since the domain should have absolutely no knowledge of how it is used, that means that there is a requirement for translation and it is not something that should be attempted to be worked out of the system. I have seen people who have used their domain classes directly in the UI, as the actual model, and that is more heinous (in my opinion) than having to create a translation layer. You are looking at it from the perspective of just being for translation, but remember that it is also about isolation. Introduction of new concepts, changing of existing concepts, and other changes within the domain can effectively be intercepted in translation to prevent impact in the UI, and vice versa.
That sounds trivial, but in an enterprise setting, it is not uncommon for there to not be just a single application that utilizes the domain, but multiple applications. Consider the possibility that your domain is serving a desktop application, a web application, and a REST API. Each of those will have their own specific application requirements that are separate from your business requirements. They also will likely want to represent the domain differently from each other. This means that each of them will likely have things such as different validation requirements, different views into your domain, and unique application functionality. Regardless of all of this, the domain remains happily oblivious to it all. You will have to translate differently for each, somewhere above the domain.
If you are finding that your models are looking exactly like your domain, with a majority of it being one-to-one mappings, you might want to take a step back and look for some other issues that might be occurring. I find a large number of two-way mappings of singular fields to be a code smell. Not always, but often, this is an early sign of an anemic domain model. I personally go as far as to enforce architectural requirements on my domain model, such as requiring that properties be read-only (forcing them to be set through a constructor for existing data and changed through methods on the classes), etc. It is fairly trivial to write architectural unit tests which will reflect your domain classes to inspect them for possible violations of such rules. But, the point is if you find translation to be your pain point, make sure that your domain model is not just acting as a data container. Anemic domain models are an extraordinarily common pitfall in DDD implementations, and with an anemic domain model, there is actually very little benefit to a DDD approach at all, as you are taking the power and responsibility away from the place it should be enforced.
Business requirements should be reflective of the needs of the domain, which is not the same thing as the usage patterns of the domain. Ideally, you should be telling the domain how you want to change its state, and the domain should be applying the domain logic to allow or disallow those changes. If you find yourself pulling down a full domain model representation for a part of the domain, translating the entire thing to a model or DTO, modifying that model or DTO, translating it back to the domain representation, and sending the whole thing back in, you likely have a larger problem.
You may want to review your understanding of DRY. A good starting point is DRY is about Knowledge -- Matthias Verraes (2014).
You may also want to look at Gary Bernhardt's 2012 talk Boundaries.
The key idea is this - the DTO model is an API contract between the domain model and the presentation components. It gives us the freedom to aggressively update/adapt/improve the domain model without breaking the existing presentation component.
Similarly, the data access model is an API contract between the domain and the presentation component. Not only does this mean that the interface between the domain and persistence is stable, but it also provides a stable contract between the current implementation of the domain model (which writes data today) and future implementations of the domain model (which read back that same data tomorrow).
1. This is not about Domain-Driven Design
Separating models comes with your ancestral n-layer architectural style. It dates back long before DDD was around.
2. You don't have to have that many models
If your application is simple enough, you can ditch some of them.
"Data access model" comes to mind first. It's only a recent addition to the DDD paraphernalia. But you can do without just as well, with a minor impact on your domain model.
And guess what, you may even find out that you don't need a rich domain model at all... Some applications are just better off as CRUD.
If you find something "irritable", get rid of it and see for yourself what the benefits/drawbacks are. Code police won't come knocking at your workplace and lock you up for favoring simplicity over so-called orthodoxy.
No, there are not many models. There are multiple representations of the same model. This distinction is very important.
In the domain model, the entity is responsible of making sure that it's state is instact. For instance, the ApprovedAt property may not be set unless ApprovedBy is set at the same time. This is usually done by adding behavior to the entity. I do it by always setting all property setters to private and then add methods every time the entity need to change state.
The DTO is responsible of transferring state between over application boundaries. But when you do DDD correctly you do not want to transfer the domain entity to the client. You want it to remain safe within the server. Thus the role of the DTO is much more important. You might even have multiple DTOs for the same entity. For instance, I might have a UserListDTO which contains a subset for just listing entities and maybe a UserDetailsDTO which is designed for the user details page. For writes you just transfer the mutated state or send command influenced DTOs (ApproveUserDTO).
Finally it's important that the domain entity isn't forced to be designed in a certain way just to be able to persist it. That's why we have the data entity. It will be design so that everything can be persisted in a efficient way. The user might have a data entity called User and one called UserField depending on the domain entity design.
The conclusion is that if you models look exactly the same you are doing something wrong (from the perspective of DDD).
I have a project with the following structure:
Project.Domain
Contains all the domain objects
Project.EntityFramework, ref Project.Domain
Contains Entity Framework UnitOfWork
Project.Services, ref Project.Domain and Project.EntityFramework
Contains a list of Service classes that perform some operations on the Domain objects
Project.Web.Mvc, ref to all the projects above
I am trying to enforce some Business rules on top of the Domain objects:
For example, you cannot edit a domain object if it's parent is disabled, or, changing the name of an object, Category for example, needs to update recursively all it's children properties (avoiding / ignoring these rules will result in creating invalid objects)
In order to enforce these rules, i need hide all the public properties setters, making them as internal or private.
In order to do this, i need to move the Project.Services and Project.EntityFramework inside the Project.Domain project.
Is this wrong?
PS: i don't want to over complicate the project by adding IRepositories interfaces which would probably allow me to keep EntityFramework and Domain separate.
PS: i don't want to over complicate the project by adding IRepositories interfaces which would probably allow me to keep EntityFramework and Domain separate.
its really a bad idea, once i had this opinion but honestly if you dont program to abstraction it will become a pain when the project becomes larger. (a real pain)
IRepositories help you spread the job between different team members also. in addition to that you can write many helper extensions for Irepository to encapsulate Different Jobs for example
IReopisotry<File>.Upload()
you must be able to test each layer independently and tying them together will let you only do an integration tests with alot of bugs in lower layers :))
First, I think this question is really opinion based.
According to the Big Book the domain models must be separated from the data access. Your domain has nothing to with the manner of how storing the data. It can be a simple text file or a clustered mssql servers.
This choice must be decided based on the actual project. What is the size of the application?
The other huge question is: how many concurrent user use the db and how complex your business logic will be.
So if it's a complex project or presumably frequently modified or it has educational purposes then you should keep the domain and data access separated. And should define the repository interfaces in the domain model. Use some DI component (personally I like Ninject) and you should not reference the data access component in the services.
And of course you should create the test projects also using some moq tools to test the layers separately.
Yes this is wrong, if you are following Domain Driven Design, you should not compromise your architecture for the sake of doing less work. Your data-access and domain should be kept apart. I would strongly suggest that you implement the Repository pattern as it would allow you more flexibility in the long run.
There are of course to right answer to whats the right design...I would however argue that EF is you data layer abstraction, there is no way youre going to make anything thats more powerful and flexible with repositories.To avoid code repetition you can easily write extension methods (for IQueryable<>) for common tasks.Unit testing of the domain layer is easily handled by substituting you big DB with some in-proc DB (SqlLite / Sql Server Compact).IMHO with the maturity of current ORMs like nHibernate and EF is a huge waste of money and time to implement repositories for something as simple as DB access.
Blog post with a more detailed reply; http://ayende.com/blog/4784/architecting-in-the-pit-of-doom-the-evils-of-the-repository-abstraction-layer
I am currently studying towards my final year of a Computer Science degree, and working on my final project and dissertation. I will be using ASP.NET Web Forms and C# to create a 3-Layer project - I can't really call it 3-Tier as it will most likely never be hosted on anything other than my local PC for testing as it is for uni purposes only.
My main question is this:
From my understanding, the idea of 3-Layer is that the BLL references the DAL, and the UI references the BLL to create complete separation of concerns. However I have made a small mock up project following a few tutorials so get the hang of 3-Layer, and most basic tutorials still require a reference between the UI and BLL.
For example in the project I have created, which is a very basic Products and Categories type e-commerce system, I have created the Product and ProductDAL classes in the DAL, then the ProductBLL class in the BLL. With this setup, of only using one database table (forget categories for now), the BLL seems to only serve as a sort of interface between the UI and DAL, the methods are exactly the same as those in the DAL and only call the DAL version.
The problem is that to access the DAL via the BLL, I have to pass in a Product object to the BLL method arguments, which means creating a Product object in the UI first, which means referencing the DAL from the UI. Is this the correct way of doing things?
I can get around simple cases like this by creating a method in the BLL that takes the appropriate fields, e.g. strings and ints to create the Product Object and returns it to the AddProduct method. However when it comes to binding different product attributes to labels in the UI, I still need access to the Product object.
So essentially, do I need to make a load of methods in the BLL to access properties of the Product Object? If not, what kind of methods would actually go there, can you give me any examples of methods that may go in the BLL in this kind of Product scenario?
Thanks in advance, and apologies if this has been asked before - I did read through a lot of posts about 3-Layer architecture but most are very basic and only access one table.
the BLL seems to only serve as a sort of interface between the UI and DAL
This is only because this application is very simple - just a CRUD interface at the moment. More complex applications have business rules that would be encapsulated in the BLL (and not be in the UI or DAL).
I have to pass in a Product object to the BLL method arguments, which means creating a Product object in the UI first, which means referencing the DAL from the UI. Is this the correct way of doing things?
Well, there are several different options here:
You can have a Product data access object (DAO) that is shared between the different layers. This object is not a DAL object, but the DAL uses it. It is called a DTO - Data Transfer Object.
You can have several different Product object - one to be consumes by the UI, one by the BLL and one by the DAL and have mapping layers to translate between the different objects.
Some combination of the above.
A common way of separating concerns is to start by having a project called YourProject.Entities or something of the like. This contains the main class definitions and you reference it when you need to get a large entity like a customer or a product or something of the like. Alongside, you have another project which acts as a repository. Depending on the technology that you are using this can either implement something like EF to get your objects from your DB or can contain methods which query your DB directly using straight SQL or stored procedures.
What you have to keep in mind is that these projects are primarily going to function based on user input. Your users will act and your program will respond. The idea though is that the actual business logic is separated from your UI and your data access. You can mix and match these ideas as you wish, but what I have tended to see in my professional experience is basic data constraint enforcement done on the DB access side of things, and data validation either done directly when creating your objects in the Entities project or in a separate EntitiesValidation project which takes entities as a parameter.
If you don't want to have a separate validation project, something to keep in mind is that you can implement business logic directly in objects using constructors and properties. Constructors can enforce logic on inputs before creating objects, and using full properties--that is to say this...
private string myProp
public string MyProp
{
get
{
// Some code
}
set
{
// Some code
}
}
instead of this...
public string MyProp { get; set; }
Allows you to implement rules when accessing the data associated with those properties.
In the end, these questions can be answered many different ways and I am sure that every response to this question will give you different ideas and opinions on the best way to do things. For me, the two rules I always follow are DRY (do not repeat yourself) and code maintainability. By separating logic from data access from object design from UI, you will have a much easier time maintaining and updating your program when that time comes... even if it is just a school project ;).
When using simple DTOs in various scenarios I have frequently run into the same kind of problem and I always wondered whether there's a better way to deal with it.
The thing is, I have a business object, e.g. Asset which has a bunch of properties, child objects and calculated fields, some of them expensive to calculate in sense of time, some of them huge in sense of data amonut. I need to use a different flavor of this object in various screens in the UI, e.g.
in a tree where there is a hierarchy displayed and I don't need much more than the display name
in a grid where I'm showing just a couple of properties
in a detail pane where there's a big subset of available information, but still some of it (like mapped objects) is shown only on demand
To be able to achieve optimal performance with this scenario, I have always created different DTOs for each context, only containing the subset of information which is actually used in that context. While being a resource-optimal solution, this leads to couple of problems :
I have a class explosion with huge number of DTO classes
I have quite a hard time coming up with different names for the same thing like AssetDtoForGridInTheOverviewScreenInTheUpperPaneAboveTheSplitter, not to mention maintaining them later
I am frequently repeating myself in the transformation methods, because there are properties that are used by most of the DTOs but not by all of them (therefore I can't put them into any superclass and reuse the transformation logic)
The technology I'm using is ASP.NET SOAP WebServices and C# 3.5, but I think somehow this could be a language-agnostic problem. Any ideas are welcome..
This is a known problem with DTOs. It's described in this otherwise mediocre articule on MSDN. To paraphrase: DTO is the most versatile n-tier data access pattern, but it also requires most work.
You can address some of your issues with mapping by using convention-based mapping, such as AutoMapper.
When it comes to class explosion, could it be that you are using too flat data structures?
This can be difficult to tell because DTOs naturally include a great deal of semantic repetition that turns out to not be logical repetition at all. For example, even if you have semantically similar types, if one is a ViewModel and the other is a Domain Object, they may share semantic structure, but have vastly different responsibilities.
If, on the other hand, you have a lot of repetition in the same application layer (e.g. UI), you may be violating the DRY principle. In this case, it may often help to encapsulate related data in what starts out as a flat data structure into a separate class. In most UI frameworks I'm aware of, you can still databind a flat display to a hierarchically structured class.
The problem of class explosion is inherent to the DTO approach, there probably isn't much you can do about that. Be careful not to mix your view-model with your DTO model. Your DTO's should only be used to get the data from your data tier to your front end and not for presentation.
With the advent of .NET 3.5 you can choose to implement some basic, more coarse grained DTO's and replace your ViewModel with an anonymous type which you can dynamically create off your DTO's. I found this to be avery flexible solution.
Regarding your naming conventions, it is probably useful to group your DTO's into scenarios and put them in a corresponding namespace. For example Solution.AssetManagement.Asset and Solution.AssetReporting.Asset