Setting value of private property - c#

I am trying to test my class
public class Parser
{
private static IDictionary<String, Regex> PhrasesToRegexp { get; set; }
public static void InitPhrases(IList<String> Phrases, Boolean useDeclination )
{
throw new NotImplementedException();
}
...
public ParsingResults Find(String source)
{
HtmlDocument doc = new HtmlDocument();
doc.LoadHtml(source);
return new ParsingResults(FindUrls(doc), CountPhrases(doc));
}
private IList<String> FindUrls(HtmlDocument source)
{
return source.DocumentNode.SelectNodes("//a[#href]").
Select(link => link.GetAttributeValue("href", "")).ToList();
}
private IDictionary<String, int> CountPhrases(HtmlDocument source)
{
IDictionary<String, int> results = new Dictionary<String, int>();
foreach (String key in PhrasesToRegexp.Keys)
{
results.Add( key , 0 );
}
foreach (HtmlNode node in source.DocumentNode.SelectNodes("//p"))
{
foreach (String phrase in results.Keys)
{
results[phrase] += PhrasesToRegexp[phrase].Matches
(Regex.Replace(node.InnerText, #"<(.|\n)*?>", string.Empty)).Count;
}
}
return results;
}
}
The thing is that property PhrasesToRegexp is (will be) initialized in InitPhrases and I am trying write unit test for method Find. Basicly i need to set value of this private property PhrasesToRegexp. Is there any way to do that? I am no expert in mocks but i think they will not do the trick since this property and tested method are in the same object.

You could add a new constructor specifically for unit tests, but I would advise minimising any changes to your class to make it unit-testable. Specialisations to support unit tests usually mean that you aren't testing the actual code that will run in the final application. The further you specialise it, the harder it is to be sure that the real code is being fully tested, and the more chance there is of introducing unwanted side effects into the code under test.
Instead, (if possible) I try to use the class as a client would - if you construct the instance and call the method as a client would, you shouldn't need to poke about in private state, and your unit test will test exactly what any client code will use. Also, your test is more likely to remain valid/effective if you change the internal workings of the class, as there is no special pathway for unit tests that you can forget to keep in sync with the code changes.
If you prefer to expose the property and prod it directly, then changing it to internal and using InternalsVisibleTo is a standard approach, but it offends my sense of encapsulation as it becomes permanently internal for everybody. How is another programmer to know that you mean "internal for testing" rather than "hey, we're good friends, please party on my internal state as much as you like". What is private there for if we just throw it away when we want to unit test? So another approach, which keeps the code private, is to use a special build for unit testing, which sets a #define to allow you to expose the privates you want to access for tests, while leaving them private in your normal build.
One way is brute force on the property itself (but this can be quite messy):
#if UNIT_TEST
public
#else
private
#endif
int MyPrivateProperty { get; set; }
Or, a cleaner approach (but more work) is to leave the original code unscathed and add access methods, to minimise the chance that you inadvertently break/alter the code under test.
private int MyProperty { get; set; }
#if UNIT_TEST
public int AccessMyProperty
{
get { return(MyProperty); }
set { MyProperty = value; }
}
#endif

In my Unit Test project I've created a MockClass which extends the original class, no methods or properties are rewritten.
Original class: the property which was private is promoted to protected.
Mock class: Created a public method which sets the protected property.
With this approach you don't have to change visibility to internal, which is a lot more visible than protected. Of course it also means that if a developer wants to acces your property he is able to by extending your class, in the same manner as your unit test does.
public class Parser
{
protected static IDictionary<String, Regex> PhrasesToRegexp { get; set; }
...
}
public class MockParser : Parser
{
public MockParser() : base()
{
}
public void AddPhraseToRegexp(String key, Regex value)
{
// Add it
PhrasesToRegexp.Add(key, value);
}
public void CreatePhrasesToRegexp(IDictionary<String, Regex> newDict)
{
// Create a new Dictionary
PhrasesToRegexp = newDict;
}
}
NOTE: this does NOT work for static or sealed classes

This may be possible depending on mocking framework you are using. I usually use Moq or NMock2, and in those cases the viable options are:
1) Make the property internal instead of private, which allows you to set it in unit test. You may have to use InternalsVisibleTo attibute if your unit tests are in separate project.
2) Create a separate constructor for unit test purpoeses that will accept PhrasesToRegexp

1) Instead of private you should declare it as internal.
2) In AssemblyInfo.cs you should add the assembly, from there your class will be accessed like follows
[assembly: InternalsVisibleTo("MainFormUnitTests")]

For me, this problem is arising because you are expressing two different concerns in your parser.
A quick reference cache for your phrases and regex
The parsing logic
I would suggest splitting out these two concerns into two different classes. Besides, you might want to address clearing out the memory of the static dictionary at some point (or invalidating the cache).
If you take the caching logic out behind a ICachePhrasesAndRegex interface then you can easily mock the dependency for testing.

Related

shortcutting access to another class properties, best practices

My app has a CurrentContext class, it provides access to properties used across the whole app (so there's no need to pass the objects via constructor parameters or methods).
Most of those properties do not change their value during a single session.
Because some classes use some of the properties quite often I decided to create properties inside them, now I'm refactoring my code so the access pattern everywhere is the same.
Which of the below pattern is a better practice?
What is the difference in memory usage or performance?
CurrentContext class:
public class CurrentContext
{
public Document Doc {get; set}
public LogFile LogFile {get; set;}
public bool AbortFlag {get; set;}
}
Class accessing the properties of CurrentContext class:
Variant 1:
public class Example
{
private Document Doc {get { return MyApp.CurrentContext.Doc; } }
private LogFile LogFile {get { return MyApp.CurrentContext.LogFile; } }
private bool AbortFlag {get { return MyApp.CurrentContext.AbortFlag; } }
}
Variant 2:
public class Example
{
private Document Doc {get; }
private LogFile LogFile {get; }
private bool AbortFlag {get; }
public Example()
{
Doc = MyApp.CurrentContext.Doc;
LogFile = MyApp.CurrentContext.LogFile;
AbortFlag = MyApp.CurrentContext.AbortFlag;
}
}
Your question is based on a false belief; that the only difference between both approaches is a supposedly gain (or loss) in performance. That is not true; the two options you are proposing have very different meanings.
The first will always return an updated value when the properties are accessed, the second will return the values at the time the object was created.
It’s up to you to decide which of the two is the correct approach. Performance wise the difference, if any, is absolutely insignificant unless the accessed properties themselves are expensive (which they shouldn’t if you follow best practices).
Were it my code, I’d probably push back on the whole set up. Repeating properties is boring and hard to maintain if the underlying object changes throughout the life of your application. I’d simply expose the object itself or if that’s not an option, I would expose a readonly interface.
The first version better, because it is returned the current value. When the value of any MyApp.CurrentContext.* variable is changing, your Example will also changing.
This version is little-bit slower, but in 99% percent this disadvantage is acceptable.
But please expression body member syntax. This syntax is designed for this case:
public class Example
{
private Document Doc => MyApp.CurrentContext.Doc;
private LogFile LogFile => MyApp.CurrentContext.LogFile;
private bool AbortFlag => MyApp.CurrentContext.AbortFlag;
}
This code is more understandable.

Object Oriented - Class Variables

I am pretty new to OOP and looking into things in a bit more depth, but I have a bit of confusion between these 3 methods in C# and which one is best and what the differences are between 2 of them.
Example 1
So lets start with this one, which (so I understand) is the wrong way to do it:
public class MyClass
{
public string myAttribute;
}
and in this way I can set the attribute directly using:
myObject.myAttribute = "something";
Example 2
The next way I have seen and that seems to be recomended is this:
public class MyClass
{
public string myAttribute { get; set;}
}
With getters and setters, this where I dont understand the difference between the first 2 as the variable can still be set directly on the object?
Example 3
The third way, and the way that I understand the theory behind, is creating a set function
public class MyClass
{
string myAttribute;
public void setAttribute(string newSetting)
{
myAttribute = newSetting;
//obviously you can apply some logic in here to remove unwanted characters or validate etc.
}
}
So, what are the differences between the three? I assume example 1 is a big no-no so which is best out of 2 and 3, and why use one over the other?
Thanks
The second
public class MyClass
{
public string MyAttribute { get; set;}
}
is basically shorthand for:
public class MyClass
{
private string myPrivateAttribute;
public string MyAttribute
{
get {return myPrivateAttribute;}
set {myPrivateAttribute = value;}
}
}
That is an auto-implemented property, which is exactly the same as any regular property, you just do not have to implement it, when the compiler can do that for you.
So, what is a property? It's nothing more than a couple of methods, coupled with a name. I could do:
public class MyClass
{
private string myPrivateAttribute;
public string GetMyAttribute()
{
return myPrivateAttribute;
}
public void SetMyAttribute(string value)
{
myPrivateAttribute = value;
}
}
but then instead of writing
myClass.MyAttribute = "something";
string variable = myClass.MyAttribute;
I would have to use the more verbose, but not necessarily clearer form:
myClass.SetMyAttribute("something");
string variable = myClass.GetMyAttribute();
Note that nothing constraints the contents of the get and set methods (accessors in C# terminology), they are methods, just like any other. You can add as much or as little logic as you need inside them. I.e. it is useful to make a prototype with auto-implemented properties, and later to add any necessary logic (e.g. log property access, or add lazy initalization) with an explicit implementation.
What your asking here has to do with encapsulation in OOP languages.
The difference between them is in the way you can access the propriety of an object after you created an object from your class.
In the fist example you can access it directly new MyClass().MyAttribute whether you get or set it's value.
In the second example you declare 2 basic functions for accessing it:
public string MyAttribute
{
get {return myPrivateAttribute;}
set {myPrivateAttribute = value;}
}
In the third example you declare your own method for setting the value. This is useful if you want to customize the setter. For example you don't want to set the value passed, but the value multiplied by 2 or something else...
I recommend some reading. You can find something here and here.
Property is a syntactic sugar over private attribute with get and set methods and it's realy helpful and fast to type;
You may treat automatic property with { get; set;} as a public attribute. It has no additional logic but you may add it later without uset ever notice it.
Just exchange
public string MyLine { get; set;}
to
string myLine;
public string MyLine
{
get { return myLine; }
set { myLine = value + Environment.NewLine; }
}
for example if you need so.
You can also easily create read only property as { get; private set }.
So use Properties instead of public attributes every time just because its easier and faster to write and it's provides better encapsulation because user should not be used get and set methods if you decide to use it in new version of yours programm.
One of the main principles of OOP is encapsulation, and this is essentially the difference between the first example and the other 2.
The first example you have a private field which is exposed directly from the object - this is bad because you are allowing mutation of internal data from outside the object and therefore have no control over it.
The other 2 examples are syntactically equivalent, the second being recommended simply because it's less code to write. However, more importantly they both restrict access & control mutation of the internal data so give you complete control over how the data should be managed - this is ecapsulation.

How to Shim long external dependency with ConcurrentDictionary (C#) via Microsoft Fakes?

In code I need to test was found such external dependency:
var something = GConfig.SConfig[Type.ServiceType1].Names;
Code of this part is like this:
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
namespace Class
{
public sealed class GConfig
{
public ConcurrentDictionary<Type, GConfigIt> SConfig { get; set; }
public GConfig()
{
SConfig = new ConcurrentDictionary<Type, GConfigIt>();
throw new InvalidOperationException("Error");
}
}
public enum Type
{
ServiceType1,
ServiceType2
}
public class GConfigIt
{
public List<string> Names { get; set; }
public GConfigIt()
{
Names = new List<string>();
}
}
}
I need to shim that dependency, but on my own I can't find full solution, only partly:
For GConfigIt (and shimming Names): Fakes.ShimGConfigIt.AllInstances.NamesGet
For shimming SConfig: Fakes.ShimGConfig.AllInstances.SConfigGet
But I can't find connection, how to shim it fully.
P.S. I'm only a tester and can't change existing code. For making a change I need to convince developers to do it (i.e. extra interface for GConfig), but they must sure that it's not a change just for "easy testing" or "testing for testing" and they really need to do it.
Okay, so you are actually on the right track. You begin with Fakes.ShimGConfig.AllInstances.SConfigGet, and once that works, you need to shim the dictionary.
Probably something like Fakes.ShimConcurrentDictionary.AllInstances.ItemGetType which you can make return whatever GConfigIt you want, probably a stub.
You can either set the property of said stub or do what you were doing before for names.
I'm assuming the concurrent dictionary can be shimmed; If not, you still aren't stuck. Simply shim your SConfigGet to return a stub of SConfigGet, into which you can enter valid values. This might even be better than the other way, since you assume less about the implementation.

what is the meaning of data hiding

One of the most important aspects of OOP is data hiding. Can somebody explain using a simple piece of code what data hiding is exactly and why we need it?
Data or Information Hiding is a design principal proposed by David Paranas.
It says that you should hide the
design decisions in one part of the
program that are likely to be changed
from other parts of the program, there
by protecting the other parts from
being affected by the changes in the
first part.
Encapsulation is programming language feature which enables data hiding.
However note that you can do data\information hiding even without encapsulation. For example using modules or functions in non Object Oriented programming languages. Thus encapsulation is not data hiding but only a means of achieving it.
While doing encapsulation if you ignore the underlying principal then you will not have a good design. For example consider this class -
public class ActionHistory
{
private string[] _actionHistory;
public string[] HistoryItems
{
get{return _actionHistory; }
set{ _actionHistory = value; }
}
}
This calls encapsulates an array. But it does not hide the design decision of using a string[] as an internal storage. If we want to change the internal storage later on it will affect the code using this class as well.
Better design would be -
public class ActionHistory
{
private string[] _actionHistory;
public IEnumerable<string> HistoryItems
{
get{return _actionHistory; }
}
}
I'm guessing by data hiding you mean something like encapsulation or having a variable within an object and only exposing it by get and modify methods, usually when you want to enforce some logic to do with setting a value?
public class Customer
{
private decimal _accountBalance;
public decimal GetBalance()
{
return _accountBalance;
}
public void AddCharge(decimal charge)
{
_accountBalance += charge;
if (_accountBalance < 0)
{
throw new ArgumentException(
"The charge cannot put the customer in credit");
}
}
}
I.e. in this example, I'm allowing the consuming class to get the balance of the Customer, but I'm not allowing them to set it directly. However I've exposed a method that allows me to modify the _accountBalance within the class instance by adding to it via a charge in an AddCharge method.
Here's an article you may find useful.
Information hiding (or more accurately encapsulation) is the practice of restricting direct access to your information on a class. We use getters/setters or more advanced constructs in C# called properties.
This lets us govern how the data is accessed, so we can sanitize inputs and format outputs later if it's required.
The idea is on any public interface, we cannot trust the calling body to do the right thing, so if you make sure it can ONLY do the right thing, you'll have less problems.
Example:
public class InformationHiding
{
private string _name;
public string Name
{
get { return _name; }
set { _name = value; }
}
/// This example ensures you can't have a negative age
/// as this would probably mess up logic somewhere in
/// this class.
private int _age;
public int Age
{
get { return _age; }
set { if (value < 0) { _age = 0; } else { _age = value; } }
}
}
Imagine that the users of your class are trying to come up with ways to make your class no longer fulfill its contract. For instance, your Banking object may have a contract that ensures that all Transactions are recorded in a log. Suppose mutation of the Bank's TransactionLog were publically accessible; now a consuming class could initiate suspect transactions and modify the log to remove the records.
This is an extreme example, but the basic principles remain the same. It's up to the class author to maintain the contractual obligations of the class and this means you either need to have weak contractual obligations (reducing the usefulness of your class) or you need to be very careful about how your state can be mutated.
What is data hiding?
Here's an example:
public class Vehicle
{
private bool isEngineStarted;
private void StartEngine()
{
// Code here.
this.isEngineStarted = true;
}
public void GoToLocation(Location location)
{
if (!this.isEngineStarted)
{
this.StartEngine();
}
// Code here: move to a new location.
}
}
As you see, the isEngineStarted field is private, ie. accessible from the class itself. In fact, when calling an object of type Vehicle, we do need to move the vehicle to a location, but don't need to know how this will be done. For example, it doesn't matter, for the caller object, if the engine is started or not: if it's not, it's to the Vehicle object to start it before moving to a location.
Why do we need this?
Mostly to make the code easier to read and to use. Classes may have dozens or hundreds of fields and properties that are used only by them. Exposing all those fields and properties to the outside world will be confusing.
Another reason is that it is easier to control a state of a private field/property. For example, in the sample code above, imagine StartEngine is performing some tasks, then assigning true to this.isEngineStarted. If isEngineStarted is public, another class would be able to set it to true, without performing tasks made by StartEngine. In this case, the value of isEngineStarted will be unreliable.
Data Hiding is defined as hiding a base class method in a derived class by naming the new class method the same name as the base class method.
class Person
{
public string AnswerGreeting()
{
return "Hi, I'm doing well. And you?";
}
}
class Employee : Person
{
new public string AnswerGreeting()
{
"Hi, and welcome to our resort.";
}
}
In this c# code, the new keyword prevents the compiler from giving a warning that the base class implementation of AnswerGreeting is being hidden by the implementation of a method with the same name in the derived class. Also known as "data hiding by inheritance".
By data hiding you are presumably referring to encapsulation. Encapsulation is defined by wikipedia as follows:
Encapsulation conceals the functional
details of a class from objects that
send messages to it.
To explain a bit further, when you design a class you can design public and private members. The class exposes its public members to other code in the program, but only the code written in the class can access the private members.
In this way a class exposes a public interface but can hide the implementation of that interface, which can include hiding how the data that the class holds is implemented.
Here is an example of a simple mathematical angle class that exposes values for both degrees and radians, but the actual storage format of the data is hidden and can be changed in the future without breaking the rest of the program.
public class Angle
{
private double _angleInDegrees;
public double Degrees
{
get
{
return _angleInDegrees;
}
set
{
_angleInDegrees = value;
}
}
public double Radians
{
get
{
return _angleInDegrees * PI / 180;
}
set
{
_angleInDegrees = value * 180 / PI;
}
}
}

More private than private? (C#)

Sometimes you have a private field that backs a property, you only ever want to set the field via the property setter so that additional processing can be done whenever the field changes. The problem is that it's still easy to accidentally bypass the property setter from within other methods of the same class and not notice that you've done so. Is there a way in C# to work around this or a general design principle to avoid it?
IMHO, it is not used, because:
The class must trust itself
If your class gets as large that one part does not know the other, it should be divided.
If the logic behind the property is slightly more complex, consider to encapsulate it in an own type.
I'd consider this a nasty hack and try to avoid it if possible, but...
You can mark the backing field as obsolete so that the compiler will generate a warning when you try to access it, and then suppress that warning for the property getter/setter.
The warning codes that you'd need to suppress are CS0612 for the plain Obsolete attribute and CS0618 if the attribute has a custom message.
[Obsolete("Please don't touch the backing field!")]
private int _backingField;
public int YourProperty
{
#pragma warning disable 612, 618
get { return _backingField; }
set { _backingField = value; }
#pragma warning restore 612, 618
}
There's no inbuilt way to do what you want to do, but by the sounds of things you need another layer of abstraction between your class and that value.
Create a separate class and put the item in there, then your outer class contains the new class, and you can only access it through its properties.
No, there isn't. I'd quite like this myself - something along the lines of:
public string Name
{
private string name; // Only accessible within the property
get { return name; /* Extra processing here */ }
set { name = value; /* Extra processing here */ }
}
I think I first suggested this about 5 years ago on the C# newsgroups... I don't expect to ever see it happen though.
There are various wrinkles to consider around serialization etc, but I still think it would be nice. I'd rather have automatically implemented readonly properties first though...
You CAN do this, by using a closure over a local in the constructor (or other initialisation function). But it requires significantly more work that the helper class approach.
class MyClass {
private Func<Foo> reallyPrivateFieldGetter;
private Action<Foo> reallyPrivateFieldSetter;
private Foo ReallyPrivateBackingFieldProperty {
get { return reallyPrivateFieldGetter(); }
set { reallyPrivateFieldSetter(value); }
}
public MyClass() {
Foo reallyPrivateField = 0;
reallyPrivateFieldGetter = () => { return reallyPrivateField; }
reallyPrivateFieldSetter = v => { reallyPrivateField = v; };
}
}
I suspect that the underlying field type Foo will need to be a reference class, so the two closures are created over the same object.
There is no such provisioning in C#.
However I would name private variables differently (e.g. m_something or just _something) so it is easier to spot it when it is used.
You can put all of your private fields into a nested class and expose them via public properties. Then within your class, you instantiate that nested class and use it. This way those private fields are not accessible as they would have been if they were part of your main class.
public class A
{
class FieldsForA
{
private int number;
public int Number
{
get
{
//TODO: Extra logic.
return number;
}
set
{
//TODO: Extra logic.
number = value;
}
}
}
FieldsForA fields = new FieldsForA();
public int Number
{
get{ return fields.Number;}
set{ fields.Number = value;}
}
}
It just provides a level of obstruction. The underlying problem of accessing private backing fields is still there within the nested class. However, the code within class A can't access those private fields of nested class FieldForA. It has to go through the public properties.
Perhaps a property backing store, similar to the way WPF stores properties?
So, you could have:
Dictionary<string,object> mPropertyBackingStore = new Dictionary<string,object> ();
public PropertyThing MyPropertyThing
{
get { return mPropertyBackingStore["MyPropertyThing"] as PropertyThing; }
set { mPropertyBackingStore["MyPropertyThing"] = value; }
}
You can do all the pre-processing you want now, safe in the knowledge that if anyone did access the variable directly, it would have been really really hard compared to the property accessor.
P.S. You may even be able to use the dependency property infrastructure from WPF...
P.P.S. This is obviously going to incur the cost of casting, but it depends on your needs - if performance is critical, perhaps this isn't the solution for you.
P.P.P.S Don't forget to initialise the backing store! (;
EDIT:
In fact, if you change the value property stored to a property storage object (using the Command pattern for example), you could do your processing in the command object...just a thought.
Can't do this in standard C#, however you could
define a custom attribute say OnlyAccessFromProperty
write your code like
[OnlyAccessFromProperty(Name)]
String name
Name
{
get{return name;}
}
etc …
Then write a custom rule for FxCop (or another checker)
Add FxCop to your build system so if your custom rule find an error the build is failed.
Do we need a set of standard custom rules/attributes to enforce common design patens like this without the need to extend C#
C# has no language feature for this. However, you can rely on naming conventions, similar to languages which have no private properties at all. Prefix your more private variable names with _p_, and you'll be pretty sure that you don't type it accidentally.
I don't know C# but in Java you may have a base class with only private instance variables and public setters and getters (should return a copy of the instance var.) and do all other in an inherited class.
A "general design principle" would be "use inheritance".
There is no build in solution in C#, but I think your problem can be solved by good OO design:
Each class should have a single purpose. So try to extract the logic around your field into a class as small as possible. This reduces the code where you can access the field by accident. If you do such errors by accident, your class is probably to big.
Often interface are good to restrict access to only a certain "subset" of an object. If that's appropriate for your case depends on your setting of course. More details about the work to be done would help to provide a better answer.
You say that you do additional processing. Presumably this would be detectable under the correct conditions. My solution, then, would be to create unit tests that implement conditions such that if the backing field is used directly the test will fail. Using these tests you should be able to ensure that your code correctly uses the property interface as long as the tests pass.
This has the benefit that you don't need to compromise your design. You get the safety of the unit tests to ensure that you don't accidently make breaking changes and you capture the understanding of how the class works so that others who come along later can read your tests as "documentation."
Wrap it in a class? The property thing is a bit like that anyway, associating data with methods - the "Encapsulation" they used to rave about...
class MyInt
{
private int n;
public static implicit operator MyInt(int v) // Set
{
MyInt tmp = new MyInt();
tmp.n = v;
return tmp;
}
public static implicit operator int(MyInt v) // Get
{
return v.n;
}
}
class MyClass
{
private MyInt myint;
public void func()
{
myint = 5;
myint.n = 2; // Can't do this.
myint = myint + 5 * 4; // Works just like an int.
}
}
I'm sure I'm missing something? It seems too normal...
BTW I do like the closures one, superbly mad.
My favorite solution to this (and what I follow) is to name private backing fields that are never intended to be used directly with a leading underscore, and private fields that are intended to be used without the underscore (but still lowercase).
I hate typing the underscore, so if I ever start to access a variable that starts with the underscore, I know somethings wrong - I'm not supposed to be directly accessing that variable. Obviously, this approach still doesn't ultimately stop you from accessing that field, but as you can see from the other answers, any approach that does is a work around and/or hardly practical.
Another benefit of using the underscore notation is that when you use the dropdown box to browse your class, it puts all of your private, never-to-be-used backing fields all in one place at the top of the list, instead of allowing them to be mixed in with their respective properties.
As a design practice, you could use a naming convention for "private properties" that's different from normal public members - for instance, using m_ItemName for private items instead of ItemName for public ones.
If you're using the C# 3.0 compiler you can define properties which have compiler-generated backing fields like this:
public int MyInt { get; set; }
That will mean there is only one way to access the property, sure it doesn't mean you can only access the field but it does mean that there's nothing but the property to access.
I agree with the general rule that the class should trust itself (and by inference anybody coding within the class).
It is a shame that the field is exposed via intellisense.
Sadly placing [EditorBrowsable(EditorBrowsableState.Never)] does not work within that class (or indeed the assembly(1))
In Visual C#, EditorBrowsableAttribute does not suppress members from a class in the same assembly.
If you really do wish to solve this aspect of it the the following class may be useful and makes the intent clear as well.
public sealed class TriggerField<T>
{
private T data;
///<summary>raised *after* the value changes, (old, new)</summary>
public event Action<T,T> OnSet;
public TriggerField() { }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(T initial) { this.data=initial; }
public TriggerField(Action<T,T> onSet) { this.OnSet += onSet; }
///<summary>the initial value does NOT trigger the onSet</summary>
public TriggerField(Action<T,T> onSet, T initial) : this(onSet)
{
this.data=initial;
}
public T Value
{
get { return this.data;}
set
{
var old = this.data;
this.data = value;
if (this.OnSet != null)
this.OnSet(old, value);
}
}
}
Allowing you to (somewhat verbosely) use it like so:
public class Foo
{
private readonly TriggerField<string> flibble = new TriggerField<string>();
private int versionCount = 0;
public Foo()
{
flibble.OnSet += (old,current) => this.versionCount++;
}
public string Flibble
{
get { return this.flibble.Value; }
set { this.flibble.Value = value; }
}
}
alternatively you can go for a less verbose option but accessing Flibble is by the not idiomatic bar.Flibble.Value = "x"; which would be problematic in reflective scenarios
public class Bar
{
public readonly TriggerField<string> Flibble;
private int versionCount = 0;
public Bar()
{
Flibble = new TriggerField<string>((old,current) => this.versionCount++);
}
}
or solution if you look at the community content!
The new Lazy class in .net 4.0
provides support for several common
patterns of lazy initialization
In my experience this is the most common reason I wish to wrap a field in a private properly, so solves a common case nicely. (If you are not using .Net 4 yet you can just create your own “Lazy” class with the same API as the .Net 4 version.)
See this and this and this for details of using the Lazy class.
Use the "veryprivate" construct type
Example:
veryprivate void YourMethod()
{
// code here
}

Categories

Resources