Naming Conventions Regarding View Models to Avoid Long Names - naming-conventions

I am creating view models for each screen in my ASP.NET MVC application. I put all of the logic for creating a view model in a builder class. Usually, there is special logic for converting the data objects into view models, including aggregating, filtering, and sorting. Each builder is passed a dependency set, which is an object containing properties for each dependency (repositories, other builders, etc.).
The problem is that my names are getting really long. A dependency set will usually have a name composed this way:
view-model-name+Builder+DependencySet
View models usually have names composed of where you are currently and the children. For instance, my system has categorized provider definitions. So, in order to show the provider definitions under a category, I have a view model called:
CategoryProviderDefinitionListViewModel
It will look something like this:
public sealed class CategoryProviderDefinitionListViewModel
{
public long CategoryId { get; set; }
public string CategoryName { get; set; }
public ProviderDefinitionViewModel[] ProviderDefinitions { get; set; }
}
So, my builder is called
CategoryProviderDefinitionListViewModelBuilder
So, my dependency set is called
CategoryProviderDefinitionListViewModelBuilderDependencySet
That barely fits across the screen. My poor fingers are tired. Furthermore, some screens almost show the same data, so their view model names are almost the same. When I am looking through my folder, it becomes really hard to find the specific view model classes I am looking for.
Ideally, I could group my view model classes together, associating them with the view(s) where they are used. It would be nice to avoid collisions and to make names as short as possible, while keeping them meaningful. Has anyone found a naming convention/folder organization that works well in this scenario?

I've been using the "ViewModel" suffix consistently for quite a while and to be honest, sometimes I find it redundant. I think just grouping all these classes in a different namespace should be sufficient.
My understanding is that this convention has been adopted to avoid collision between domain model and view model classes (eg Product vs ProductViewModel). However, since your view models are named after the screens, it is very unlikely that you would have a class with the same name in your domain model. In fact, it should be really questionable why you have such a class in your domain model! :)
So, if you name your view model something like ViewProduct (to allow the user to view/edit a product), you don't need to call it ViewProductViewModel. See where I'm going?
Consequently, your Builder class could simply be called ViewProductBuilder instead of ViewProductViewModelBuilder.
Regarding your dependency set, I'm not sure what is your rationale behind this. But to me it looks unnecessary. If your builder has dependencies to other objects, you'll need to inject dependencies in the constructor of builder, instead of encapsulating them into another class (DependencySet) and then passing them around.
If you find your builder dependent on too may things and this is what you are trying to hide behind DependencySet, then it could be the indication of a design smell somewhere else. If classes and their dependencies are designed in a proper object-oriented fashion, behavior should be distributed very nicely between various classes and no class should have dependency on too many other things. So, hiding those N dependencies under 1 class (DependencySet) is merely treating the symptoms not the problem itself.
Hope this help :)

I prefer post-fixing my ViewModel names with "DTO". (Where DTO stands for Data Transfer Object, ie. an object that does nothing but contain information)
This is not only to avoid long names. But it also makes me able to use the same names like User, but it will be called UserDTO, indicating to me that I am working with an object that is part of my ViewModel, and thus avoid naming collisions.

I tend to agree with Mosh.
The ViewModel suffix becomes redundant the majority of the time and while sometimes you might have matching class names, it is quite easy to manage as they are confined to your ViewModel namespace. I also find that using the odd namespace alias hurts my brain less than suffixing my class names across the board.
Of course in your presenter/controller you may have naming collisions, but that could be a sign that you need to name your Views more appropriately, e.g. not User but ViewUser/EditUser.
For search results and lists I find it is best to break out something such as IEnumerable instead of IEnumerable. The latter often means you end up with a User view model class that becomes a dumping ground for all User properties that may or may not be needed across the project. This is one of the big things to watch out for and if you find yourself with a class like this, you've gone of the track somewhere. Keep your views and view models descriptive and specific. If you have many similar view models the issue is probably a bigger design problem; some designers have a tendency to reinvent rather than reuse existing graphical structures.

Related

Class diagram - multiple classes uses same class

I am designing a class diagram for an assignment. In this design, I use a separate class called Currency, to define currency values and their functionality. there are at least four other classes have to use this Currency class.
How can I show it in the class diagram ? I mean, do I need to draw relationships (connecting lines) from the Currency class to all the others ?
Is there a better way ?
What am I doing wrong here ?
There is nothing wrong and a reusability of a class is valuable. Actually that's a standard situation.
If you use this class in another class as an attribute you have two options to depict that:
draw an association relationship (line) from the class using to the class that is used.
put the attribute in a proper compartment of a class that is using and as a type of an attribute (after a colon) put the name of the used class.
The benefit of the first approach is that you immediately see the dependency between the classes.
If you use a class but not directly as an attribute type you use other relationship types that suit best to the situation you want to describe.
As I imagine one of your concerns is that you'll have a lot of relationships pointing to your class (in your case Currency). Don't worry about that. You don't have to put everything in a single diagram. Put a full specification of your class on one diagram with those relationships where it uses something else and then put only the class box with a name (without any compartment) on diagrams defining those elements that use your class. It will make your model readable. And with a support of some CASE tool you will be able to see all relationship and dependencies of this class anyway. By the way that's how the UML specification is written. Look for example how Namespace is used in the diagrams there (and many others as well).
Of course I'm not suggesting creating one diagram per one element to define it. No. Collect them in logical Packages (hey - that's exactly what Packages are for!) and make a class diagram per Package. If the Package becomes too large - you might need to split it into smaller subpackages.
For Currency your Package would be probably something like Utils. It can also contain other elements like Date, Address etc. Note - these are typical examples, probably every analyst/designer/programmer sooner or later has to cope with those elements. If you build them well, you'll be really able to reuse them in future applications as well.
One last thought. While you build "package based" Class diagram you might also need a diagram that shows just specific parts coming from several Packages to clarify some bit of your system/business/whatsoever. This is also absolutely fine. Again a benefit of CASE tool here is that it keeps consistency in your model.

Worker vs data class

I have a data class which encapsulates relevant data items in it. Those data items are set and get by users one by one when needed.
My confusion about the design has to do with which object should be responsible for handling the update of multiple properties of that data object. Sometimes an update operation will be performed which affects many properties at once.
So, which class should have the update() method?. Is it the data class itself or another manager class ? The update() method requires data exchange with many different objects, so I don't want to make it a member of the data class because I believe it should know nothing about the other objects required for update. I want the data class to be only a data-structure. Am I thinking wrong? What would be the right approach?
My code:
class RefData
{
Matrix mX;
Vector mV;
int mA;
bool mB;
getX();
setB();
update(); // which affects almost any member attributes in the class, but requires many relations with many different classes, which makes this class dependant on them.
}
or,
class RefDataUpdater
{
update(RefData*); // something like this ?
}
There is this really great section in the book Clean Code, by Robert C. Martin, that speaks directly to this issue.
And the answer is it depends. It depends on what you are trying to accomplish in your design--and
if you might have more than one data-object that exhibit similar behaviors.
First, your data class could be considered a Data Transfer Object (DTO). As such, its ideal form is simply a class without any public methods--only public properties -- basically a data structure. It will not encapsulate any behavior, it simply groups together related data. Since other objects manipulate these data objects, if you were to add a property to the data object, you'd need to change all the other objects that have functions that now need to access that new property. However, on the flip side, if you added a new function to a manager class, you need to make zero changes to the data object class.
So, I think often you want to think about how many data objects might have an update function that relates directly to the properties of that class. If you have 5 classes that contain 3-4 properties but all have an update function, then I'd lean toward having the update function be part of the "data-class" (which is more of an OO-design). But, if you have one data-class in which it is likely to have properties added to it in the future, then I'd lean toward the DTO design (object as a data structure)--which is more procedural (requiring other functions to manipulate it) but still can be part of an otherwise Object Oriented architecture.
All this being said, as Robert Martin points out in the book:
There are ways around this that are well known to experienced
object-oriented designers: VISITOR, or dual-dispatch, for example.
But these techniques carry costs of their own and generally return the
structure to that of a procedural program.
Now, in the code you show, you have properties with types of Vector, and Matrix, which are probably more complex types than a simple DTO would contain, so you may want to think about what those represent and whether they could be moved to separate classes--with different functions to manipulate--as you typically would not expose a Matrix or a Vector directly as a property, but encapsulate them.
As already written, it depends, but I'd probably go with an external support class that handles the update.
For once, I'd like to know why you'd use such a method? I believe it's safe to assume that the class doesn't only call setter methods for a list of parameters it receives, but I'll consider this case as well
1) the trivial updater method
In this case I mean something like this:
public update(a, b, c)
{
setA(a);
setB(b);
setC(c);
}
In this case I'd probably not use such a method at all, I'd either define a macro for it or I'd call the setter themselves. But if it must be a method, then I'd place it inside the data class.
2) the complex updater method
The method in this case doesn't only contain calls to setters, but it also contains logic. If the logic is some sort of simple property update logic I'd try to put that logic inside the setters (that's what they are for in the first place), but if the logic involves multiple properties I'd put this logic inside an external supporting class (or a business logic class if any appropriate already there) since it's not a great idea having logic reside inside data classes.
Developing clear code that can be easily understood is very important and it's my belief that by putting logic of any kind (except for say setter logic) inside data classes won't help you achieving that.
Edit
I just though I'd add something else. Where to put such methods also depend upon your class and what purpose it fulfills. If we're talking for instance about Business/Domain Object classes, and we're not using an Anemic Domain Model these classes are allowed (and should contain) behavior/logic.
On the other hand, if this data class is say an Entity (persistence objects) which is not used in the Domain Model as well (complex Domain Model) I would strongly advice against placing logic inside them. The same goes for data classes which "feel" like pure data objects (more like structs), don't pollute them, keep the logic outside.
I guess like everywhere in software, there's no silver bullet and the right answer is: it depends (upon the classes, what this update method is doing, what's the architecture behind the application and other application specific considerations).

Design pattern advice: Using an array of custom objects as a singleton

After a lot of studying, I am starting to code my first app.
In my code I have a class called "Measurement". I want to implement an array of Measurements. This array of Measurements needs to be accessible across multiple view controllers, so I have created a custom class called "MeasurementsArray" for the array, and made it into a singleton.
I have done this, and the code works as expected. But now that I have it working, I want to make sure that I have easy to understand code, and that I am following conventional objective-c design patterns.
If it weren't for fact that I need the array of Measurements to be a singleton, it would seem that this array belongs inside the "Measurement" class as a class method. But my understanding is that there can be only one instance of a class when it is a singleton.
But somehow, having a separate class named "MeasurmentsArray" seems a little hacky to me.
My question:
Am I approaching this the right way, or am I missing something?
If I do need the split off the array of Measurements to a separate class in order to have it be a singleton, does "MeasurementsArray" seem like an appropriate class name? If not, please provide a naming convention you would use for this type of situation.
Edit: After some inital answers, some clarification regarding the function of the app might help.
It is a fitness application that records, saves and tracks body fat percentage and body weight. Every time the user records his body fat and weight, it becomes an instance of the class "Measurement". The array of Measurements is needed in order to track changes in weight and body fat over time. A singleton is needed because multiple view controllers need access to the array.
A singleton is needed because multiple
view controllers need access to the
array.
There are other, better ways to share data between objects than to rely on a singleton.
View controllers are usually created either by the application delegate or by another view controller. The application's data model (in this case, that's your measurements array) is often also created ether by the application delegate. So when the app delegate creates a view controller, it can also give that controller a pointer to the data model. If that controller creates any view controllers, it can likewise share its pointer to the data model.
Passing the data model along from app delegate to view controller and from one view controller to the next makes your code easier to maintain, test, reconfigure, and reuse because it avoids depending on some predetermined, globally accessibly object.
Having a singleton at all may be a wrong move. There are times that a singleton is appropriate, but there's usually a better choice.
It sounds like you may already be implementing something resembling the Model-View-Controller pattern, which would be appropriate. In this context, this array of measurements is part of your model, and it may make sense for it to be a separate class, but there's likely no need for it to be a singleton.
The name MeasurementsArray is implementation-specific. I would be more inclined to call it just Measurements or to give it a name reflecting what the measurements are measuring.
In fact I wonder about the name of your Measurement class. What is it measuring? What does it actually represent?
If you post some code, we might be able to provide more specific ideas.
Based on your update and a bit of thinking, you might want to think about The Repository Pattern. Rather than having your controllers hold the array, they have access to the repository from which they can get it.
My thinking here is that your array of measurements might be supplied by a MeasurementRepository and that while now the data might be a single simple array that the repository just holds, it might evolve to something that is stored in a database per user and with variation over time, so that your repository supplies more complex access.
Rather than having this repository be a singleton (though that is certainly sometimes done), it might better be just created once and then injected into everything that needs it. See http://en.wikipedia.org/wiki/Dependency_injection and Uncle Bob's blog
I feel that a separate class is probably overkill unless it has several methods of its own, in which case it might be justified. This problem may just be an artefact of your app's structure not (yet) being well defined. Is data going to be persistent across sessions? If so, will there be a "manager" class on which you could put a property to retrieve the array; something like allMeasurements on the MeasurementStore class? Another option would be to store the array in your app delegate.
I find that if I continue working on an app, it becomes obvious how I should structure it.
Edit: To elaborate, there's nothing "wrong" with your approach; there's probably just nicer ways to do it.
If I understand you correctly, the measurements array represents past measurements of a specific user.
If that is the case- you're not looking for a singleton at all.
remember that a singleton is a single value PER APPLICATION, and what you're looking for here is a single value PER USER.
Don Roby is absolutely right- Measurements is probably a property of the User class. for example (I'm using c# notation, but you get the hang of it...):
public class User
{
public string Name {get; set;}
public int Id {get; set;}
public Measurement[] Measurements {get; set;} //one array per-user...
}

Pattern for polymorphic views

Imagine I have a abstract "FriendEvent" model which has several different concrete implementations, ie. FriendPosted, FriendCommented, FriendUploadedPhoto etc. They should all be rendered in my view of FriendEvents, but should be visually distinct from each other (e.g. FriendUploadPhoto should include a thumbnail).
What is a good object oriented pattern to achieve this?
I'm interested to learn if there's an alternative to switching on the concrete class of the model in the view code. That somehow feels wrong because it uses conditional logic where I believe it should be possible to rely on polymorphism, but I have a hard time thinking up a better idea. Are there any established patterns to deal with this?
(I obviously don't want to implement the view logic in the model, since that would be mixing the responsibilities, and since I may want to have different views for each model)
To clarify: How to model the different event type in the model layer is not the problem. There are several well known OO solutions. The question concerns the view code which is responsible for presenting the models visually. I imagine I have an EventView class which deals with showing an event (model). The question is: How to implement this class without a switch block that selects a different code path depending on the concrete type of Event is is rendering.
Seems like you have some DoubleDispatch concerns going on here.
If I understand you correctly, you are trying to avoid mixing Model and View. Each Event class could have
HtmlString getHtmlView() { /* code */ }
but then all events have view knowledge and each time we add a new kind of view we add a new getXXXView() method. I agree that this sees unpleasant.
So we could increase the separation of concerns by having all events offer
HtmlViewMaker getHtmlMaker { return new MyKindOfViwer(this); }
Now at least we've got the View code out into its own class. Yes we may well need to write special case code for each/many kinds of events, but that's inevitable. Our first problem is where to put that special code - and that we've an answer for.
However we still have a problem: each new kind of View needs a new getXxxMaker method. So we start to look at more complex Factories and the use of Generics and Templates and so on.
For me, I would just use the partial-view concept. The base class is dealt with by the primary view, and that primary view requires a partial view that takes care of the needs of displaying the concrete class.

How to prevent multiple classes for the same business object?

A lot of the time I will have a Business object that has a property for a user index or a set of indexes for some data. When I display this object in a form or some other view I need the users full name or some of the other properties of the data. Usually I create another class myObjectView or something similar. What is the best way to handle this case?
To further clarify:
If I had a class an issue tracker and my class for an issue has IxCreatedByUser as a property and a collection of IxAttachment values (indexes for attachment records). When I display this on a web page I want to show John Doe instead of the IxCreatedByUser and I want to show a link to the Attachment and the file name on the page. So usually I create a new class with a Collection of Attachment objects and a CreatedByUserFullName property or something of that nature. It just feels wrong creating this second class to display data on a page. Perhaps I am wrong?
The façade pattern.
I think your approach, creating a façade pattern to abstract the complexities with multiple datasources is often appropriate, and will make your code easy to understand.
Care should be taken to create too many layers of abstractions, because the level of indirection will ruin the initial attempt at making the code easier to read. Especially, if you feel you just write classes to match what you've done in other places. For intance if you have a myLoanView, doesn't necessarily you need to create a myView for every single dialogue in the system. Take 10-steps back from the code, and maybe make a façade which is a reusable and intuitive abstraction, you can use in several places.
Feel free to elaborate on the exact nature of your challenge.
One key principle is that each of your classes should have a defined purpose. If the purpose of your "Business object" class is to expose relevant data related to the business object, it may be entirely reasonable to create a property on the class that delegates the request for the lookup description to the related class that is responsible for that information. Any formatting that is specific to your class would be done in the property.
Here's some guidelines to help you with deciding how to handle this (pretty common, IMO) pattern:
If you all you need is a quickie link to a lookup table that does not change often (e.g. a table of addresses that links to a table of states and/or countries), you can keep a lazy-loaded, static copy of the lookup table.
If you have a really big class that would take a lot of joins or subqueries to load just for display purposes, you probably want to make a "view" or "info" class for display purposes like you've described above. Just make sure the XInfo class (for displaying) loads significantly faster than the X class (for editing). This is a situation where using a view on the database side may be a very good idea.