开发者

Property Getters vs Get Methods when using a MVC or similar pattern?

Not that it really matters but I want to follow the best practices. When creating View Models is it considered best practice to use property getters or methods? e.g

public class ProductViewModel
{
    private readonly Product _product;

    public ProductViewModel(Product p)
    {
        _product = p;
    }

    public string Price
    {
        get { return string.Format("${0}" _product.Price.ToString("N2") };
    }
}

Considering that this is a simple example is it better to use a method?

public string GetPrice()
{
    return s开发者_如何学编程tring.Format("${0}" _product.Price.ToString("N2");
}

What are the pros / cons between the two?


If you're using MVVM, then you're using databinding. Databinding binds to properties, not methods. (See the docs for the Binding.Path property -- there's not a single occurrence of the word "method" on that page. It's all about properties.)

So there's no contest. Use properties, because that's what the binding system supports.


I would lean towards a property and away from a function. The point of a view model is to present the model in a fashion suitable for displaying in a view. Usually the view and the view model talk to one another through binding, often done in XAML.

By using a method instead of a property you make wiring up the view and the view model less turn key.

Say you end up needing that price elsewhere, keeping it formatted in the old code but without the formatting in the new code. With a method you'd now need another method, or a property to get the price. With the property, you could just apply a StringFormat to the first binding.

<!-- Old code -->
<TextBlock Text="{Binding Price}" />

<!-- New code -->
<TextBlock Text="{Binding Price, StringFormat=${0:N2}}" />
<awesome:MoneyUpDown Value="{Binding Price}" />


If you are using MVVM, chances are you want INotifyPropertyChanged support, in which case properties are the way to go. There are a number of frameworks (e.g. Caliburn.Micro) that help you minimize repetitive crud code, like wiring up the notifications.

The original question was about the MVVM pattern. With plain MVC (without data binding), the answer is not as clear cut. Personally, I would still use a property over a method when getting simple data when no extra calculation or data access is required.


one caveat with the first method is that you would have to implement a second property to be able to get the price without formatting

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜