I'm a new programmer, so please excuse any dumbness of this question, how the following code is encapsulating private data? -
public class SomeClass
{
private int age;
public int Age
{
get { return age; }
set { age = value; }
}
public SomeClass(int age)
{
this.age = age;
}
}
I mean, with no restriction logic or filtering logic in the properties, how is the above code different from the folowing one -
public class SomeClass
{
public int age;
public SomeClass(int age)
{
this.age = age;
}
}
Is the first code providing any encapsulation at all?
It's providing one piece of encapsulation: it's saying, "there's an Age property you can get and set, but I'm not going to tell you how I'm implementing it."
That's not very strong encapsulation, but it does keep the implementation details separate from the public API. Without changing the public API at all, you could start to store the age somewhere else - in two short fields, in a service somewhere, as part of a long field or whatever. You could put logging in the property to see how often it's used. You could add an event which gets fired when the age changes (that's an API change, but won't break existing callers).
EDIT: One thing to note: even though this does nothing now, the change to make it do something later is both source and binary compatible. Changing a field to become a property is not backward compatible, either in source or binary forms. In most cases it will be source-compatible, but not binary-compatible. In some cases source will no longer build. In more evil (and contrived, admittedly) both versions will build, but with different effects.
Also note that as of C# 3, you can declare a trivial property as easily as a field:
public int Age { get; set; }
I have an article about all of this which provides more details.
This is a bit of a vacuous example. As you've correctly noted, the property doesn't seem to do anything.
But it could. For example, SomeClass could put restrictions on how the Age property is modified (by say not changing the age to a bad value like -2 or 823). Also, SomeClass need not represent age as an int internally. Age could be the result of a computation (by say subtracting today's date from a person's date of birth) or it could be stored within SomeClass as another data type (say a byte, long or a double).
I mean, with no restriction logic or filtering logic in the properties, how is the above one different from the folowing one
Its not the fact that you have or have not implemented the validation logic in the property, encapsulation here means that nobody can directly access/modify your private data. The only access available is to go through the property.
Using the bottom code, anyone can genereate exceptions and cause all kinds of havoc because they can do anything they want to your data.
Using the top code as its written allows this same havoc, but at any time in the future you can implement restriction logic in the Property and not have to modify an API for users of this class.
It's encapsulating, or wrapping, changes to the private variable age. Private variable Age can't be modified by external callers directly, only through the public methods given. It's setting up an interface so future changes to age won't break callers. The benefit is to external callers in the future, which is why it's hard to see now.
In your first example, SomeClass.Age is a property. The field "backing" the property is private. In your second example, SomeClass.age is a public field. While in many cases there may be no difference, choosing a property over a field gives you the ability to change the implementation without changing the API, or "shape" of the class. Maybe you want to do something (persist, or notify) whenever the property changes -- that would be impossible to do with a field.
Is the first code providing any encapsulation at all?
NO (at least the particular code you wrote).
The 2 pieces of code are almost the same. The first one doesn't provide any useful difference compare to the second one (as the code is written).
When using getters and setters, you can restrict access to the private variables. This could be a form of Encapsulation.
i.e.
private int x
public int getInt(String password){
if(password == 'RealPassword'){
return x
}
}
Related
I have seen some code and thought that something seems wrong with it, so I would like to know if it is acceptable for good coding or not, my first thought is no.
Consider:
class MyClass
{
private string m_MySuperString;
public string MySuperString
{
get { return m_MySuperString; }
set { m_MySuperString = value; }
}
public void MyMethod()
{
if (blah != yada)
{
m_MySuperString = badabing;
}
}
public void MyOtherMethod()
{
if (blah == yada)
{
m_MySuperString = badaboom;
}
}
}
Is this kind of direct access to the Backing Field an acceptable practice or is it bad coding - or should I ask what is the point of the Property Accessor, and if this is done internally in a class with public members , access is allowed by multiple components - is it possible to have a crash - I would venture in a multi threaded application a crash should be expected.
Please any thoughts ?
I have looked at this Link on SO and others>
Why use private members then use public properties to set them?
EDIT
Let me be clear since there is good info being provided and rather respond to all answers and comments directly.
I am not asking about what properties are for, not if I can do auto implemented properties, private setters, OnValueChange notifications, logic on the properties.
My question is in regards to accessing that backing field directly - for example if you have say a mutlithreaded scenario - isn't the whole point of the synclock on the getters/setters - to control access to the backingfield ? Will this kind of code be acceptable in that scenario - just adding a syncLock to the getter and setter ?? Keep in mind the code in the constructor of myClass is an example - the code can be in any additional method - such as the updated class - Method1
END EDIT
Properties in Object Oriented Programming (OOP) help to enforce Encapsulation. The idea is that only the object itself is allowed to interact with its own data (i.e. fields). Access to the object's data from outside is only allowed through methods. In Java, for instance, you have to explicitly write get- and set-methods. Properties in C# have a special syntax that combines both of these methods in one construct, but the getters and setters are in fact methods.
This also means that an object is absolutely allowed to access its own fields directly.
There are cases, however, where property getters and setters perform additional logic. A setter might raise the PropertyChanged event or do some validation. A getter might combine several fields or yield a formatted or calculated value. If you need this additional logic to be performed, then you must access the properties instead of the fields. If a property is auto-implemented, then you have no choice (in C#), since the backing field is hidden and not accessible. (In VB it is hidden from IntelliSense but accessible from within the class.)
I recommend checking out Chapter 8, Section 1 of #JonSkeet's C# In Depth (from which I've shamelessly taken the below snippets for the purpose of education) for more information on automatically implemented properties. In short answer to your question, no, there's nothing wrong with this code.
Consider that the following snippet:
public string Name { get; set; }
is compiled as
private string <Name>k__BackingField;
public string Name
{
get { return <Name>k__BackingField; }
set { <Name>k__BackingField = value; }
}
...so the compiler is already doing the work for you that you've done above. There are ways to modify what it's doing, but those don't really answer the question. One example given in the book for thread safety is this:
//code above, plus
private static int InstanceCounter { get; set; }
private static readonly object counterLock = new object();
public InstanceCountingPerson(string name, int age) {
Name = name;
Age = age;
lock (counterLock) // safe property access
{
InstanceCounter++;
// and whatever else you have to do with the lock enabled
}
}
--Which is a pattern also referenced in this SO question. However, as pointed out there, locks are (a) potentially slow, (b) might not actually ensure their job is done because they have to be released at some point, and (c) rely on the trust system, because they sort of naively assume that anything wanting to access that object will make proper use of the lock (not always true, at least not in some of the code I've seen :D ). The advantage of the getter and setter methods is that you can enforce the pattern of using the lock (read: properly encapsulate the field, as others have suggested) for any instance of your class.
Another pattern you might consider, however, is Inversion of Control. With a Dependency Injection container, you can specify the level of thread safety you are comfortable with. If you are comfortable with everyone waiting for a singleton instance of your object, you can declare that all references to the object's interface reference the same object (and must wait for the object to become available), or you can determine that a thread-safe instance of the object should be created each time it is requested. See this SO answer for more details.
Note:
Any peer-reviewed criticism of the above ideas will be graciously accepted and added to the answer, as I'm sort of a thread safety dilettante at this point.
In the use case described , You can define this as follows using auto-implemented properties
public string MySuperString{ get; set ;}
you should use a backing filed if you need to do some input verification or the property is different than the internal fields for example
public string FullName{ get { return firstName + LastName} }
another benefit of using properties is you can define them in an interface , which is better in the long run for future features to be added
This question already has answers here:
Auto-implemented getters and setters vs. public fields
(17 answers)
Difference between Property and Field in C# 3.0+
(10 answers)
Closed 8 years ago.
I've learned about the getter and setter topic and i couldn't understand the new type of this topic :
Let's say someone is declaring a new get&set method :
public int Id { get; set; };
What i want to know is what is the differences between doing what i wrote below and a regular public variable (public int id).
Comments are welcome.
Properties enhance the notion of encapsulation in OOP (oject oriented programming). That's the of a getter and setter in C#. Concretely, instead of using a simple variable class, you could use a property and a backing field in which actually your value will be stored. The property would be the way to access this backing variable and get it's value or altered it. The good thing about properties is that you can use any logic you want, before you store the value the user provide you. So instead of doing the same check in the methods of your class where this value is setted by the user and then used you could use your property.
Let we have a class called Customer where, one of it's fields is the customer's age.
public class Customer
{
private int age;
public int Age
{
get
{
return age;
}
set
{
if(age>0)
{
age = value;
}
else
{
throw new ArgumentException("age must be greater than 0.");
}
}
}
}
Having defined the above property, you avoid the check of the age that will be provide by the creator of an object of type Customer in any other place. the provided value will be stored somewhere that the creator/consumer of the object should not know (encapsulation) and in general terms would make you life as a programmer far easier.
So you contructor now will not contain any logic:
public class Customer(int age)
{
Age = age;
}
you simply assign the provided value to the corresponding property, without making any check about the validity of the provided value in your constructor.
Furthermore, say that in a method of your class some calculations are executed and the result is going to stored to variable called age. If you use it's corresponding property, you will not have again to make any validation check. This was a rather simple case with one variable. Try to think about what would have happened if you had 6 or 7 variables, a common case in production code.
The above are applicable wherever you have variables, whose values setting requires validation. On the other, if you class holds only varaibles, whose values aren't to undergo a validation testing, you could use the following syntax.
public class Customer
{
public int Age { get; set; }
}
This syntax, at first seems meaningless. Why we should declare this instead of the following one:
public class Customer
{
public int age;
}
The second declaration doesn't respect the principle of encapsulation (for more information about encapsulation in OOP, please refer here. Namely, the second declaration exposes the variable in which we will actually store the value of age.
In a few words, it wouldn't happened anything odd if you had use the second declaration and not the first one - provided that's there weresn't any logic in you value setting. However it's more consistent you use the first one.
A public property keeps the option open to perform validation or other logic while getting or setting the value. A public field does not.
For example:
- You might want to check that an age value isn't negative or ridiciously high
- You might want to make sure that when a first name is set, that it is properly cased
If you offer these properties as public fields you won't be able to enforce these rules later on.
You can also use properties to perform lazy instantiation, which might be useful when working with resource intensive code.
Take private string Property {get; set;} versus private string field.
Note that both are private (so they will not be exposed outside of this class) and that the property is not employing extra validation.
As regards semantics, do they have different meanings? In the sense that, are they interchangeable when used like this?
And when it comes to implications, such as (micro?) performance, does it matter if you create a field versus a property i.e. letting the compiler take care of the backing field for you.
When they're private the only difference I know is that the property is not suitable for out and ref parameters.
But mostly a private property does not deliver any advantages (over a field), so why bother?
There probably are (micro) performance costs. I would worry more about the extra clutter.
A property is about data hiding of a field
A private property does not mean much, since whoever has access to the property, will have access to the field as well
There is no performance implication for auto-property versus backing field since compiler spits out the backing field but there can be serialisation/deserialisation caveats.
UPDATE
Performance implications:
There is a slight performance in using property (auto or with backing field) vs field since a property is a method and a CLR virtcall needs to be called.
But as I said, there is not much point in using property and I believe a field is more readable as usually immediately visible by the naming convention (starting with underscore or camel casing).
You can't have a reference to a property, but you can get a reference to a member. Thus, if you use members, you might have trouble switching them to properties for whatever reason later, such as adding the notorious validation.
Creating a private automatic property has no use that I can see. If its not automatic it could be used as some kind of internal 'event handler' to keep the object state up to date: perform some actions every time the field changes (through the setter) anywhere in the code.
Performance? I dont think there would be an issue, not even at a micro micro level.
Properties ARE functions.
Fields are 'variables with at least class visibility'.
So if you have private property vs private field:
The difference from the performance point:
no difference if you use optimization and no trace (properties are treated as inlines).
The difference in semantics:
1) Formally no difference.
2) More deeply, there IS a difference. Since properties are functions you CAN get a delegate from getter and setter. And CAN use the delegate as... delegate, like putting this delegate to the list with other delegates (Create a delegate from a property getter or setter method)
The difference from a design view:
But properties are functions that looks like variables. Why one could need functions that look like variables?
Lets say you have class Hand and this hand has variable fingersNumber.
class Hand
{
public int fingersNumber;
}
Then you may have a lot of code like
if(he is BadPerson) leftHand.fingersNumber--
if(doctor.Heal()) leftHand.fingersNumber++
But at some point you may want to add some other variable to Hand. Lets say it is ringsNumber. And you know, that you can't have more than 10 rings for each finger.
class Hand
{
public int fingersNumber;
public int ringsNumber;
}
now, you cannot just do
leftHand.fingersNumber--
because you have to control ringsNumber on fingersNumber dependence.
So you have to create some functions that whould check this dependance. Also you have to hide fingersNumber ander ringsNumber from users so they cannot change this fields without the check.
class Hand
{
private int fingersNumber;
private int ringsNumber;
public int GetFingersNumber(){...check logic...}
public void SetFingersNumber(int value){...check logic...}
public int GetRingsNumber(){...check logic...}
public void SetRingsNumber(int value){...check logic...}
}
And use this functions as
if(he is BadPerson) leftHand.SetFingersNumber(leftHand.GetFingersNumber()-1)
The problem here that the old code leftHand.fingersNumber-- would not work now. And from the beginning you wouldn't know that one will add rings in the future. To solve the problems it became a paradigm to set fields as private and use Set and Get functions to get and change variables and BE SURE that in the future one could add any logic there and code would work!
Setters and Getters is a current situation in C++, Java and many languages.
But C# creators went further and decorated such getters and setters functions as "properties".
class Hand
{
private int fingersNumber;
public int FingersNumber
{
get{return fingersNumber;}
set{fingersNumber=value;}
}
...
}
...
if(he is BadPerson) leftHand.FingersNumber--;
But most of the time people create such simple property and, you see the example, it is 5 lines of routine code. So at some version of C# autoproperties was added to simplify life of programmers. So your class is probably looks like
class Hand
{
public int FingersNumber{get;set;}
}
but at any time you can extend this get set behaviour:
class Hand
{
private int fingersNumber;
public int FingersNumber
{
get{...check logic...}
set{...check logic...}
}
...
}
And it will NOT BRAKE ANY CODE. Like
if(he is BadPerson) leftHand.FingersNumber--;
So thats what are the properties, why do they used and what is the difference with fields.
Also as I ser earlier, simple properties and autoproperties have the same performance as variables if you use optimization. Se disassembly or just google about it.
Seen a few examples of code where this happens:
public class Foo
{
string[] m_workID;
public string[] WorkID
{
get
{
return m_workID;
}
private set
{
m_workID = value;
}
}
}
What's the point of this?
Since the use m_workID unnescessary.
In general, the point is to separate implementation (the field) from API (the property).
Later on you can, should you wish, put logic, logging etc in the property without breaking either source or binary compatibility - but more importantly you're saying what your type is willing to do, rather than how it's going to do it.
I have an article giving more benefits of using properties instead of public fields.
In C# 3 you can make all of this a lot simpler with automatically implemented properties:
public class Foo
{
public string[] WorkID { get; private set; }
}
At that point you still have a public getter and a private setter, but the backing field (and property implementation) is generated for you behind the scenes. At any point you can change this to a "normal" fully-implemented property with a backing field, and you'll still have binary and source compatibility. (Compatibility of serialized objects is a different matter, mind you.)
Additionally, in this case you can't mirror the behaviour you want (the ability to read the value publicly but write it privately) with a field - you could have a readonly field, but then you could only write to it within the constructor. Personally I wish there were a similar shorthand for this:
public class Foo
{
private readonly int id;
public int Id { get { return id; } }
...
}
as I like immutable types, but that's a different matter.
In another different matter, it's generally not a good idea to expose arrays like this anyway - even though callers can't change which array WorkID refers to, they can change the contents of the array, which is probably not what you want.
In the example you've given you could get away without the property setter, just setting the field directly within the same class, but it would mean that if you ever wanted to add logging etc you'd have to find all those writes.
A property by itself doesn't provide anywhere to put the data - you need the field (m_workID) for storage, but it entirely correct to hide that behind a property for many, many reasons. In C# 3.0 you can reduce this to:
public string[] WorkID {get; private set;}
Which will do much of the same. Note that exposing an array itself may be problematic, as there is no mechanism for protecting data in an array - at least with an IList<string> you could (if needed) add extra code to sanity check things, or could make it immutable. I'm not saying this needs fixing, but it is something to watch.
In addition to the Object Oriented philosophy of data encapsulation, it helps when you need to do something every time your property is read/write.
You can have to perform a log, a validation, or any another method call later in your development.
If your property is public, you'll have to look around all your code to find and modify your code. And what if your code is used as a library by someone else ?
If your property is private with appropriate get/set methods, then you change the get/set and that's all.
You can use C# 3.0 auto properties feature to save time typing:
public class Foo
{
public string[] WorkID
{
get; private set;
}
}
In addition properties gives you lot of advantages in comparison to fields:
properties can be virtual
properties hide implementation details (not all properties are just trivial variable accessors)
properties can contain validation and logging code and raise change events
interfaces cannot contains fields but properties
A lot of times you only want to provide read access to a field. By using a property you can provide this access. As you mention you may want to perform operations before the field is accessed (lazy loading, e.g.). You have a lot of code in there that just isn't necessary anymore unless you're still working in .Net 2.0-.
my question is simple, is using the get set properties of C# considered good, better even than writing getter and setter methods? When you use these properties, don't you have to declare your class data members as public ? I ask this because my professor stated that data members should never be declared as public, as it is considered bad practice.
This....
class GetSetExample
{
public int someInt { get; set; }
}
vs This...
class NonGetSetExample
{
private int someInt;
}
Edit:
Thanks to all of you! All of your answers helped me out, and I appropriately up-voted your answers.
This:
class GetSetExample
{
public int someInt { get; set; }
}
is really the same as this:
class GetSetExample
{
private int _someInt;
public int someInt {
get { return _someInt; }
set { _someInt = value; }
}
}
The get; set; syntax is just a convenient shorthand for this that you can use when the getter and setter don't do anything special.
Thus, you are not exposing a public member, you are defining a private member and providing get/set methods to access it.
Yes, members should normally never be declared public in good design for several reasons. Think about OOP where you inherit the class later. Kind of hard to override a field. :-) Also it prevents you from keeping your internals from being accessed directly.
The simplistic get; set; design was introduced in C# 2.0. It's basically the same as declaring everything with a private member backing it (decompile it out in tool like Reflector and see).
public int someInt{get;set;}
is directly equal to
private int m_someInt;
public int someInt{
get { return m_someInt; }
set { m_someInt = value; }
}
The great part about having the simplified getter/setter is that when you want to fill in the implementation with a little bit more guts later, you do not break ABI compatibility.
Don't worry about getter/setters slowing down your code through indirection. The JIT has a thing called inlineing makes using the getter/setter just as efficient as direct field access.
Yes. Data members should be private and automatic properties allow it and give public access on right way.
But you should be careful. Understand the context is very important. In threaded application, update one property following an another related property can be harmful to consistency. In that case, a setter method updating the two private data members in a proper way makes more sense.
In your first example C# automatically generates the private backing fields so technically the data member is not declared as public only the getter/setter.
because with public data member , that data member can be changed or can be read out of class
and you cannot control read/write operation accessibility but with properties you can control
read/write stream for example consider this statement :
public MyVar{private get; public set;}
means value of MyVar can be changed only inside of class and can be read out of class(read privately and read publicly) and this is not possible with just public data members
In a "pure" object oriented approach, it is not considered OK to expose the state of your objects at all, and this appliese to properties as they are implemented in .NET and get_ set_ properteis of Java/EJB. The idea is that by exposing the state of your object, you are creating external dependencies to the internal data representation of your object. A pure object design reduces all interactions to messages with parameters.
Back to the real world: if you try to implement such a strict theoretical approach on the job, you will either be laughed out of the office or beaten to a pulp. Properties are immensely popular because they are a reasonable compromise between a pure object design and fully exposed private data.
It's quite reasonable, and your professor (without context) is wrong. But anyway, using "automatic properties", is fine, and you can do it whether they are public or private.
Though in my experience, whenever I use one, I almost inevitably end up needing to write some logic in there, and hence can't use the auto props.
your professor was quite right.
Consider this trivial example of why "getters" should be avoided: There may be 1,000 calls to a getX() method in your program, and every one of those calls assumes that the return value is a particular type. The return value of getX() may be sotred in a local variable, for example, and the variable type must match the return-value type. If you need to change the way that the object is implemented in such a way that the type of X changes, you're in deep trouble. If X used to be an int, but now has to be a long, you'll now get 1,000 compile errors. If you fix the problem incorrectly by casting the return value to int, the code will compile cleanly but won't work. (The return value may be truncated.) You have to modify the code surrounding every one of those 1,000 calls to compensate for the change. I, at least, don't want to do that much work.
Holub On Patterns