Data driven view of associations vs. Behavior driven view of associations - associations

From UML user guide,chapter 5, I've found the following:
To model structural relationships,
For each pair of classes, if you need to navigate from objects of one to objects of another, specify an association between the two. This is a data-driven view of associations.
For each pair of classes, if objects of one class need to interact with objects of the other class other than as parameters to an operation, specify an association between the two. This is more of a behavior-driven view of associations
And this is my understanding about the first type of association,data-driven view of associations through the following example: a class, User, with three attributes, one of which is another class, Address.
class User {
String firstName;
String lastName;
Address address;
}
class Address {
String streetName;
int streetNumber;
String postalCode;
}
and the UML diagram of the above situation is:
Note that the third attribute of User converted to association end(as far as I know because it is of Address class type)
My questions:
1- Is this the correct interpretation of data-driven view of associations?
2- What about behavior-driven view of associations? is there an example explains it?

Data - driven associations are normal associations with aggregation, multiplicity, navigability and all these things. They are well defined.
Behavior-driven associations you use when showing functions that belong to one class and use other class instance as a parameter or the result. Also here belongs any complex connection, such as "listens", "registers" and so on. They are shown as dependencies, maybe with some additional letter, such as <<u>> (usage). They are not strictly defined and can't be used for code generation.
Don't believe much to the words "UML user guide" - all of them are simply books and are not the part of UML standard. They are not saint and are full of personal views (and alas, fallacies) of authors. Nowhere in UML standard is forbidden to use Dependencies for showing the use of other class in some parameter list.

Related

Write OCL restrictions related to associations with other classes

How do you model the following restriction?
A place is popular if it has been bookmarked by 2 or more than 2 users.
Here the corresponding uml diagram:
uml
I tried several ways, for example:
context place inv: place.popular = (self.user.place.popular>=2)
but nothing worked well...
The constraint that you expressed is an interesting start but does not work because self.user in the place context is a collection. Your expression moreover attempts to use popular as if it were an integer.
If there would be an unambiguous user, you’d just need to check its size():
context place inv:
place.popular = (self.user->size()>1)
Unfortunately, there are two associations with User: one for the favorites (bookmarks) and for for historic (past visits whether they appreciated or not). This makes that expression ambiguous. To disambiguate, in absence of a role name (name at the association end), you’ll need to qualify the user with the association name:
context place inv:
place.popular = (self.favorites::user->size()>1)
(Btw, in case of absence of association name, you'd need to use the default name A_place_user instead of favorites).
See also section 7.5.3 of the OCL specifications for more information about navigating associations.
Edit: more complex navigations**:
You could also navigate to properties of associated classes. It works like the navigation above, but with the help of the collect() operation. You can then perform collection oprations such as sum()
context route inv:
self.totalDistance = self.step->collect(distanceFromPreviousStep)->sum()
Navigating to a specific object in a collection of linked objects is more delicate. In the case of the steps, we see that the association is ordered (by the way, it should be {ordered} and not «ordered»). This allows to use last() to get the last element in the given order:
context route inv:
self.destination::place = self.step->last().place

DDD : How to model association between aggregate roots

We have a aggregate root as follows.
#AggregateRoot
class Document {
DocumentId id;
}
The problem statement given by the client is "A document can have multiple document as attachments"
So refactoring the model will lead to
//Design One
#AggregateRoot
class Document {
DocumentId id;
//Since Document is an aggregate root it is referenced by its id only
Set<DocumentId> attachments;
attach(Document doc);
detach(Document doc);
}
But this model alone won't be sufficient as the client wants to store some meta information about the attachment, like who attached it and when it was attached. This will lead to creation of another class.
class Attachment {
DocumentId mainDocument;
DocumentId attachedDocument;
Date attachedOn;
UserId attachedBy;
//no operation
}
and we could again refactor the Document model as below
//Design Two
#AggregateRoot
class Document {
DocumentId id;
Set<Attachment> attachments;
attach(Document doc);
detach(Document doc);
}
The different possibilities of modeling that I could think of are given below.
If I go with design one then I could model Attachment class as an aggregate root and use Events to create them whenever a Document is attached. But it doesn't look like an aggregate root.
If I choose design two then Attachment class could be modeled as a value object or an entity.
Or If I use CQRS, I could go with design one and model Attachment as a query model and populate it using Events.
So, which is the right way to model this scenario? Is there any other way to model other what I have mentioned?
You might find in the long term that passing values, rather than entities, makes your code easier to manage. If attach/detach don't care about the entire document, then just pass in the bits they do care about (aka Interface Segregation Principle).
attach(DocumentId);
detach(DocumentId);
this model alone won't be sufficient as the client wants to store some meta information about the attachment, like who attached it and when it was attached.
Yes, that makes a lot of sense.
which is the right way to model this scenario?
Not enough information provided (the polite way of saying "it depends".)
Aggregate boundaries are usually discovered by looking at behaviors, rather than at structures or relationships. Is the attachment relationship just an immutable value that you can add/remove, or is it an entity with an internal state that changes over time? If you change an attachment, what other information do you need, and so on.

ViewModel classes VS defining an Exclude Bind list on the domain class

I have a model class named Server, it contains many navigation properties and properties, which I want to prevent users from binding it. So I find two approaches of doing so to avoid over-posting attacks.
The first approach is to go to each model class and define an Exclude Bind list , with all the properties and navigating properties that should not be bind by users , as follow:-
[MetadataType(typeof(TMSServer_Validation))]
[Bind(Exclude = "Technology,IT360SiteID, VirtualMachines, TMSServer1,DataCenter,OperatingSystem,Rack,ServerModel,TechnologyBackUpStatu,TechnologyRole,TechnologyStatu ")]
public partial class Server {
}
}
The second approach is to create a view model class , with only the properties that can be modified by users as follow:-
public class ServerViewModel
{
public int ServerSize { get; set; }
[Required]
public String OperatingSystem { get; set; }
public String Commnet { get; set; }
}
I find that the first approach is faster to implement , as I only need to define the Exclude list, while the second approach will require me to create view-model class for each of the domain classes. So which approach is recommended to use and why ?
Thanks
Over-posting occurs due to the default model binder not knowing which fields you actually included in the form.
It will try to map all values in the request to object. Attackers can use your form to add additional fields to
query strings/form post data and add properties as part of the request. The default model binder won't
know the difference. Your Server class will deactivate once the mapping is complete and the update is processed.
To prevent over-posting, set the annotation to include fields in the binding, or create a ViewModel like you mentioned in your code.
So which approach is recommended to use and why ?
Both annotation and ViewModel allow binding only on specified fields, but when you use ViewModel you will not bind against business objects or entities, and you will only have properties available for the input you expected.
Once the model is validated, you can then move values from the input model to the object you used in the next layer.
k. Soctt Allen has a good article about which approach is better, you can take a look at by the following link:
http://odetocode.com/blogs/scott/archive/2012/03/11/complete-guide-to-mass-assignment-in-asp-net-mvc.aspx
It's difficult to tell without seeing the rest of your code, but in general I'd say using the ViewModel is probably a better approach for the following reasons:
You separate your view from your business logic
It is safer. If in the future someone adds a property on Server and forgets the Bind-exclude, you're exposed to over-binding without knowing it. If you use the ViewModel-approach you have to explicity add new properties
Maybe this question is a little bit ambiguous because the answers are going to be based on opinions or something. But I'll try to answer it the best I can and indeed is kind of my opinion. So this is the way I see it:
First approach (Bind attribute): Is faster to implement because you only need to add on your class the name of the property you don't want to expose, but the problems comes when you want your class to exclude some properties for one feature and other properties for another feature, and you can't add fields and sometimes in MVC, the views need more fields that the ones provided by the model class and then you're gonna need to use ViewBag or something else. This approach is very handy for fast and smalls projects, but I still don't like to use ViewBag (For aesthetics reasons)
Second approach (ViewModels): Is more work, and more time but at the end (again in my opinion) you get a cleaner and ordered code and you don't need to use the ViewBag, because you can have the perfect object to send to the view depending on what this View needs, so if you a have an object with different views, again depending on the needs, they could share the same ViewModel or they could have a ViewModel for each one. If you have a solution or a big web project, this approach is going to be very handy to keep an ordered code.
Let me know.

Understanding the use of Interfaces and Base Classes

I know there are a number of post out there on Interfaces and Base classes, but I'm having a hard time getting the correct design pattern understanding.
If I were to write a reporting class, my initial though would be to create an interface with the core properties, methods, etc. that all reports will implement.
For example:
Public Interface IReportSales
Property Sales() As List(Of Sales)
Property ItemTotalSales() As Decimal
End Interface
Public Interface IReportProducts
Property Productss() As List(Of Inventory)
Property ProductsTotal() As Decimal
End Interface
Then I assume I would have a class to implement the interface:
Public Class MyReport
Implements IReportSales
Public Property Sales() As System.Collections.Generic.List(Of Decimal) Implements IReportItem.Sales
Get
Return Sales
End Get
Set(ByVal value As System.Collections.Generic.List(Of Decimal))
Items = value
End Set
End Property
Public Function ItemTotalSales() As Decimal Implements IReport.ItemTotalSales
Dim total As Decimal = 0.0
For Each item In Me.Sales
total = total + item
Next
End Function
End Class
My thought was that it should be an interface because other reports may not use "Items", this way I can implement the objects that are used for a given report class.
Am I way off? should I have still have just created a base class? My logic behind not creating a base class was that not all report classes may use "Items" so I didn't want to define them where they are not being used.
To attempt to answer you question, abstract classes are used to provide a common ancestor for related classes. An example of this in the .Net API is TextWriter. This class provides a common ancestor all various classes whose purpose is to write text in some fashion.
Interfaces are more properly used to act as adapters for different objects that don't belong in the same "family" of objects but have similar capabilities. A good example of this can be seen with the various collections in the .Net API.
For example, the List and Dictionary classes provide the ability for you to manage a collection of objects. They do not share a common ancestor by inheritance, this wouldn't make sense. In order to allow easy interop between them though, they implement some of the same interfaces.
Both classes implement IEnumerable. This cleanly allows you use objects of either type List or Dictionary as an operand for anything that requires an IEnumerable. How wonderful!
So now in your case in designing new software you want to think about how this would fit into your problem space. If you give these classes a common ancestor via inheritance of an abstract class you have to be sure that all the items that inherit from it are truly of the base type. (A StreamWriter is a TextWriter, for example). Inappropriate use of class inheritance can make your API very difficult to build and modify in the future.
Let's say you make an abstract class, ReportBase, for your repots. It may contain a few very generic methods that all reports simply must have. Perhaps it simply specifies the method Run()
You then only have one type of report you want to make so you define a concrete Report class that inherits from ReportBase. Everything is great. Then you find out you need to add several more types of reports, XReport, YReport, and ZReport for sake of example. It doesn't really matter what they are, but they work differently and have different requirements. All of the reports generate pretty HTML output and everyone is happy.
Next week your client says they want XReport and YReport to be able to output PDF documents as well. Now there are many ways to solve this, but obviously adding an OutputPdf method to your abstract class is a poor idea, as some of those reports shouldn't or can't support this behavior!
Now this is where interfaces could be useful to you. Let's say you define a few interfaces IHtmlReport and IPdfReport. Now the report classes that are supposed to support these various output types can implement those interfaces. This will then let you create a function such as CreatePdfReports(IEnumerable<IPdfReport> reports) that can take all reports that implement IPdfReport and do whatever it needs to do with them without caring what the appropriate base type is.
Hopefully this helps, I was kind of shooting from the hip here as I'm not familiar with the problem you're trying to solve.
Yes, if you don't know how many reports are not going to use Items , you can go for Abastract class.
Another good thought follows:
You can also create both Interface and Abstract class
Define Sales in Interface , create two abstract classes , one for Reports that implement both and another for Report not implementing Sales. Implement interface for both
define both method (implement sales) in first and only implement sales in second.
Give appropriate names to both Abstract classes e.g. ReportWithItemsBase or ReportWithoutItemsBase.
This way you can also achieve self explaining named base classes on deriving Report classes as well.

Adding and removing items dynamically in one View with Entity Framework and MVC

I've been at this same question in different forms now for a while (see e.g. Entity Framework and MVC 3: The relationship could not be changed because one or more of the foreign-key properties is non-nullable ), and it's still bugging me, so I thought I'd put it a little more generically:
I feel this can't be a very unusual problem:
You have an entity object (using Entity Framework), say User. The User has some simple properties such as FirstName, LastName, etc. But it also has some object property lists, take the proverbial example Emails, to make this simple. Email is often designed as a list of objects so that you can add to that object properties like Address and Type (Home, Work, etc). I'm using this as an example to keep it generic, but it could be anything, the point is, you want the user to be able to add an arbitrary number of these items. You should also be able to delete items (old address, or whatever).
Now, in a normal web page you would expect to be able to add these items in the same View. But MVC as it seems designed only makes it easy to do this if you call up an entirely new View just to add the address. (In the template for an Index View you get the "Create New" link e.g.).
I've come across a couple of examples that do something close to what I mean here:
http://haacked.com/archive/2008/10/23/model-binding-to-a-list.aspx
and
http://blog.stevensanderson.com/2010/01/28/editing-a-variable-length-list-aspnet-mvc-2-style/
The problem is, although the sample projects on these sites work fine, with mock model objects, and simply lists (not an object with a child list), it's a different thing if you actually want to do something with the posted information - in my case save to database through the Entity Framework model. To adapt these cases to that, all of a sudden I'm in a maze of intricate and definitely not DRY code... Juggling objects with AutoMapper and whatnot, and the Entity Framework won't let you save and so on (see above link if you're interested in the details).
What I want to get at is, is it really possible that this is such an uncommon thing to want to do? Update a child collection in the same View as the parent object (such as the email addresses in this case)? It seems to me it can't be uncommon at all, and there must be a standard way of handling this sort of scenario, and I'm just missing it (and no one here so far has been able to point me to a straighforward solution, perhaps because I made it too abstract with my own application examples).
So if there is a simple solution to what should in my view be a simple problem (since the design is so common), please tell me.
Have you tried updating the project at your link to Steven Anderson's blog to bind to a complex object? Create a class in models called Sack and give it a single property and see if you can get it to work.
public class Sack
{
public IEnumberable<Gift> Gifts { get; set; }
}
It only took me a minute to get it up and running as I think you intend. The improvement I would have made next would be to add an HtmlHelper extension that is essentially the same as Html.EditorFor(m => m.SomeProperty), only call it something more meaningful and have it interface with the prefix scope extensions provided in the project.
public static class HtmlExtensions
{
public static IHtmlString CollectionEditorFor<TModel, TValue>(this HtmlHelper html, Expression<Func<TModel, TValue>> expression)
{
if (/* type of expression value is not a collection */) throw new FailureToFollowTheRulesException("id10t");
// your implementation
}
}

Resources