开发者

The case against automatic properties [duplicate]

开发者 https://www.devze.com 2023-01-15 14:37 出处:网络
This question already has answers here: Closed 12 years ago. Possible Duplicate: C# 3.0 Auto-Properties - useful or not?
This question already has answers here: Closed 12 years ago.

Possible Duplicate:

C# 3.0 Auto-Properties - useful or not?

My boss and I regularly argue about the benefits and disadvantages of using automatic properties.

public string Name { get; set; }

vs

private string name;

public string Name
{
    get { return this.name; }
    set { this.name = value; }
}

For

I am strongly in favor of using 开发者_如何学Pythonthem because I have to write less code, I find it easier to understand the class when all the fields are coded that way and just saves me a lot of time in the long run (mostly because I write a bit less code each time).

Against

He argues that they break some programming principle because the fields should reflect the state of the object and by using a property instead of a field with a property to access it, I lose that information while debugging. (Boss if you read this and it's not exactly what you mean, feel free to comment ;))

What's everyone's take on this matter?

NOTE: I have looked at the duplicate and it doesn't talk about the against points which is the point of this question. It's just people saying "I love them"/"I don't care".


How do you give up that information? The property reflects the state of the object instead of the field - is it that big a difference?

The only time I want to have it backed by a field is if I need to do additional logic when setting it (ie: validation) or when I want to enforce a design pattern such as caching the value or singleton etc.


Perhaps my understanding of Auto implemented properties is flawed, but if the documentation is to be bekieved, it is still backed by a property. Auto-implemented properties are a shortcut for writing boilerplate code only. The complier expands the Auto property upon compiliation, right? If you look at the IL it should show you a backing field. I believe the backing field is the property name preceded with an underscore.

So, the field does reflect the state of the object AND you don't have to write as much code. The field is just hidden in the IDE, although you should still be able to access it using reflection, if you wanted to.


His argument is wrong (so perhaps you've mis-quoted it).

Anyway, it doesn't matter. You are exaggerating how much time you save. And with most real-world applications, you'll start off with an automatic property and eventually change it to be backed by a real field for various purposes. It's really a useless argument.

0

精彩评论

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

关注公众号