Difference between member variable and member element?

There are situations when I declare member variables at the top of my class and then declare a property to access or set this member variable, but I ask myself if the property is needed if it will be available only for the variable, and set inside the class and not elsewhere, so what is the advantage of using a property to access and set a member variable instead of just doing it directly with the member variable itself. Here is an example:

public class Car { int speed; //Is this sufficient enough if Car will only set and get it. public Car(int initialSpeed) { speed = initialSpeed; } //Is this actually necessary, is it only for setting and getting the member //variable or does it add some benefit to it, such as caching and if so, //how does caching work with properties. public int Speed { get{return speed;} set{speed = value;} } //Which is better? public void MultiplySpeed(int multiply) { speed = speed * multiply; //Line 1 this.Speed = this.Speed * multiply; //Line 2 //Change speed value many times speed = speed + speed + speed; speed = speed * speed; speed = speed / 3; speed = speed - 4; } } 

In the above example, if I don't have the Speed ​​property to set and get a variable speed, and I decide to change the speed of int to int spd, I will have to change the speed to spd wherever it is used, if I use a property like Speed To set and get the speed, I just need to change the speed to spd in the get and set properties, so in my MutilplySpeed ​​method, as above. Speed ​​= this.Speed ​​+ this.Speed ​​+ this.Speed ​​will not break.

+16
c # oop
Feb 17 '10 at 17:41
source share
8 answers

If the variable is private , I often do not create a property for it. If it is in any way exposed to an external type, I always expose it through the property for various reasons:

  • It may not be necessary today, but if it is needed later, it will be a breaking change
  • Working with data only works on properties, not on fields (I think not a big user of data binding).
  • It allows you to insert validations, logging, breakpoints when accessing a value

In addition, if a field is opened through a property, I always get it through a property, even inside a class.

Update
In response to your updated code samples: here are a few things you can consider around code design.

  • Readability versus Speed
  • atomicity
  • Other side effects

One typical tip (which I find very good) is to "write for clarity, a performance test." This means that when you write your code, your first problem is whether it is clear what the code does when viewing it. This is often (but not always) more important than raw code speed. Optimize recording speed when you set where you get it. Access to the property will be slightly slower than reading the field directly, but in most cases the difference will be insignificant (if at all measurable).

Atomicity can be a problem. Given your sample code, we have a speed field that is open through the speed property. If the MultiplySpeed method needs to perform several updates for a value, these intermediate values ​​will be available through the speed property at different times while the calculation continues. This is true whether you are updating the field directly or through a property. In such cases, it might be better to first put the value in a local variable, use it for calculations, and assign the value to this variable when it is done.

Finally, other side effects. Perhaps a change in speed should result in an event (e.g. SpeedChanged ). In such cases, it is also probably a good idea not to update until the calculation is complete.

I like to think of property as a contract, and the field as implementation. Anyone (with the exception of a kernel of my type) that needs cost should use a contract. Based on the implementation should be done only if there are sufficient grounds for circumventing the contract.

And yes, if you encapsulate access to a field in a property, naturally changing the field name will require fewer updates (and perhaps also the field name becomes less important).

I hope this makes sense, and not too much from the topic;)

+22
Feb 17 '10 at 17:45
source share

I agree with Frederick's answer. One thing that makes him a little less work to follow his advice is to use automatic properties. These are simply properties that automatically generate the standard getter / setter logic. You don't get any validation, but you can always replace the automatic property with a standard one later. This replacement is not a violation of the changes.

Here I replaced the Speed ​​property in your example with an automatic property. Note that the member variable disappears and your class must access it through the property.

 public class Car { public Car(int initialSpeed) { Speed = initialSpeed; } public int Speed { get; set; } public void MultiplySpeed(int multiply) { Speed *= multiply; } } 

You can also use another flavor called "get with private set". This means that the getter is public, but the setter is private. You define it as follows:

  public int Speed { get; private set; } 

Regarding your question about this. prefix this. It usually doesn't matter. The only time this is important is when you define a method parameter or local variable with the same name as the member variable. You can then use this to access the member variable.

+8
Feb 17 '10 at 18:13
source share

Things like checking can be covered in one place. The member is encapsulated and you want to worry about validation and other things from the rest of your class.

In your current scenario, this does not really matter, but when you need to change a variable or add behavior, it is easier to use properties because you only have one place where you need to change it.

+1
Feb 17 '10 at 17:45
source share

it does not add caching, but allows a consistent interface.

Imagine that you needed to speed up speed by adding a constant value to it in the future. using a member variable would be difficult when the property allows this manipulation.

Also inside the class, you must again access the property for consistency (imagine the scenario described above when you had a class that accessed a member variable directly).

+1
Feb 17 2018-10-17
source share

The only true reason I know is access to the field from outside the assembly. In this case, if you want to add light functionality to this field (maybe set the Dirty flag or confirm the change), you should change it to a property that changes the way it is viewed by the calling assembly, which will also require rebuilding. In very rare cases, you You may find that you have no control over this assembly, then you have a problem.

Don't let OO fans let you know that it’s philosophically wrong to use public fields, although I can agree that auto-properties make the argument somewhat controversial.

+1
Feb 17 '10 at 17:51
source share

The fact is that there is not a big difference between a publicly declared field and a public property with a private backup storage, if there is no additional logic. However, it is believed that you can still use properties.

And before everyone tells me about extensibility, remember that if you need to add functionality, you can save a name with this property and enter a new name for the backup storage so that it does not change.

+1
Feb 17 '10 at 18:22
source share

One thing you forgot to mention is that properties will help you when you extend your class. If your class is correctly designed, your variables inside the base class must be private . Without the properties of the public properties that are. You would not have access to these private variables from the extended class. We are talking about public and private, and I do not include protection for some reason :).

Just a few notes worth mentioning:

  • Class Aide Properties
  • properties for me make the code more readable (in addition to this.privateVariable verson PublicPropertyVariableName)
  • properties can provide only read, private sets, public, etc. (much more readable for other programmers). Consider the case when the identifier requires public access, but a private set
  • Personally, I get too many get / sets, it seems, complicates the code, makes the code less readable, too much unnecessary syntax
  • Inheriting / extending to an extended class does not allow private variables to be inherited; properties are the answer. (again, the mention of protection here is a completely different story).
  • For me, even if the class has a private variable, my class methods still use the property to access or use this private variable
  • Don't forget about validation, it makes it easier to verify the readability.

These are just some common things (my 2 cents, although most of them).

0
Feb 17 '10 at 17:45
source share

In my opinion, the design of the language is broken. There should not be two ways to do things with so much semantic overlap. Properties / Fields should have easily provided the benefits of any approach, depending on how they are used. If a program makes minimal use of Property properties, they should act just like fields. In addition, it should not be necessary to declare an empty get; and install; methods in this case. The differences seem artificial to me.

This is a great language; and pretty clean for the most part. This does not mean that the next time it should not be improved.

0
Jul 04 '11 at 5:13
source share



All Articles