What's the best object layout in ASP.net or at least.. what are the advantages and disadvantages of either case:
Public Class Dog
Public Breed as String
Public Type as String
Etc....
OR the use of properties and keeping variables private
Somewhat of a debate among our team about it. Just wanted to hear thoughts.
Never expose fields directly.
Use properties with private backing fields. This allows you to change implementation and to encapsulate logic around getting/setting them.
See what the Visual Basic Team have to say on this.
Also, read about the differences between fields and properties.
Related
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.
Why not getters? And how it combined with encapsulation principe? Does it safe?
Upd:
Yes, I'm about Request. Safety: I mean that anybody in code (by using listener) can do $request->attributes = null;
If you are talking about the Request and Response objects, there was a discussion about this on the Symfony developers mailing list a few days ago. I invite you to take a look at it here.
Why not getters? Not sure if there is a definitive answer to this but I think it is a decision based on personal tastes mainly.
Does it break encapsulation? Not really in my opinion for this particular case. My reasoning is that for now, no special logic is performed on the various objects that are public right now. So in the end, you would end up retrieving the object via a getter and read or modify it directly. There is not much difference with retrieving the object using a public property.
// With Getters
$parameterBag = $request->getQuery();
$parameterBag->get('key');
// With Public Properties
$parameterBag = $request->query;
$parameterBag->get('key');
Encapsulation should be enforced when you need to be sure that a property has a particular value or format. For example, say you have a class with a cost property and this property should never be negative. So if the cost property was public, it could be possible to set it to a negative value by doing something like $receipt->cost = -1;. However, if you make it private and the user of the class is only able to set it via a setter, then you could ensure that the cost is never below 0 by doing some special validation in the setter code.
In our case, we are talking about a collection object, a ParameterBag object to be precise. I don't think there are special requirements on this object but I could be wrong. So for me, it is correct to have access to those properties via public properties.
The main argument I could see in favor of the getters is that it would be more consistent with the other parts of the framework where getters are used. However, the getters could co-exist with the public properties.
To conclude, I think it is safe for this particular case. Public properties should be used only in special cases where it seems to be beneficial and where it is correct to do so.
Do you mean the Request object? Or what properties are you thinking of?
If you're worried about safety, then take a look at the Security component, use Test-Driven-Development, use tested libraries (don't invent your own authentication, cryptography and related solutions) and do code reviews.
What's the point to encapsulate what already's been encapsulated? I mean - each of this properties is a parameterBag instance with it's encapsulation.
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
}
}
I know that my this question may sound pathetic to you but as a beginner in .NET, it means a lot to me.
I just want to know that how can I utilize the concept of Abstract class, virtual class etc. in my shopping cart website. I have read the tutorial out there on internet and I saw some examples too, but those examples are so general that they dosen't fit into real world scenerio like I am searching for a shopping website. Same questions again and again comes to my mind that why to made a class only to give the declaration of methods and property.
I understand that most of you are Gurus of .NET and have ample knowlesge in it but if you could just help me out in thinking the logic behind this i'll be very greatfull.
If possible, please recommend me nice books for asp.net design patterns, from which I can learn design patterns.
Thanks in advance
Your one stop resource and guide is Head First - OOAD.
alt text http://i36.tinypic.com/8y6luo.jpg
If you can't see why to use them then don't for now. Never use a design pattern just for the sake of it.
As for their purpose however, imagine that you want to allow different types of products, but you never have something that is just a "Product" - it's always something specific like a "Book" or "Car". In that case you can put the common properties in an abstract Product class like this:
public abstract class Product
{
/* Abstract Price allows Car/Book to apply their own category discounts */
public abstract decimal Price { get; }
public string Title { get; }
public void AddReview(int userId, string reviewText)
{
/* Add review */
}
public abstract List<Product> Recommendations(int userId);
}
which your Book and Car classes can then extend.
Here is a good design patterns book with examples in C#.
C# 3.0 Design Patterns
Its not ture that for every desing you have to use Abstarct class or define virtual methods.
Basically virtual keyword is used to modify a method, property, indexer or event declaration, and allow it to be overridden in a derived class, and Abstarct keyword enables you to create classes and class members solely for the purpose of inheritance—to define features of derived, non-abstract classes
In your case you can have an abstract class called CartItem which works as a base class for all the types of items you are supposed to support in you cart. All types of items will inherit the CartItem class. You can’t directely create the instance of CartItem class but you can use this as a reference to achieve the Polymorphism.
You can define some concrete methods/properties like ItemId, ItemName, Price etc in the CartItem class which are common to all the types of items and you can also define some of the methods a virtual for which you have a default implementation but the child classes can override the implementation.
if we can access the private members through setters and getters then what is the use of private?
You need the private to enforce Encapsulation. It is one of the fundamental paradigm of Object Oriented programming to keep the implementation of something separate from the interface. This reduces the coupling between your different program parts and in the long run make it more maintainable.
Take the following example :
class toto {
private String someThing;
public String getSomething();
public void setSomething(String Something);
}
If you change above to simply put someThing public, sure you have less code, but if one day that someThing needs to change to a more complex object for some new functionality while the old code could still work fine with a string then you need to change everything. By isolating the internal representation of someThing you can evolve your system much more easily
class toto {
private ComplexSomeThing someThing;
public String getSomething(){ someThing.toString();}
public void setSomething(String something){ something = new ComplexSomeThing(something);}
public ComplexSomeThing (getComplexSomething();
public void setComplexSomething(ComplexSomething someThing);
}
There are other reasons that makes encapsulation a Good Thing (tm), this is just a silly example to illustrate the point.
EDIT
There is somewhat of a debate right now as to using protected vs private or to use concepts akin to properties in some languages (Delphi, C#) rather than getters and setters (as in Java).
Protected rather than private will allow easier changes by the clients of the code but it does expose the innards of your system more so there is a balance to strive for between usability of the API and it's maintainability. However the basic principle of encapsulation remains.
Whatever the option chosen one still needs to expose functionality that is coherent and on the same level of abstraction and hide the gory details of how this is done.
To me the debate is not to declare a jihad against private but to find a way to provide extensibility and flexibility while not breaking the coherence of the API.
Here some interesting reading about private if you want to dig further. However I must stress that before forming an opinion about private you should really master the concepts of encapsulation and polymorphism, their apparent simplicity does hides some subtle complexities.
Because the getters and setters can act as a proxy. They make it so that you can hide the actual insides of the class, and only let the outside classes access the data through methods. Allowing you to treat the inners of the class however you want.
Just because your getter/setter is named getName() and your property is called name, doesn't mean it will always be that way.
What if you wanted to change the variable to be fullName. If you directly accessed public variables, the change would break a lot of code. Instead, you can simply remap where getName() retrieves its data from.
One of my best examples of this is my own URL class, where I allow for creating and manipulating a URL. If you want to set the scheme, you can get $obj->setScheme(). However, you don't know whether I am manually making the string every time you change the URL, whether I am storing them as separate parts. This gives me flexibility as I can store your data however I want to.
Furthermore, I can preform manipulations on the data before storing it. In my URL class, I assume that all schemes and host names are lowercase. I can standardize this by converting all strings saved via setHost() to lowercase, and then storing them. If I used a public variable, you would have to assume that the client that put the data in was correctly storing it.
They can also validate information that is being passed in to make sure that it is valid data, and cause an error if it isn't.
No one forces you to put in getters and setters for every variable. Indeed, blindly using private members + dummy getters & setters for every variable is pointless, even though many "object oriented encapsulation" tutorials do this all the time for some reason. For one thing, such encapsulation is no encapsulation from concurrency viewpoint.
I think what you really want to understand is why we use public properties with private backing fields, instead of just using public fields. There are several questions on SO like this; here's one:
What is the difference between a Field and a Property in C#?
I think you have good answers so far (information hiding and all that). Just want to add a suggestion about using setters.
As you mentioned using accessors makes private variables a bit pointless and in some environments performance consequence of using getters and setters just makes it worthless.
On the other hand if you don't have such concerns, I think using getters isn't so bad, but you should think twice before using setters. They make your object mutable which is especially hard to maintain in concurrent environments.