Method Vs Property
I'm a newbie to .NET. I have a class called Project, a project can have multiple forecasts.Now If I want to check if the projects has any forecasts or not should I use a readonly boolean property called HasForecast() or s开发者_开发百科hould I use a method named HasForecast() which basically returns a boolean value.From framework design guidelines I came to know that methods should be used when the operation is complex,since here I'm retrieving the value of forecasts from DB should I consider method, or since it is a logical data member should I use a property.If I use a property can I call a method in DBLayer from its getter.Please explain
Regards, Ravi
Properties should be very light weight that act and feel like fields. If you needs to access a database then you should use a method.
See MSDN here: http://msdn.microsoft.com/en-us/library/bzwdh01d(VS.71).aspx
Properties vs. Methods
Class library designers often must decide between implementing a class member as a property or a method. In general, methods represent actions and properties represent data. Use the following guidelines to help you choose between these options.
Use a property when
- The member is a logical data member. In the following member declarations, Name is a property because it is a logical member of the class.
Use a method when:
- The operation is a conversion, such as Object.ToString.
- The operation is expensive enough that you want to communicate to the user that they should consider caching the result.
- Obtaining a property value using the get accessor would have an observable side effect.
- Calling the member twice in succession produces different results.
- The order of execution is important. Note that a type's properties should be able to be set and retrieved in any order.
- The member is static but returns a value that can be changed.
- The member returns an array. Properties that return arrays can be very misleading. Usually it is necessary to return a copy of the internal array so that the user cannot change internal state. This, coupled with the fact that a user can easily assume it is an indexed property, leads to inefficient code.
If that method call is going to initiate a database query I would make it a method and perhaps change the name as well to make it obvious that this is not simply returning the value of a field.
A good rule that I learned is that if there is a chance that the property isn't guaranteed to return immediately* or there is even a remote chance that an exception could be thrown then use a method.
*For variable definitions of immediately, it's fine to have logic in a property, but keep it as short as possible.
Isn't that just all about convention?
I mean, aren't properties simply syntaxic sugar to normal getters and setters at the end of the day?
精彩评论