Ok to have unbound roles in a DCI Context? - dci

I'm working on a CreditCardPayment context, and found this possibility that not all roles are needed for some context methods. For example, the method CreateSecurityHash may require all roles, but VerifyHash only requires one. Is it ok not to bind all roles? If so, what about introducing multiple constructors and only bind what's needed, like this:
public CreditCardPayment(objectA, objectB, objectC)
{
BindRoles(objectA, objectB, objectC)
}
public CreditCardPayment(objectA)
{
BindRoles(objectA, null, null)
}
It feels difficult though to know what context methods are allowed to call when doing this. So I'd like to know:
Is this still ok (if so, why?), or
Is the whole scenario a sign that another context is needed, or
Should I keep the context and supply all objects needed for the roles, always?

If you feel like not binding all roles there's a few questions you should go and ask your self. You've already asked one of them "Should I create two contexts?" to answer that question I'd look at the context as a hole. If it does indeed model one process then don't divide that into several. We wish to model the end users mental model. If that model is complex there's nothing we can do to change that but we can help by reflecting it.
In your particular case it would seem that you are indeed modelling one process in which case you should keep the context as one. Boind the roles once and know that from that point on you are safe to call use the interactions.
Not binding roles will lead to code that is unnessecarily hard to reason about. "Will it be safe to call this method?" you will only be able to answer that at runtime when you can see which roles have been bound. All roles are always bound at the same time at this happens prior to the interaction or is the first part of the interaction

Related

How many DbContext subclasses should I have, in relation to my models?

I'm learning ASP.NET MVC and I'm having some questions that the tutorials I've read until now haven't explored in a way that covers me. I've tried searching, but I didn't see any questions asking this. Still, please forgive me if I have missed an existing ones.
If I have a single ASP.NET MVC application that has a number of models (some of which related and some unrelated with each other), how many DbContext subclasses should I create, if I want to use one connection string and one database globally for my application?
One context for every model?
One context for every group of related models?
One context for all the models?
If the answer is one of the first two, then is there anything I should have in mind to make sure that only one database is created for the whole application? I ask because, when debugging locally in Visual Studio, it looks to me like it's creating as many databases as there are contexts. That's why I find myself using the third option, but I'd like to know if it's a correct practice or if I'm making some kind of mistake that will come back and bite me later.
#jrummell is only partially correct. Entity Framework will create one database per DbContext type, if you leave it to its own devices. Using the concept of "bounded contexts" that #NeilThompson mentioned from Julie Lerhman, all you're doing is essentially telling each context to actually use the same database. Julie's method uses a generic pattern so that each DbContext that implements it ends up on the same database, but you could do it manually for each one, which would look like:
public class MyContext : DbContext
{
public MyContext()
: base("name=DatabaseConnectionStringNameHere")
{
Database.SetInitializer(null);
}
}
In other words, Julie's method just sets up a base class that each of your contexts can inherit from that handles this piece automatically.
This does two things: 1) it tells your context to use a specific database (i.e., the same as every other context) and 2) it tells your context to disable database initialization. This last part is important because these contexts are now essentially treated as database-first. In other words, you now have no context that can actually cause a database to be created, or to signal that a migration needs to occur. As a result, you actually need another "master" context that will have every single entity in your application in it. You don't have to use this context for anything other than creating migrations and updating your database, though. For your code, you can use your more specialized contexts.
The other thing to keep in mind with specialized contexts is that each instantiation of each context represents a unique state even if they share entities. For example, a Cat entity from one context is not the same thing as a Cat entity from a second context, even if they share the same primary key. You will get an error if you retrieved the Cat from the first context, updated it, and then tried save it via the second context. That example is a bit contrived since you're not likely to have the same entity explicitly in two different contexts, but when you get into foreign key relationships and such it's far more common to run into this problem. Even if you don't explicitly declare a DbSet for a related entity, it an entity in the context depends on it, EF will implicitly create a DbSet for it. All this is to say that if you use specialized contexts, you need to ensure that they are truly specialized and that there is zero crossover at any level of related items.
I use what Julie Lerman calls the Bounded Context
The SystemUsers code might have nothing to do with Products - so I might have a System DbContext and a Shop DbContext (for example).
Life is easier with a single context in a small app, but for larger application it helps to break the contexts up.
Typically, you should have one DbContext per database. But if you have separate, unrelated groups of models, it would make sense to have separate DbContext implementations.
it looks to me like it's creating as many databases as there are
contexts.
That's correct, Entity Framework will create one database per DbContext type.

DCI, trouble with concept of 'context' and what roles within know of each-other

I may just be missing a key concept here. I understand the 'dumb' data objects. I also understand that roles are stateless collections of methods applied to a dumb object when it takes on that role. I also understand that a context assembles the actors that will take place in the algorithm being implemented. But what the roles know about each-other, and weather they must be defined within the context, or outside it is unknown to me.
Say a context has 2 roles, start and end. Our use-case is string concatenation, so we will be assigning a string to each role.
some psudocode:
context concat {
role start {
method concat() {...}
method get_value {self->as_string}
}
role end {
method get_value {self->as_string}
}
// According to the docs I have read, the context simply kicks off a method in
// a role, the role handles the rest.
start.concat(?)
}
Now for 3 different combinations of how concat() (the method) and start.concat(?) (the call) may need to be:
Roles are aware of other roles in the same context (forcing roles to be non-reusable in other contexts, which seems wrong to me.)
concat{ self.get_value + end.get_value }
start.concat() // Not passing 'end' as an argument,
// it is already aware of end because
// it is defined in the same context
Roles are not aware of the other roles in the context, and thus need them passed in as arguments (Which seems a pain as a context could have any number of roles, if the context starts by kicking off a method we could need to pass 30 'roles' into the one method call as arguments, then chain them all the way!)
(Note: In this one the role definitions may be moved outside the context, and re-used in multiple contexts)
concat( end x ) { self.get_value + x.get_value )
start.concat(x)
To me the most obvious choice seems to be to not force context to kick off a method and nothing more. Then put the interaction logic into the context, and the non-interactive parts into roles. (Note: In this one the role definitions may be moved outside the context, and re-used ina couple of contexts)
concat() UNDEFINED
start.get_value + x.get_value
This seems to contradict this though:
http://en.wikipedia.org/wiki/Data,_Context_and_Interaction#Execution_Model
the Context invokes a Role method on the first object to take part in the use case.
From that point forward, Roles invoke each others' methods to carry out the use case.
In DCI the roles are usually aware of the context, and the context can act a repository for all the relavant roles. I.e. case number two where the role can access the context, and ask it for the objects playing the other roles it needs.
This is implementation detail though. Passing the needed objects into role methods can work too. The important part is that the roles interact with each other through the role methods (that is, not through role player methods, since that creates an unfortunate coupling).
Roles are - generally speaking - not expected to be candidates for reuse across contexts. A context roughly corresponds to a use case, and the roles implement the behavior of the use case. In general that logic is not reusable across use cases.
Hope this helps.
Also you may want to check out the artima article introducing DCI, and the object-composition google group.

When to create a class vs setting a boolean flag?

I have an interesting question to pose; when should one create a model class/object as opposed to setting a boolean flag for data stored in a database?
For example, say I have a Person class that has boolean flags for President, Guard, and PartTime. This class/model is treated differently depending on the value of the flags. So the President gets different privileges in the system from the Guard and from the PartTime(r).
When would one use Single Table Inheritance to represent this information and when would one just continue to use the boolean flag?
My instinct is to convert these to different Objects using STI since this seems more OO to me. Checking booleans seems wrong in some way, but I can also see a place for it.
Update for clarification
Let me use another example because the one above has too many cases involved with it.
I am working on a CMS application that contains Pages, a Page can be Public, Private, Shared, Hidden, or Default (meaning it is what you get when you don't specify a page in the url). Right now, we have a Page model and everything is a boolean flag - Public, Default, Shared.
I am not convinced this is the best method of handling this. Especially since we have rules governing what page can be what, i.e., the Default page or a Shared page must be a Public page whereas a Private page is just Private.
I agree with the comment below that Roles for the Person example makes a lot of sense. I am not sure that for the Page example it does.
And to make things more complicated, there can only be one Default page and one Shared page. STI may allow me to validate this, but I am not sure since there can be many default and shared pages in the table (just not associated with a particular site).
Note: The context for the question is a Ruby on Rails application, but is applicable for any object-oriented language.
First of all, let's establish what single-table inheritance typically is used for. It is a way to combine the storage and behaviour of multiple things that resemble each other. Sticking to a CMS, an example would be a table with posts, which could be either a Comment or an Article. They share similar data and behavior, but are ultimately different things. Whether or not something is a comment is not the state of the object, it's an identity.
In your example, however, whether or not a page is public or private, shared or not, or hidden, appears to be a part of the state of the page. Although single-table inheritance might technically work (provided all subclasses are mutually exclusive), it's not a good fit.
State should be implemented in one or more columns. An attribute that represents a certain dual state can be specified as a boolean; yes or no. If a page always is either private or public, you can model this as a single boolean column, private. If it's not private it's public (or the other way around).
In some cases you may want to store three or more different states that are mutually exclusive. For example, a page could be either private, or public, or shared (I don't know if this is the case -- let's pretend that it is). In this case a boolean will not help. You could use multiple boolean flags, but as you correctly observe that is very confusing. The easiest way is to model this as an enumeration. Or when you lack this (as is the case with Rails), simply use string values with a special meaning and add a validation that ensures the only values you use are one of private, public or shared.
Sometimes certain combinations of different state variables are invalid. For example, a page might be a draft or approved (reflected by a boolean column approved); and it is also either public or private (also reflected by a boolean column). We could decide that a page should must be approved before it is made public. In this case we declare one of the states invalid. This should be reflected by the validation of your model. It is important to realise that a draft, public page is not fundamentally impossible, it's only impossible because you decide it should not happen.
When creating your model, make a careful distinction between the attributes that reflect actual properties and states of the subjects in the real world, and the business rules that determine what should be possible and what shouldn't be. The first should be modelled as columns, the second as validations.
Original answer:
One obvious difference is that boolean flags allow a Person to be marked as president and guard at the same time. If your model should allow these situations, single-table inheritance will not work for you.
On the other hand, maybe a Person that is a president behaves differently from a regular person; and a single person can only be president or guard. In this case inheritance may be a better fit. I don't think you should model "part time" as a subclass, though. That is an attribute in any case.
There is also an important third option, one where you completely separate the job or role of a person from the model. One person has one (or many?) jobs, which are or are not part-time. The advantage of this model is that you separate attributes of a person from the attributes of their job. After all, people change jobs, but that does not make them literally a different person. Ultimately this seems to me the most realistic way to model your situation.
I prefer not to use a flag for this, but also not to subclass Person for this. Rather, attach a Role (or if you have someone who's both a President and a Guard, a set of Roles) with subclasses of Role governing the prvileges.
Personally, I am neither a President nor a Guard, but I am both a Programmer and a Musician, and have a few other roles at times (in fact, I was a Guard for a while simultaneous with being a Student many years ago.).
A Person has-a Role.
I have found that whenever I think "Hm, I have these 3 types of behavior and they do look like subclasses, but need to change at runtime", look at a strategy or state pattern. It usually fits very well and usually also beats a simple boolean flag with respect to keeping responsiblities apart.
In your case, this heuristic would say that you have a Person with an attribute of type AccessRights, which decides if a certain action can be performed or not. Person either gives access to this object or delegates appropiate methods. After that, you have PresidentialRights, GuardRights and PartTimeRights implemetning this AccessRights interface and you are good to go.
Given this, you never need to change the person class whenever a new type of access right appears, you might need to change the person class if a new type of action appears (depends on if you delegate and how you delegate) and in order to add new types of AccessRights, you just add new implementations of AccessRights.
the answer is that it is basically a design decision. There is not an a priori right way of designing an architecture. When you define classes and relationships among them you define an architecture and, at the same time, a language representing the domain of your application.
As any languages it consists of a vocabulary (i.e. Person, President, Guard, etc.); a Syntax (i.e. the relationships you can specify for the instances of your vocabulary) and Semantics (i.e. the meaning of the terms you specify in vocabulary and relationships).
Now you can obviously obtain the same behaviour in possibly infinite way. And anyone would come up with a different architecture for the same system since anyone might have a different way of thinking at the problem.
Despite this there are some criteria you should take into account when designing.
When you define a Class you are defining a "first order" construct of your language, when you define attributes for a Class you are describing the characteristics of your first order constructs.
The best way to decide if you need a class or an attribute might be this.
Do Presidents and Guards have different characteristics apart of those they share since they are both person? If that is the case, and they have a number of different characteristics you should create two classes (one for the President and one for the Guard)both inheriting from Person. Otherwise you have to collapse all the characteristics (those belonging to person, those belonging to President and those belonging to Guard) in the Person class and condition their validity to another flag (type). This would be a very bad design
The characteristic of a Page of being public or not is instead something which actually describes the status of a page. It is therefore quite reasonable to model it as a Property of the Page Class

MVC Validation using Data Annotations - Scenarios where it doesn't work, Alternatives?

So I have been using data annotations for my validation in an MVC project and they seem to work in most scenarios.
Here are two examples in my current project where they don't seem to fit and I am unsure of the best place to put the validation.
1) I have a Join League page that contains a form where the logged in user enters their team name and clicks to join the league. When they submit the form i need to make sure that the current user doesn't already have a team in the league. So it basically needs to query the db for that user id and league id to make sure no team exists for the user. My ViewModel does not contain user id, since it is not relevant to the view.
2) On this same page, I also need to make sure the team name is unique. This is easy if you are just looking to see if it exists in a table. You create a custom validation attribute that query's a table for the value of the field. However i need to see if it exists in a table for a certain league id. (the league they are joining.)
It doesn't seem like Data Annotations are an ideal solution for anything other then trivial validation. My current solution is to query the db at beginning of post action method, and add the error to the ModelState manually. (yes, terrible)
Any ideas?
I think it may help to put some thought into the difference between Input Validation and Business Logic. Ayende has some thoughts on this here
Rules like 'When they submit the form I need to make sure that the current user doesn't already have a team in the league' sounds like Business Logic, not Input Validation, and you may want to handle it in a different way. This logic could, for instance, go into a 'CanSave' method on a 'User' class or something similar - the key thing is to separate this from Input Validation if you can.
Although I agree with Steve, DataAnnotations has a base ValidationAttribute in which you can implement anything you want. To say it can only do trivial things is not accurate in fact with this extensibility point you can do almost anything you want.
Now there are some issues with service location being all over the place by having database logic inside your code but there are options to clean this up. The DataAnnotations are applied via a ModelValidatorProvider class that can easily be configured just like you would do ControllerFactories or ViewEngines.
ModelValidatorProviders.Providers.Add(new YourCustomProvider());
Now what you can do in this case is have your validator provider provide the persistence layer code into your attribute. So the code stays clean yet you can use custom data annotation attributes that touch the db.

Reusing validation attributes in custom ViewModels

When I started using xVal for client-side validation, I was only implementing action methods which used domain model objects as a viewmodel or embedded instances of those objects in the viewmodel.
This approach works fine most of the time, but there are cases when the view needs to display and post back only a subset of the model's properties (for example when the user wants to update his password, but not the rest of his profile data).
One (ugly) workaround is to have a hidden input field on the form for each property that is not otherwise present on the form.
Apparently the best practice here is to create a custom viewmodel which only contains properties relevant to the view and populate the viewmodel via Automapper. It's much cleaner since I am only transferring the data relevant to the view, but it's far from perfect since I have to repeat the same validation attributes that are already present on the domain model object.
Ideally I'd like to specify the Domain Model object as a meta class via a MetaData attribute (this is also often referred to as "buddy class"), but that doesn't work since xVal throws when the metadata class has properties that are not present on the viewmodel.
Is there any elegant workaround to this? I've been considering hacking the xVal sourcecode, but perhaps there is some other way I have overlooked so far.
Thanks,
Adrian
Edit: With the arrival of ASP.NET MVC 2, this is not only a problem related to validation attributes anymore, but it also applies to editor and display attributes.
This is the quintessential reason why your input screens should not be tightly coupled to your model. This question actually pops up here on the MVC tag about 3-4 times a month. I'd dupe if I could find the previous question and some of the comment discussion here is interesting. ;)
The issue your having is you're trying to force two different validation contexts of a model into a single model which fails under a large amount of scenarios. The best example is signing up a new user and then having an admin edit a user field later. You need to validate a password on a user object during registration but you won't show the password field to the admin editing the user details.
The choices for getting around these are all sub-optimal. I've worked on this problem for 3 projects now and implementing the following solutions has never been clean and usually frustrating. I'm going to try and be practical and forget all the DDD/db/model/hotnessofthemonth discussions everybody else is having.
1) Multiple View Models
Having viewmodels that are almost the same violates the DRY principal but I feel the costs of this approach are really low. Usually violating DRY amps up maintenance costs but IMHO the costs for this are the lowest and don't amount to much. Hypothetically speaking you don't change how max number characters the LastName field can have very often.
2) Dynamic Metadata
There are hooks in MVC 2 for providing your own metadata for a model. With this approach you could have whatever your using to provide metadata exclude certain fields based on the current HTTPRequest and therefore Action and Controller. I've used this technique to build a database driven permissions system which goes to the DB and tells the a subclass of the DataAnnotationsMetadataProvider to exclude properties based values stored in the database.
This technique is working great atm but the only problem is validating with UpdateModel(). To solve this problem we created a SmartUpdateModel() method which also goes to the database and automatically generates the exclude string[] array so that any non-permissisable fields aren't validated. We of course cached this for performance reasons so its not bad.
Just want to reiterate that we used [ValidationAttributes] on our models and then superceeded them with new rules on runtime. The end result was that the [Required] User.LastName field wasn't validated if the user didn't have permission to access it.
3) Crazy Interface Dynamic Proxy Thing
The last technique I tried to was to use interfaces for ViewModels. The end result was I had a User object that inherited from interfaces like IAdminEdit and IUserRegistration. IAdminEdit and IUserRegistration would both contain DataAnnotation attributes that performed all the context specific validation like a Password property with the interfaces.
This required some hackery and was more an academic exercise than anything else. The problem with 2 and 3 is that UpdateModel and the DataAnnotationsAttribute provider needed to be customized to be made aware of this technique.
My biggest stumbling block was I didn't ever want to send the whole user object to the view so I ended up using dynamic proxies to create runtime instances of IAdminEdit
Now I understand this is a very xVal specific question but all of the roads to dynamic validation like this lead to customization of the internal MVC Metadata providers. Since all the metadata stuff is new nothing is that clean or simple to do at this point. The work you'd have to do to customize MVC's validation behavior isn't hard but requires some in depth knowledge of how all of the internals work.
We moved our validation attributes to the ViewModel layer. In our case, this provided a cleaner separation of concerns anyway, as we were then able to design our domain model such that it couldn't get into an invalid state in the first place. For example, Date might be required on a BillingTransaction object. So we don't want to make it Nullable. But on our ViewModel, we might need to expose Nullable such that we can catch the situation where the user didn't enter a value.
In other cases, you might have validation that is specific per page/form, and you'll want to validate based on the command the user is trying to perform, rather than set a bunch of stuff and ask the domain model, "are you valid for trying to do XYZ", where in doing "ABC" those values are valid.
If ViewModels are hypothetically being forced upon you, then I recommend that they only enforce domain-agnostic requirements. This includes things like "username is required" and "email is formatted properly".
If you duplicate validation from the domain models in the view models, then you have tightly coupled the domain to the UI. When the domain validation changes ("can only apply 2 coupon per week" becomes "can only apply 1 coupon per week"), the UI must be updated. Generally speaking, this would be awful, and detrimental to agility.
If you move the validation from the domain models to the UI, you've essentially gutted your domain and placed the responsibility of validation on the UI. A second UI would have to duplicate all the validation, and you have coupled two separate UI's together. Now if the customer wants a special interface to administrate the inventory from their iPhone, the iPhone project needs to replicate all the validation that is also found in the website UI.
This would be even more awful than validation duplication described above.
Unless you can predict the future and can rule out these possibilities, only validate domain-agnostic requirements.
I don't know how this will play for client-side validation, but if partial validation is your issue you can modify the DataAnnotationsValidationRunner discussed here to take in an IEnumerable<string> list of property names, as follows:
public static class DataAnnotationsValidationRunner
{
public static IEnumerable<ErrorInfo> GetErrors(object instance, IEnumerable<string> fieldsToValidate)
{
return from prop in TypeDescriptor.GetProperties(instance).Cast<PropertyDescriptor>().Where(p => fieldsToValidate.Contains(p.Name))
from attribute in prop.Attributes.OfType<ValidationAttribute>()
where !attribute.IsValid(prop.GetValue(instance))
select new ErrorInfo(prop.Name, attribute.FormatErrorMessage(string.Empty), instance);
}
}
I'm gonna risk the downvotes and state that there is no benefit to ViewModels (in ASP.NET MVC), especially considering the overhead of creating and maintaining them. If the idea is to decouple from the domain, that is indefensible. A UI decoupled from a domain is not a UI for that domain. The UI must depend on the domain, so you're either going to have your Views/Actions coupled to the domain model, or your ViewModel management logic coupled to the domain model. The architecture argument is thus moot.
If the idea is to prevent users from hacking malicious HTTP POSTs that take advantage of ASP.NET MVC's model binding to mutate fields they shouldn't be allowed to change, then A) the domain should enforce this requirement, and B) the actions should provide whitelists of updateable properties to the model binder.
Unless you're domain is exposing something crazy like a live, in-memory object graph instead of entity copies, ViewModels are wasted effort. So to answer your question, keep domain validation in the domain model.

Resources