Techie Talks

Monday, July 03, 2006

Suggestion: Encapsulate-only field

How about a way of ensuring that a programmer uses only a property encapsulating a variable as opposed to directly acessing a variable?

e.g.:

// The property-only descriptor is the desired feature.
// The variable must be readable only in a fixed descriptor (MyInt)
// mentioned within the angle brackets.
private property-only<MyInt> int myInt;
public int MyInt
{
get { return myInt; } //OK to access the variable inside the descriptor
set { myInt = value; }
}

public int SecondAccessor
{
get { return myInt; } //Compiler must issue an error.
}

private void foo()
{
....
this.myInt = 10; //Compiler must issue an error
this.MyInt = 10; //OK
....
}

This way, it is ensured during compile time itself that no direct access to a particular variable within the code (except in the predetermined property) is allowed. This will be helpful

1) In cases in where reference variables are lazy initialized.
(eg: in get of MyRef property, if(myRef == null) myRef = new Ref(); return myRef;).

2) Moreover, ensures that the variables are initialized properly.

3) Also, it ensures access-time checking of variables - for bounds, value ranges, value legality etc.

4) Any "side-effect" code within the accessors are fired, for sure.

(Of course, for 2 and 3 the initialization/validation must be coded inside appropriate acessors. This method ensures that they are fired each time the local variable needs to be accessed, by protecting accidental access to local variable instead of the accessor.)

Update:

The current way of handling this issue is to name the private variable starting with an underscore ( _ ).

e.g.:
private int _myInt;
public int MyInt
{
get { return _myInt; }
set { _myInt = value; }
}

This does prevent ease of the local variable access to a great extent within the code. Yet, it doesn't warrant prevention against accidental access. However, since most of the errors would be happening while using autocomplete, I guess the underscore strategy would be good enough.

technorati tags:, , ,

0 Comments:

Post a Comment

<< Home