using get vs property vs method [duplicate] - c#

This question already has answers here:
Exposing Member Objects As Properties or Methods in .NET
(7 answers)
Closed 9 years ago.
if i have a private property in a class, i'm wondering what technically the difference is between the following three scenarios (memory usage, usability, best practice, etc):
class testClass
{
private string myString1 = "hello";
private string myString2 { get { return "hello"; } }
private string myString3() { return "hello"; }
}
apart from obviously being able to set the value in myString1 and not in myString2 or myString3, i'm wondering more about how these differ in terms of efficiency?

I try to follow these rules where possible:
Fields should be kept private
Properties should be used to expose data
Methods should be used to perform an action
There are obviously going to be some situations where every last drop of performance is important, but in general I would attempt to follow best-practice until profiling tells you that optimisation is needed.
There's a good article here: Why Properties Matter

I personally prefer properties for things without side effects and explicit getter if something is calculate on the fly. Eg:
class User {
private string username;
public string Username {
get { return username; }
set { username = value; }
}
public Post GetLatestPost() {
// query the database or whatever you do here.
}
}
And a lot of the APIs I've seen seem to do it similar. Hope that helps.

All these methods are very different in terms of what they get compiled to, though very much similar in terms of use. I'll try to summarise the differences in brief:
This is a simple private instance variable. It's easily going to be the most efficient when referencing.
This is a read-only property (i.e. a get but no set accessor).
This is a normal parameterless function. I suspect you're just offering these examples purely as a point of comparison, and realise that such a function is totally useless (as are private properties, in almost all cases). The layout (i.e. everything on one line) is also rather horrible.
Methods 2 and 3 are going to be equally inefficient compared to 1 in that they both involve the overhead of function calls. I don't know by memory the CIL code that they all compile to (maybe someone else can produce that), but they certainly involve a few more instructions, whereas referencing myString1 ought to only require a single instruction in CIL.
Not sure I can make a very useful comment on best practice without knowing more about the context, but method 2 (i.e. a private property) is generally seen as quite useless. The third method should never be used in my opinion (it's begging to be turned into a property). I think what you really want is just a plain old private variable, so definitely go for the first declaration. Public values should always be accessed as properties rather than variables in classes (i.e. a private/protected backing variable to a property), but that is slightly unrelated to your question. (You could find plenty of resources discussing the matter in a quick search anyway.) Finally, note that if your "property" is going to be read-only (i.e. not modified at any point), you really want to use a constant, i.e. private const string myString1 = "hello";.
Hope that helps clarify things a bit.

Thats a good question:
You have this alternatives:
private string myString = "hi!"; //Private Field
public string MyString //Property created to the private field
{
get {return myString;}
}
public string myString {get; private set;} //VS2008 automatic properties
public string getMyString() //Method Way
{
return myString;
}
As you can see the idea is the same, not to violate the encapsulation principle. Use the one you feel more comfortable with, all of them achieves the goal, but I recommend property way or the VIsual Studio 2008 automatic Property.
Is more concise and clear to see than the methods.
Hope this helps!
Regards!!

As far as best practices go,
class testClass
{
private string _myString;
public string myString { get { return _myString; } set { _myString = value; } }
public testClass()
{
myString = "Hello"; // Initial value.
}
}
Is generally recommended as it implements encapsulation (hiding internal state so that all manipulations pass through the methods/interface). Of course, the setters and getters are often methods themselves.
In C# 3.0, you can replace the above with:
class testClass
{
public string myString { get; set; }
public testClass()
{
...
}
}
As far as efficiency goes, you really should not be thinking about your design in terms of whether direct access to a variable is more efficient than a property. The difference is so small (if any) and the best practices guidelines so clear that you are just going astray worrying about efficiency.

All of the above discussions about design, style etc are valid. But the question is about performance. Easy enough to test. Wrapped some timers around each of the invokations, repeated to int32.Max.
On my machine the below code shows that the myString1 is much faster. (Note that I had to change the class definition to make the members public):
private void button2_Click(object sender, EventArgs e)
{
//performance test
testClass t = new testClass();
System.Diagnostics.Stopwatch sw1 = new System.Diagnostics.Stopwatch();
sw1.Start();
for (int i = 0; i < int.MaxValue; i++)
{
string result = t.myString1;
}
sw1.Stop();
System.Diagnostics.Stopwatch sw2 = new System.Diagnostics.Stopwatch();
sw2.Start();
for (int i = 0; i < int.MaxValue; i++)
{
string result = t.myString2;
}
sw2.Stop();
System.Diagnostics.Stopwatch sw3 = new System.Diagnostics.Stopwatch();
sw3.Start();
for (int i = 0; i < int.MaxValue; i++)
{
string result = t.myString3();
}
sw3.Stop();
MessageBox.Show(string.Format("Direct: {0}, Getter: {1}, Method: {2}"
, sw1.ElapsedMilliseconds.ToString()
, sw2.ElapsedMilliseconds.ToString()
, sw3.ElapsedMilliseconds.ToString()));
}
class testClass
{
public string myString1 = "hello";
public string myString2 { get { return "hello"; } }
public string myString3() { return "hello"; }
}

Related

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.

Should you use properties to initialize your fields in the constructor?

Pretty simple question really, should I use my properties to initialize fields in the constructor or reference them directly?
Example:
public class Foo()
{
private string example;
public String Example
{
get/set etc..
}
public Foo(string exampleIn)
{
Example = exampleIn;
}
}
Or is it better practice to do this:
public class Foo()
{
private string example;
public String Example
{
get/set etc..
}
public Foo(string exampleIn)
{
example = exampleIn;
}
}
Either way, I don't think either would violate encapsulation so I am wondering if there is a preferred way to go?
There is really no right or wrong answer here (and because of that I am almost tempted to vote to close). But, I tend to agree with Jacob on this. I prefer the property getter and setter route especially now that we have automatic properties. Do keep in mind that you can have different access modifies on the getters and setters in case that influences your decision for any reason. I mean, if you are going to use the property in the constructor then try to be consistent and use it exclusively everywhere else in the class as well. That may mean that you do not want to expose the setter to the outside.
public class Foo()
{
private string example;
public String Example
{
get { return example; }
private set { example = value; }
}
public Foo(string exampleIn)
{
Example = exampleIn;
}
}
Before automatic properties, which were introduced in C# 3.0, your second example is more "proper" in my opinion. Now with automatic properties I think this is best:
public class Foo()
{
private string example;
public String Example
{
{ get; set; }
}
public Foo(string exampleIn)
{
Example = exampleIn;
}
}
It depends on whether the data value will further be processed inside the Setter. IF the value needs processing then it's better to use what #Jacob has said but if the value will not be further processed (which is the case in most scenarios), it's better to use the private member to avoid an extra method call to setter method. When CLR compiles the code, it create two methods for Get and Set property and using the Property to access/modify the value which defines the property will result in extra method call unnecessarily (if the value is not processed further).

Accessing members in your own class: use (auto)properties or not?

I've created this "question" as a community-wiki, because there is no right or wrong answer. I only would like to know how the community feels about this specific issue.
When you have a class with instance variables, and you also created properties that are simply getters and setters for these instance variables, should you use the properties inside your own class, or should you always use the instance variable?
Having auto-properties in C# 3.0 made this an even harder decision.
Using properties:
public class MyClass
{
private string _name;
// could be an auto-property of-course
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = Name;
// ...
Name = "someValue";
// ...
}
}
Using instance variables:
public class MyClass
{
private string _name;
public string Name { get { return _name; } set { _name = value; } }
public void Action()
{
string localVar = _name;
// ...
_name = "someValue";
// ...
}
}
(for those who hate member prefixes, I apologize)
Personally, I always use the latter (instance variables), because I feel that properties should only be used by other classes, not yourself. That's why I mostly stay away from auto-properties as well.
Of course, things change when the property setter (or getter) does a little more than just wrapping the instance variable.
Are there compelling reasons to pick one or the other?
I always use instance variables as well. The reason is because properties might be doing stuff like validating arguments (like in a setter) for not null or not empty. If you're using the variable inside your class code, there's no need to go through the extra overhead of those checks (assuming you know the variable value is valid). The properties could be doing other things as well (logging, for example), that are important for the public API, but not for internal usage, so again, it's better to avoid the overhead and just use the instance variable in my opinion.
I think it becomes more difficult to change the internal implementation if the code uses its own public interface.
Difficult to explain but consider these expressions:
mTotalPrice = mPrice * mQuantity;
mTotalPrice = Price * Quantity;
What to do in the second expression if I need to change the internals to express all prices in € instead of $ (without affecting the public interface which still uses $)?
One solution is to make the expression more complex by adding the opposite of the change in the property.
mTotalPrice = Price / Rate * Quantity
The other solution is to start to use the private field instead.
mTotalPrice = mPrice * Quantity
In the end you get a mix of private and public use. The only way to get consistent use is to always use the private field.
I don't like prefixing members either, but actually I find I can write something like this accidently and not spot it until run time. Which kinda tempts me to avoid using properties where they're not necessary... but I still do, currently!
Public String MyString
{
{ get { return this.MyString; } } //<== Stack Overflow
{ set { this.myString = value; } }
}
private String myString;
I think that there is no difference between these two approaches.
Auto-implemented properties is just a quick way to access private members which are created any way.
Example from MSDN:
class Customer
{
// Auto-Impl Properties for trivial get and set
public double TotalPurchases { get; set; }
public string Name { get; set; }
public int CustomerID { get; set; }
// Constructor
public Customer(double purchases, string name, int ID)
{
TotalPurchases = purchases;
Name = name;
CustomerID = ID;
}
// Methods
public string GetContactInfo() {return "ContactInfo";}
public string GetTransactionHistory() {return "History";}
// .. Additional methods, events, etc.
}
99% of the time I use the property rather then the instance variable. In the past, I've worked with a lot of code that used the instance variable and when there was a bug associated with that variable, I had to put a breakpoint on every line of code that referenced it.
I decided to use properties instead, either public or private, to wrap around the instance variable. Doing this means that I only have to put a breakpoint in the getter/setter of the property if I need to debug an issue with the instance variable, rather then having (potentially) a lot of breakpoints scattered all over the code.

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
}

UnitTesting Properties in .Net?

I am working on a lib that I want to release in open source. I have started writing the tests for the code, and I was wondering how I am suppose to test a property in a .Net object. Lets say I have the following:
public class Person{
#region variables
private string _name = String.Empty;
private string _surname = String.Empty;
#region properties
public string Name{
get{
return _name;
}
}
public string Surname{
get{
return _surname;
}
set{
_surname = value;
}
}
}
I have two questions related to the code:
How do I Unit test a Property that just has a getter (Like Name in the example)
How do I Unit test a Property with a setter and a getter (Like Surname in the example)
I want to test properties that are that simple because I have already found errors in other code were Itellinsense did the wrong autocomplete and the property was not returning the correct variable.
Update: I am not talking about simple properties as the one in the example, they do have some logic behind them and are quite hard to debug. Writing a test that uses the setter to test the getter and vice versa is not good because if there is a fail I won't know which method to blame. I am using properties because they were added as public variables and later more logic had to be added.
Don's waste your time on writing silly
tests for getters and setters.
Another test will probably set the
Name and then get that property so you
will have code coverage for the
getter.
You should test anything public facing, including properties. If you don't test a property, you run the risk that someone may add some logic inside it, breaking the functionality.
Also you shouldn't rely on it being tested in other tests. This makes your tests brittle, and makes it harder to identify where the problem is as a test will be testing more than one thing.
How do I Unit test a Property that
just has a getter (Like Name in the
example)
Really not so different from testing if you had a setter. you'll just need to find another way of determining the output. Could be in a ctor, or the result of other setters/operations on the object.
[Test]
public void NamePropTest()
{
Person p = new Person();
//Some code here that will set up the Person object
// so that you know what the name will be
Assert.AreEqual("some known value...", p.Name);
}
If we had setters for Name and SurName, but only a getter for FullName, the test could look like this:
[Test]
public void NamePropTest()
{
Person p = new Person();
p.Name = "Sean";
p.Surname = "Penn";
Assert.AreEqual("Sean Penn", p.FullName);
}
You should test properties. Also automatic properties!
Unittests are about assuring that changes to the program, don't break the program.
You could end up changing a property implementation at some time, and you want to make sure the program still works as expected. You do that with your tests.
Even if you use automatic properties (as a replacement for fields/member variables), the reason for making them properties is in case you want to change their implementation later on. Then you'll want the tests to be there.
EDIT: (In response to shahkalpesh's comment...)
If you are changing the
implementation, the tests might also
require the change. So, I don't know
of why someone should test simple
get/set?
Starting with this class:
public class TimeOfDay
{
public int Hour{get; private set;}
public int Minute{get; private set;}
public TimeOfDay(int hour, int minute)
{
Hour = hour;
Minute = minute;
}
}
When changing the implementation, the tests are still valid!
public class TimeOfDay
{
public int _minutesSinceMidnight = 0;
public int Hour
{
get { return _minutesSinceMidnight / 60; }
set { _minutesSinceMidnight = value * 60 + Minutes; }
}
public int Minute
{
get { return _minutesSinceMidnight % 60; }
set { _minutesSinceMidnight = Hour * 60 + value; }
}
public TimeOfDay(int hour, int minute)
{
Hour = hour;
Minute = minute;
}
}
Throw in some date and time arithmetic functions or something, and I would like the tests to show that everything still works...
I think you should test, them if you write them like you did. Afterall you can mistype something.
Just something like
var person = New Person();
person.Surname = "test";
Assert.AreEqual("test", person.Surname);
After all TDD and unit testing n general is all about avoiding the most bugs you can.
If by accident you had written this.
public class Person{
#region variables
private string _name = String.Empty;
private string _surname = String.Empty;
#region properties
public string Name{
get{
return _name;
}
}
public string Surname{
get{
return _name;
}
set{
_name = value;
}
}
}
then you would have a bug.
Testing the automatic properties is perhaps less valuable. But that's another question.
Those property should be there because you have usages that needs them. As for these there should be unit tests, you should already have coverage for them.
If there is no scenario that needs them, they possibly shouldn't be there at all.
As I understand, you shouldn't be testing properties (i.e. those which are simple get/set).
I am not sure what version of c# you are using. But, you can use automatic properties to avoid the simple set/get problems that you are facing.
See this link
Don's waste your time on writing silly tests for getters and setters.
Another test will probably set the Name and then get that property so you will have code coverage for the getter.
My question is more related of HOW to
write the test. I have been thinking
about it and I need to access the
private values to make sure that the
properties work as expected, otherwise
I do not know how to do it.
https://stackoverflow.com/users/59332/mandel
Ok...since you insist on knowing how to do it....
[Test]
TestMethod()
{
Person p = new Person();
p.Name = "a name";
p.Surname = "a surname";
Assert.That(p.Name, Is.EqualTo("a name"));
Assert.That(p.Surname, Is.EqualTo("a surname"));
}
However, that only works if you have setters....
If you only have getters there are only two ways I can think of that you can do this.
know the return value in advance and assert against that.
Use Reflection to set the value and then assert against that known value.
A better bit of advice would be to give up and test something worthwhile that actually adds value to your software. Testing getters and setters is an absolute waste of time unless there is something complex going on behind them....which is rarely the case.
I think you meant that your getter-only propoerty uses private fields or other private data. If you need to set them, only way is to get them by Reflection (see all (something)Info classes in System.Reflection). But there is a hard discussion if this is a good practice.

Categories

Resources