Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Difference between member variable and member property?

Tags:

c#

oop

There are situations where I declare member variables at the top of my class and then also declare a property to access or set that member variable, but I ask myself if the property is necessary if it variable is only going to be accessed and set from within the class and no where else, so what is the advantage of using a property to access and set a member variable instead of just doing it directly to 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, if I don't have the property Speed to set and get the variable speed, and I decide to change int speed to int spd, I will have to change speed to spd everywhere it is used, however, if I use a property such as Speed to set and get speed, I will just have to change speed to spd in the get and set of the property, so in my MutilplySpeed method, stuff like above this.Speed = this.Speed + this.Speed + this.Speed will not break.

like image 428
Xaisoft Avatar asked Feb 17 '10 17:02

Xaisoft


People also ask

What is the difference between member and variable?

A local variable is the variable you declare in a function. Its lifespan is on that Function only. A member variable is the variable you declare in a class definition. Its lifespan is inside that class only.It is Global Variable.It can be access by any function inside that same class.

What is a member variable example?

You cannot declare more than one member variable with the same name in the same class. However, a member variable and a method can have the same name. For example, the following code is legal: class IntegerClass { int anInteger; int anInteger() { // a method with the same name as a member variable . . . } }

What is the difference between property and variable in Javascript?

A property is usually associated with a javascript object. var obj = { name: 'test', --> property getName: function(){ --> property return this.name } }; In contrary variables are used inside functions and even outside of them.


2 Answers

If the variable is private , I will often not create a property for it. If it is, in any way, exposed outside the type, I always expose it through a property for different reasons:

  • It may not be necessary today, but if it becomes necessary later it's a breaking change
  • Databinding works only on properties, not on fields (I think, not a big databinding user)
  • It allows to insert validations, logging, breakpoints when accessing the value

Also, if the field is exposed through a property, I always access it through the property, even within the class.

Update
In response to your updated code samples: there are a number of things to consider around the code design here.

  • Readability vs. Speed
  • "Atomicity"
  • Other side effects

One typical piece of advice (that I find very good) is "write for clarity, test for performance". That means that when you write your code, your first concern should be whether it is clear what the code does when looking at it. This is often (but not always) more important than the raw speed of the code. Write speed optimizations when you have established where you gain it. Accessing a property will be a tad slower than reading the field directly, but in most cases, the difference will be negligible (if at all measurable).

Atomicity may be an issue. Given your code sample, we have the field speed, that is publicly exposed through the property Speed. If the method MultiplySpeed needs to perform several updates to the value, those intermediate values will be available through the Speed property at different times while the calculation is ongoing. This is true regardless of whether you update the field directly or through the property. In cases like this it is perhaps better to first put the value into a local variable, use that for the calculations and assign the value of that variable back to the property when done.

Lastly, other side effects. It could be that changing the value of Speed should raise an event (such as SpeedChanged). In cases like that, it is also probably a good idea not to make the update until the calculation is done.

I like to think about the property as a contract and the field as implementation. Anybody (except for the core of my type) that needs the value should use the contract. Relying on the implementation should be done only if there are good reasons to bypass the contract.

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

I hope that makes sense, and is not too much off topic ;)

like image 79
Fredrik Mörk Avatar answered Oct 19 '22 16:10

Fredrik Mörk


I agree with Frederik's answer. One thing that makes it slightly less work to follow his advice is to use automatic properties. Those are just 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 breaking change.

Here I've replaced the Speed property in your example with an automatic property. Notice 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 flavour called "get with private set". This means that the getter is public, but the setter is private. You define it like this:

    public int Speed { get; private set; }

As for your question about the this. prefix, it's usually irrelevant. The only time it matters is when you've defined a method parameter or local variable with the same name as a member variable. Then you can use this to access the member variable.

like image 28
Don Kirkby Avatar answered Oct 19 '22 15:10

Don Kirkby