Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the best way to access properties from the same class, via accessors or directly? [closed]

This is something I'm not much consistent about and always curious about what other people do.

How do you access internal properties (private or public)?

For example you've got this property :

Private _Name As String

Public Property Name() As String
    Get
        Return _Name
    End Get
    Set(ByVal value As String)
        _Name = value
    End Set
End Property

In the same class within another function which one do you prefer? and why?

_Name = "Johnny"

or

Name = "Johnny"

Ignore the fact that I used Name instead of Me.Name.

like image 900
dr. evil Avatar asked Dec 07 '22 08:12

dr. evil


2 Answers

Personally I prefer to use the property where possible. This means you still get the validation, and you can easily put breakpoints on the property access. This doesn't work where you're trying to make a change to two properties which validate against each other - for instance, a "min and max" pair, where each has a validation constraint such that min <= max at all times. You might have (C#):

public void SetMinMax(int min, int max)
{
    if (max > min)
    {
        throw new ArgumentOutOfRangeException("max";
    }
    // We're okay now - no need to validate, so go straight to fields
    this.min = min;
    this.max = max;
}

At some point in the future, I'd like to see C# gain the ability to declare the backing field within the property, such that it's private to just the property:

public string Name
{
    string name;

    get { return name; }
    set
    {
        if (value == null)
        {
            throw new ArgumentNullException("value");
        }    
        name = value;
    }
}

Outside the property, you wouldn't be able to get at name at all, only Name. We already have this for automatically implemented properties, but they can't contain any logic.

like image 142
Jon Skeet Avatar answered Dec 09 '22 21:12

Jon Skeet


I would say

Name = "Johnny"

The reason is that I might have some validation (or trigger, or lazy initialization, or...), or might later decide to insert some validation, when assigning Name and I want to be sure to trigger that code.

like image 23
finnsson Avatar answered Dec 09 '22 21:12

finnsson