Style Guide to Prevent Unwanted Field Access

I once asked a question about whether it is possible to embed fields in properties so that they cannot be accessed in the rest of the class, for example.

public string Name { private string _name; get { return _name; } set { _name = value; // <Important stuff that would not be executed // upon direct field access> } } 

Unfortunately, this is not possible, so I thought that maybe it would help to set the style directive so that the fields would never be accessible outside the property. Obviously, you do not want to publish all fields publicly so that these fields require private properties as follows:

 private int _progress = 0; private int progress { get { return _progress; } set { _progress = value; } } 

If this involves the directive that fields must have an underscore as a prefix, you can immediately say that something is wrong if the underscore occurs elsewhere in the class.

So, my question - or rather, the questions:

Is that a good idea?
Is using camel housing for private properties reasonable?
Can anyone think of a scenario where this might be problematic?

+4
source share
1 answer

If the recipient and the setter have no side effects, it makes no sense to make a private property to wrap the private field. Either use the field, or do with it, or use the auto-property. Do not write six lines of code to express the intent of one line; you just make your code harder to read.

Now, if your setter had side effects, then this is another matter. In this case, it is good to have a directive that you should not set the field outside the property, but consider that the constructor may also need to set the field. (Initially, setting the state of an object may require that you bypass side effects.) There may also be other cases when you want to use this field (deep copy, load / save, etc.), but why use the property should be guiding rather than a hard rule: you want to give it an extra thought before going around the property.

As for the naming conventions, obviously it is up to you, but it seems strange to me that I have a camelCased property. Throughout the code I've seen, PascalCased properties, even if they are private.

+3
source

All Articles