Accessing Class Properties within the Class - use private or public properties.  
Author Message
Tryst





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

Hi all,

If I have a class that declares private variables which are then accessed via their relating public properties, which ones (public or private) do I use when using them within the Class in which they are created. For example...

public class SiteMember : Person
{
private string ID;

// Constructor(s)
public SiteMember(string id)
{
m_ID = id; /* I have use the Public access here, but should I use the private */
}

// Public property
public string m_ID
{
get { return ID; }
set { ID = value; }
}
}

I just need clarify on whats the best practice really.

Thanks. Tryst



Visual C#3  
 
 
louthy





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

You have it slightly wrong. The private one should be named m_ID, as that's an internal member.

public class SiteMember : Person
{
private string mID;

// Constructor(s)
public SiteMember(string id)
{
mID = id;

}

// Public property
public string ID
{
get { return mID; }
set { mID = value; }
}
}

It doesn't matter too much whether you use the public or private members internally, just be consistent with whatever you pick. However if your public property does extra work other than returning the private member, then you should use the public property.


 
 
ShellShock





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

Actually the Microsoft convention is to prefix private fields with an underscore, and to use Pascal casing, e.g., "_id", and "_myId". This is clear if you view any Microsoft types in the de****. The "m_" prefix is a left over from MFC.


 
 
louthy





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

Agreed, all the hungarian notation is ugly as hell.  I assumed he had an internal coding style that he had to stick with.

Personally, I prefer not to use underscores either, as I find them to be pretty ugly.  I'm a firm believer that if you can't work out where your variables came from then your code is too complex and should be refactored.

public class SiteMember : Person
{
        private string id;

        // Constructor(s)
        public SiteMember(string id)
        {
                this.id = id;
        }

        // Public property
        public string Id
        {
            get { return id; }
            set { id = value; }
        }
}


 
 
PhilipDaniels





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

My rule is to always use the property accessors, that way if I give some "intelligence" to the "field" via it's property then I know the "intelligence" will be applied irrespectively of the context in which the data is used. Of course the field identifier must be used with the accessors.

My inclination is to provide accessors for ALL class scope variables, even if the property or one its its accessors is marked private eg

public string NickName {get{return this.theNickName:} private set{this.theNickName=value:}

As for naming conventions, all I care about is consistency, whether you use Hungarian or Swahili is not important, but whatever convention you use you must stick to it, at least within a project. My only global rule would be to ban double underscores, reserving them for compiler writers.


Rgds phld

 
 
Jeff Wharton





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

I agree with Philip as if you access the private variable directly, you may be bypassing business logic implemented into the getter or setter.

 
 
Paul Louth





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

I disagree, your class should know about it's own internal implementation - it's domain. So if you know that the 'Id' property always returns this.id then I don't see why internally you should incur the overhead of calling a property method.
 
 
Jeff Wharton





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

Remembering that whatever method you chose to implement, you should continue to implement throughout your code (bit like coding conventions), what would you recommend calling for this example :

class MyClass
{
private int x;
public int X
{
get
{
return DoComplexCalculation();
}
set
{
if (value < 0)
{
throw new ApplicationException("Invalid Value");
}
else
x = value;
}
}

private int DoComplexCalculation()
{
return x * 3 / 7 + 4;
}
}

You would need to call the property, therefore you should always call the property as you want to stay consistent and calling the property in some instances and the variable in others will only make your code confusing.

Also, what if someone decided to change the implementation (not the interface) of a property and include some important rules/calculations and didn't realise that you were calling the variable directly



 
 
Paul Louth





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

Obviously if the property does some complex calculation then using that internally makes sense.  But usually a property that does a complex calculation does it for the purposes of external code not for internal reasons.  Also if somebody doesn't realise that you were calling the variable directly internally then the class is too complex and should be refactored (and unit-tests should fire!) 

There's also an argument that if you're doing complex calculation inside a property accessor then you should change it to GetX() to show users of your class that it's performing extra work and not just a simple accessor with validation.  So I'd implement your example thus:

class MyClass
{
    private int x;

    public int X
    {
        set
        {
            if (value < 0)
            {
                throw new ApplicationException("Invalid Value");
            }
            else
            {
                x = value;
            }
        }
    }

    public int DoComplexCalculation()
    {
        return x * 3 / 7 + 4;
    }
}

I think you should be pragmatic in your choice, not blindly follow one rule for your entire project, as there really isn't a 'best fit'.


 
 
PhilipDaniels





PostPosted: Visual C# General, Accessing Class Properties within the Class - use private or public properties. Top

Any compiler worth its salt will optimise the inefficiencies you percieve out of the object code. Hence gets and sets that add no value will play no role in the executable code.

However if you add some value to an accessor, and the accessors are used religiously, then all you need to worry about the new functionality not whether it will be utilised in all contexts.

I've no idea what the state of play is with C#, but the optimisation in MS's C compilers is pretty good, in some instances amazingly so, I hope that some of that knowledge & skill has been transferred to the C# guys.

Your are absolutely right a class should know all about itself, but I know of no self maintaining classes. It is for the people of tomorrow who have to maintain the code that we write today, that we do these things

rgds phild