Bad practice to have models made up of other models? - asp.net-mvc

I have a situation where I have Model A that has a variety of properties. I have discovered that some of the properties are similar across other models. My thought was I could create Model B and Model C and have Model A be a composite with a Model B property and a Model C property.
Just trying to determine if this is the best way to handle this situation.

It's definitely valid in certain situations. Let's say you have a Person class and a Company class, and they have the common properties streetNumber, streetName, postcode, etc. It makes sense to make a new model class called Address that both Person and Company contain. Inheritance is the completely wrong way to go in such a situation.

When properties (e.g. state) are the elements of commonality, I definately tend towards using composition rather than inheritance. When using inheritance, its perhaps best to wait until behavior is the commonality, and overrides are needed now or imminently.

What you're looking at is creating an Aggregate Root. A core paradigm of the Domain Driven Design (DDD) principals.
Certain models in your app will appear to belong "at the top" or "as root" to other objects. For example in the case of customers you might have a Contact model which then contains a collection of ContactPoints (names, addresses, etc).
Or a Post (in the case of a blog), which contains a collection of Comments, a Tite, Body and a TagSet (for tagging). Notice how the items i've highlighted as objects - these are other model types as opposed to simple types (strings, ints, etc).
The trick will come when and how you decide to 'fill' these Aggregate Root trees/graphs. Ie. How will you query just for a single TagSet? Will you go to the top and get the corresponding Post first? Maybe you just wanted to rename the tag "aspnetmvc" to "asp.net-mvc" for all Posts so you want to cut in and just get the TagSet item.
The MVC Storefront tutorial has some good examples of this pattern. Take a look if you can.

Related

Rails 3.0 - best practices: multiple subtypes of a model object

So this is probably a fairly easy question to answer but here goes anyway.
I want to have this view, say media_objects/ that shows a list of media objects. Easy enough, right? However, I want the list of media objects to be a collection of things that are subtypes of MediaObject, CDMediaObject, DVDMediaObject, for example. Each of these subtypes needs to be represented with a db table for specific set of metadata that is not entirely common across the subtypes.
My first pass at this was to create a model for each of the subtypes, alter the MediaObject to be smart enough to join into those tables on it's conceptual 'all' behavior. This seems straightforward enough but I end up doing a lot of little things that feel not so rails-O-rific so I wanted to ask for advice here.
I don't have any concrete code for this example yet, obviously, but if you have questions I'll gladly edit this question to provide that information...
thanks!
Creating a model for each sub-type is the way to go, but what you're talking about is multiple-table inheritance. Rails assumes single-table inheritance and provides really easy support for setting it up. Add a type column to your media_objects table, and add all the columns for each of the specific types of MediaObject to the table. Then make each of your models a sub-class of MediaObject:
class MediaObject < ActiveRecord::Base
end
class CDMediaObject < MediaObject
end
Rails will handle pulling the records out and instantiating the correct subclass, so that when you MediaObject.find(:all) the results will contain a mixture of instances of the various subclasses of MediaObject.
Note this doesn't meet your requirement:
Each of these subtypes needs to be represented with a db table for specific set of metadata that is not entirely common across the subtypes.
Rails is all about convention-over-configuration, and it will make your life very easy if you write your application to it's strengths rather than expecting Rails to adapt to your requirements. Yes, STI will waste space leaving some columns unpopulated for every record. Should you care? Probably not; database storage is cheap, and extra columns won't affect lookup performance if your important columns have indexes on them.
That said, you can setup something very close to multiple-table inheritance, but you probably shouldn't.
I know this question is pretty old but just putting down my thoughts, if somebody lands up here.
In case the DB is postgres, I would suggest use STI along hstore column for storing attributes not common across different objects. This will avoid wasting space in DB yet the attributes can be accessed for different operations.
I would say, it depends on your data: For example, if the differences between the specific media objects do not have to be searchable, you could use a single db table with a TEXT column, say "additional_attributes". With rails, you could then serialize arbitrary data into that column.
If you can't go with that, you could have a general table "media_objects" which "has one :dataset". Within the dataset, you could then store the specifics between CDMediaObject, DVDMediaObject, etc.
A completely different approach would be to go with MongoDB (instead of MySQL) which is a document store. Each document can have a completely different form. The entire document tree is also searchable.

What to consider when deciding to use Single Table Inheritance

I'm getting ready to start a small project that provides an opportunity to use single table inheritance. As I read through prior post on STI on Stackoverflow there seems to be some strong opinions on sides of the argument.
My application is related to my horse racing hobby. A horse's connections are defined as its current jockey, trainer and owner. The jockey, trainer and owner could be modeled using three separate tables (models/classes) or as one one class with several sub-classes through single table inheritance.
When faced with a decision like this, is there a check list of questions that one can go through to determine what approach is preferable. I'm assuming that using STI would reduce the number of potential joins. What are the other practical considerations?
There are a few things you should think about:
Are the objects, conceptually, children of a single parent?
Don't use single table inheritance just because your classes share some attributes; make sure there is actually an OO inheritance relationship between each of them and an understandable parent class.
Do you need to do database queries on all objects together?
If you want to list the objects together or run aggregate queries on all of the data, you’ll probably want everything in the same database table for speed and simplicity.
Do the objects have similar data but different behavior?
If you have a larger number of model-specific columns, you should consider polymorphic associations instead.
The article linked goes in depth a bit more.

Domain Driven Design: When to make an Aggregate Root?

I'm attempting to implement DDD for the first time with a ASP.NET MVC project and I'm struggling with a few things.
I have 2 related entities, a Company and a Supplier. My initial thought was that Company was an aggregate root and that Supplier was a value object for Company. So I have a Repository for company and none for Supplier.
But as I have started to build out my app, I ended up needing separate list, create, and update forms for the Supplier. The list was easy I could call Company.Suppliers, and create was horrible I could do Company.Suppliers.Add(supplier), but update is giving me a headache. Since I need just one entity and I can't exactly stick it in memory between forms, I ended up needing to refetch the company and all of the suppliers and find the one I needed to bind to it and again to modified it and persist it back to the db.
I really just needed to do a GetOne if I had a repository for Supplier. I could add some work arounds by adding a GetOneSupplier to my Company or CompanyRepository, but that seems junky.
So, I'm really wondering if it's actually a Value Object, and not a full domain entity itself.
tldr;
Is needing separate list/create/update view/pages a sign that an entity should be it's own root?
Based on your terminology I assume you are performing DDD based on Eric Evans' book. It sounds like you have already identified a problem with your initial go at modeling and you are right on.
You mention you thought of supplier as a Value Object... I suggest it is not. A Value Object is something primarily identified by its properties. For example, the date "September 30th, 2009" is a value object. Why? Because all date instances with a different month/day/year combo are different dates. All date instances with the same month/day/year combo are considered identical. We would never argue over swapping my "September 30th, 2009" for yours because they are the same :-)
An Entity on the other hand is primarily identified by its "ID". For example, bank accounts have IDs - they all have account numbers. If there are two accounts at a bank, each with $500, if their account numbers are different, so are they. Their properties (in this example, their balance) do not identify them or imply equality. I bet we would argue over swapping bank accounts even if their balances were the same :-)
So, in your example, I would consider a supplier an Entity, as I would presume each supplier is primarily identified by its ID rather than its properties. My own company shares its name with two others in the world - yet we are not all interchangeable.
I think your suggestion that if you need views for CRUDing an object then it is an Entity probably holds true as a rule of thumb, but you should focus more on what makes one object different from others: properties or ID.
Now as far as Aggregate Roots go, you want to focus on the lifecycle and access control of the objects. Consider that I have a blog with many posts each with many comments - where is/are the Aggregate Root(s)? Let's start with comments. Does it make sense to have a comment without a post? Would you create a comment, then go find a post and attach it to it? If you delete a post, would you keep its comments around? I suggest a post is an Aggregate Root with one "leaf" - comments. Now consider the blog itself - its relationship with its posts is similar to that between posts and comments. It too in my opinion is an Aggregate Root with one "leaf" - posts.
So in your example, is there a strong relationship between company and supplier whereby if you delete a company (I know... you probably only have one instance of company) you would also delete its suppliers? If you delete "Starbucks" (a coffee company in the US) do all its coffee bean suppliers cease to exist? This all depends on your domain and application, but I suggest more than likely neither of your Entities are Aggregate Roots, or perhaps a better way to think about them is that they are Aggregate Roots each with no "leaves" (nothing to aggregate). In other words, company does not control access to or control the lifecycle of suppliers. It simply has a one-to-many relationship with suppliers (or perhaps many-to-many).
This brings us to Repositories. A Repository is for storing and retrieving Aggregate Roots. You have two (technically they are not aggregating anything but its easier than saying "repositories store aggregate roots or entities that are not leaves in an aggregate"), therefore you need two Repositories. One for company and one for suppliers.
I hope this helps. Perhaps Eric Evans lurks around here and will tell me where I deviated from his paradigm.
Sounds like a no-brainer to me - Supplier should have its own repository. If there is any logical possibility that an entity could exist independently in the model then it should be a root entity, otherwise you'll just end up refactoring later on anyway, which is redundant work.
Root entities are always more flexible than value objects, despite the extra implementation work up front. I find that value objects in a model become rarer over time as the model evolves, and entities that remain value objects were usually the ones that you could logically constrain that way from day one.
If companies share suppliers then having supplier as a root entity removes data redundancy as well, as you do not duplicate the supplier definition per company but share the reference instead, and the association between Company and Supplier can be bi-directional as well, which may yield more benefits.

Is there a standard model to controller 'ratio' when trying to implement good ASP.NET MVC?

I'm not sure if this question is non-sense or not, please tell me if so. I am wondering do I create my models like one per each table in my database, or do you do one per controller? Is there something I am missing here?
From what I read the Model is suppose to be a representation of the real business objects, so would I just want to make it one big model or divide them out based on things in the app? based on real user/client perception of the data?
Thanks for your advice.
There's nothing wrong with controllers sharing models. But trying to serve every controller with the same model doesn't make sense.
Models and controllers really are't related, nor should they be. Models also aren't directly related to how data is stored in your application.
Models encapsulate data. Their design should be dictated by the data they are encapsulating. The demands of the system dictate what models you'll need and what data they must hold.
Don't try to overthink it. For a given request, determine what you need to show in your view and how it will be displayed. Determine what an appropriate model would look like for this scenario. If one already exists, use it. If not, create a new model. Save the overengineering later when you know what your needs are and can find commonalities between models.
Models can also contain other models, that's fine. Think of a model for a sales report. You would have a model for the report which would contain not only a report name, a total, but also a collection of other models which make up the report's line items.
It depends on what you mean by "Model". If by model you mean the business rule layer of your application, then there is no relationship in terms of numbers. One model of that type is used for any amount of views you need to build.
Personally, however, I would not bind any view to any model, but create an intermediary layer called a ViewModel that essentially taylors the data from your model to fit a particular view. In that case, the relationship is one-to-one. This is essentially how Presenter patterns work. Every view is strongly typed to it's own ViewModel that is populated from the Model layer.
Models do not necessarily have a literal coorespondence with the database either. How you store data your model is different from how your "Model" uses that data.

What attributes should belong to a page and what should belong to a model?

Say you have an Events model that contains information about the event. But what about things like slugs, titles and meta description that would go into the html?
It would seem like such things properly belong as attributes to a Page model rather than to an Events model.
Is there a correct way to do this? What are the pros and cons of one approach over the other?
An Event has some first-class attributes and some "derived" attributes.
Let's focus on Django.
For example, your model might have a big long title and a derived slug.
You can easily define class methods for this derived data.
However, in some cases, you need to denormalize your model to make derived data persistent. In this case, you'll have additional attributes and you'll set those attributes through the save() method.
"Correct" is well-defined -- 3rd Normal Form is correct. You can afford to compute derived fields if they aren't computed all that often. In some cases, you have to break 3NF and persist the data for performance.

Resources