getters and setters for superclasses? - c#

Is it still standard practice to provide getters and setters in the superclass, for subclasses to access the attributes of the superclass (in other words set the attributes as private)? Or should the attributes be accessed directly (declaring the attributes as protected) by the subclasses?
Is there a standard convention?

It depends entirely on what you want to accomplish.
If you want the superclass attributes to be accessible without being inherited, then you need to declare public getters and setters.
If, on the other hand, you want the members to be accessible only if the superclass is inherited, then you need to declare protected members.
If you want some form of validation, you need getters and setters. This protects the superclass from inadvertent corruption, even if it is inherited.

When I was in university doing my CS degree we were told don't do getters and setters in second year and do them in fifth year.
My personal preference, is to use getters and setters where absolutely required only and to never ever have public variables.

Check the top two answers to this question:
Are getters and setters poor design? Contradictory advice seen
Not a great answer to your question but you are obviously concerned with coding good OO so you should give them some thought.

In Java I prefer to make all my fields private. If I really need to expose something, I create a separate, protected getter for the field. (For example if the interface I'm implementing requires a broader return type than what I want to pass between the different levels of implementations.)
With tools that can generate getters/setters at a click of the mouse, I never felt the need to break encapsulation even between parent/child classes.

Speaking for the C# side, if you have a data member (field or property) that is not public, but is useful to child classes and should be available both to read and write, then declare that member as protected.
If the member should be read by subclasses but not written, you can define the member as a property that is protected but with a private setter:
//as of C# 3.0 this can also be an auto-property
private string myValue;
protected string MyValue
{
get{return myValue;}
private set{myValue = value;}
}
This makes MyValue completely hidden from classes outside the inheritance hierarchy, and read-only to subclasses; only the superclass itself can set the value. This would be equivalent to a private field with a protected getter method and a private setter method.
In general, as the designer of the superclass, it's up to you to define how subclasses should be able to use what you provide. If you make something protected, assume subclasses will do anything that "protected" allows them to do. Both C# and Java have methods by which you can independently control the visibility of read and write access.

Seems that in C#, the standard practice is to use properties with get/set accessors.
In the simplified form you'll have:
public string Name { get; set; }
But you may have finer control over the access level, for example:
public string Name { get; protected set; }
Here you publicly expose the get method, but leave the set method to derived classes only.
One other benefit of using accessors instead of directly accessing a data member is that you could put a break point on a get/set method and see who executed the method.
This, however, is not possible with the { get; set; } trick. You'll have to write the whole expanded property form:
private string m_Name = string.Empty;
public string Name
{
get { return m_Name; } // Put a happy breakpoint here
set { m_Name = value; } // or here.
}
It will be safe to reflect the same concept for Java.

Related

Explicit interface implementaion with second implementation

I was tracking down a bug and I found this in the Avalon Dock 2.0 source code:
public abstract class LayoutContent : LayoutElement, /* ... */, ILayoutPreviousContainer
{
// ...
[XmlIgnore]
string ILayoutPreviousContainer.PreviousContainerId
{
get;
set;
}
protected string PreviousContainerId
{
get { return ((ILayoutPreviousContainer)this).PreviousContainerId; }
set { ((ILayoutPreviousContainer)this).PreviousContainerId = value; }
}
}
ILayoutPreviousContainer has a member string PreviousContainerId { get; set; }.
What does this pattern accomplish? I understand that you could not get/set the PreviousContainerId from outside the inheritance subtree unless you first cast the LayoutContent to an ILayoutPreviousContainer. But I don't understand why you would want this.
Upon doing research about this pattern, I found this SO post which confused me some more. By implementing it this way, it is seemingly similar to having just a virtual property that would be implemented in a convoluted way:
public class SpecificLayoutContent : LayoutContent, ILayoutPreviousContainer
{
// override LayoutContent.PreviousContainerId since it casts 'this' to an ILayoutPreviousContainer
// which will then call this property
string ILayoutPreviousContainer.PreviousContainerId{ /* ... */ }
}
Am I missing something?
A protected property cannot implement an interface property, implicitly or explicitly. So if you want easy direct access from this class and derived classes, you want one protected property and another "hidden" property which explicitly implements the interface.
Looking at your example, one could consider switching roles of the two properties, such that the protected one was an auto-property, and interface-implementing one was referring to the auto-property (and not the other way around).
What alternative do you see? One could stick to a single property if that was made public (so implementing implicitly), but in that case the property would be exposed much more which is apparently not desired.
ILayoutPreviousContainer seems to be an internal interface. So as far as outside users of SpecificLayoutControl are concerned, the interface doesn't exist, and there is just the PreviousContainerId property defined on the class.
The usual rules apply for whether that should be protected or public. I won't expand on that, since it doesn't seem like that's what your question is about.
The class's authors have decided that the property should be protected. However, if it is protected, it cannot implement the interface's property, and although external users don't see that interface, internally that interface is required elsewhere. So, they implemented it like this, where one property merely forwards to the other.

Why static automatic properties is only useful in which the getter is public and setter is private

In book <<c# in depth>>, I have read a sentence "The only scenario in which I can see static automatic properties being useful is where the getter is public and setter is private, and the setter is only called whithin the type initializer". I am not sure what's Jon skeet suggested here.
In my opinion both getter and setter can be used as private or public.
The point is that static members should generally be thread-safe... and automatically-implemented properties aren't thread-safe, in terms of any guarantee that a value written by one thread will be immediately visible to another. You can't change that within an automatic property, so the only times a static automatic property are useful are:
If you don't care about thread safety
If the setter is private and only set from the static initializer (which is thread-safe automatically). In this case I'd usually just have a readonly static variable and a getter-only property to expose it anyway.
To be honest, settable static properties are pretty unusual (in well-designed code) to start with, even without the thread safety aspect.
Because auto-properties break encapsulation, which is a basic priciple of OOP. You cannot encapsulate data with auto-properties. The job of encapsulation is to ensure, that your object stays in a consistent state. If you are using auto-properties like this:
public IFoo Foo { get; set; }
you have no option to validate the value in the setter. Setting the property to null is possible without giving you any chance to even notice or forbid it. This may be what you want, but it probably makes it easier to use your interface wrong. This is why the previously mentioned blog-post states
It's a code smell, not an anti-pattern.
You should prefer this style:
public IFoo Foo { get; private set; }
because then you're given the possibility to inject your reference together with the constructor.
public Bar(IFoo foo)
{
if (foo == null)
throw new ArgumentNullException("Foo");
this.Foo = foo;
}
This makes it easier for clients to use your object the right way. I really suggest reading the previously mentioned blog-post. It describes very well why you should prefer keeping the setter private.

Why are C# auto-implemented properties public?

In all the examples I see, C# auto-implemented properties are made public, even in the MSDN documentation examples. Coming from a C++ background, I've always been taught that it is a good idea to make member data private, unless there is a good reason not to.
Why is the following never used (at least I've never seen it):
private Name { get; set; }
I've looked through the MSDN documentation and read several tutorials regarding auto-implemented properties but there does not seem to be any advice on their pros and cons and when they should be avoided. Do auto-implemented properties compromise program security? Are there situations where they should be avoided? In which situations are they the ideal choice?
Thanks.
You are correct that auto-implemented properties that simply expose a backing field are not much of a gain over a public field.
As Alan Kay said:
But most people who use setters simply use them to simulate direct assignments to interior variables, and this violates the spirit and intent of real OOP.
However, there is an advantage to an auto-implemented property over a public field, and that is that it's a non-breaking change to later revise the implementation. If you have a public field, and code outside your class manipulates that public field, you can't change it to a private field in a future version of the class, or else any other code that touches that field will have to be recompiled. By contrast, once you have a public property, you can revise the implementation of that property in a future version, and client classes can continue using it with zero changes.
So it's useful to use auto-implemented properties for properties that right now would have trivial getter and setter implementations, but that may have more complex implementations in the future.
Have you asked yourself why you've always been taught that it's a good idea to make members private?
It's because (among other reasons) fields are an implementation detail. The detail of "storing data in memory", and it is an unimportant detail to any object which wishes to retrieve or set the data. Another class doesn't need to care whether he can access some memory slot somewhere - he just wants an interface for which he can pass or retrieve a value - there are the getters and setters, or properties.
Having decoupled the property from the detail of "memory based storage", we're given a large number of advantages. Primarily - we can override the behaviour of getting and setting without upsetting any code which uses the property. We can also use the property as an abstraction for retrieving data over a number of different implementations. That becomes extremely useful for testing/mocking behaviour, and providing alternative storage. If other classes depend on the implementation detail of "memory storage", you are not going to be able to change the behaviour of your class without breaking all those.
Before auto properties came along, we would typically store a field and create a getter and setter to encapsulate it for the reasons described above. An auto property automates that for us. We might write code that commonly uses fields everywhere in code, but we do so holding the idea of "I'll do this as a field for now, but that may be subject to change later if the criteria change".
Since a class knows about it's own implementation, it's usually a pointless endeavour to create private auto properties, you're not hiding the detail that's already known. Protected auto properties can be useful if you need to expose to subclasses.
As for situations where they should be avoided: When you want readonly data. (data which will not change after the object is constructed). Auto-properties lack the syntax to allow you to create an automated property that's backed by readonly data.
Auto implemented properties have a private backing member. Compiler adds them for you. Its just a shortcut for
private int _aMember;
public int AMember {
get {return _aMember;}
set {_aMember = value;}
}
You use them you have no real logic in the getter/setter (other than needing to encapsulate).
Auto-implemented properties are just a shortcut for a common pattern. Any time you would have a private member with corresponding get and set functions in C++, you can accomplish the same thing with an auto property in C#. They don't introduce any different best practices or security issues.
Auto-implemented properties with public getters and setters are shortcuts for private backing fields with trivial get and set implementations.
You should think of them as akin to private fields with public get and set methods in C++. That's a role for properties on C#.
Properties aren't "member" data. They are kind of your
const T& field() const;
T& field();
type of things, or get and set methods, i.e. they are accessors.
If you don't need member exposed, don't express them in properties.
In the case of autogenerated ones, you can simply (as of C# 2.0 afaik) write
int SomeProperty { get; private set; }

Why have empty get set properties instead of using a public member variable? [duplicate]

This question already has answers here:
Closed 13 years ago.
Possible Duplicate:
C#: Public Fields versus Automatic Properties
Duplicate? I think not:
This question is not the same as "Why
use properties instead of public
field". A property with a specified
getter and setter is far different
than a public field. My question was,
is a property WITHOUT a getter and
setter, any different.
With the somewhat recent ability to have empty getters and setters, what is the benefit of using them instead of just declaring a public member variable?
Example:
public string MyProperty
{
get;
set;
}
versus:
public string MyProperty;
One word: inheritance.
Properties are inheritable while fields are not. You can use fields in an inherited class, but not alter their behavior by making them virtual.
Like so:
public class Foo {
public virtual int MyField = 1; // Nope, this can't
public virtual int Bar {get; set; }
}
public class MyDerive : Foo {
public override MyField; // Nope, this can't
public override int Bar {
get {
//do something;
}
set; }
}
Edit: Besides the fact of inheritance, the points pointed out in the other answers (like visibility) are also a huge benefit of properties over fields.
One thing you can do with properties that you can't do with fields is limit visibility for either setter or getter:
public string MyProperty { get; private set; }
Something I use quite a lot.
And something (more powerful) you can't do with fields is define them inside an interface. Suppose you want an interface that requires implementing classes to have a certain property:
public interface MyInterface
{
string MyProperty { get; }
}
Note that you do not need to have a setter here. It is entirely up to implementing classes to determine how they should set MyProperty.
Fields cannot be exposed in interfaces. And the auto-property can be changed into a "normal" property at any time if needed, without having the signature and interface of the class changing.
In general, fields are considered to be an implementation detail, which may change in future versions of the code. Therefore, you should expose data via methods and properties, leaving the way open for internal changes in the future which do not affect code using the class.
A property gives you several advantages over a simple public field:
you can control whether the property is read-only, write-only, or read/write
you can hide the actual implementation (maybe in the setter you want to do more than just setting a value)
when using databinding (e.g. in ASP.NET), you'll have to use properties (does not work with fields)
Tight coupling comes to mind. Using public fields removes the layer of abstraction made available by the use of properties. Using private fields and properties hides the implementation from other classes and helps to insulate them (external classes) whenever a change is necessary.
Also, keep in mind that you are referring to auto-implemented properties which causes the compiler to create the backing field for you instead of you having to manually create the backing (private) field for each property on your class.
The idea is to manage the values inside of the object, state, avoiding corruption and misuse by calling code.
You can flag properties with attributes that aren't available on members. There are attributes that only apply to fields in the DataContract namespace that affects serialization, the attribute can't be applied to fields, etc.
Admittedly, there isn't anything technically preventing these attributes from being used on members, but nonetheless they only work on properties.

public variables vs private variables with accessors

Has anyone else seen people do this:
private string _name;
public string Name{ get{ return _name; } set{ _name = value;}}
I understand using accessors if you are going to exercise some sort of control over how it gets set or perform some sort of function on it when there is a get. But if you are just going to do this, why not just make the variable public to begin with? Am I missing something?
If you make the member a public field, then you can't later refactor it into a property without changing the interface to your class. If you expose it as a property from the very beginning, you can make whatever changes to the property accessor functions that you need and the class's interface remains unchanged.
Note that as of C# 3.0, you can implement a property without creating a backing field, e.g.:
public string Name { get; set; }
This removes what is pretty much the only justification for not implementing public fields as properties in the first place.
If you define a public interface with a property in assembly A, you could then use this interface in assembly B.
Now, you can change the property's implementation (maybe fetching the value from a database instead of storing it in a field). Then you can recompile assembly A, and replace an older one. Assembly B would carry on fine because the interface wouldn't have changed.
However, if you'd started off initially with a public field, and decided this wasn't suitable and wanted to change the implementation and to do that you needed to convert it to a property, then this would mean you'd have to change assembly A's public interface. Any clients of that interface (including assembly B) would also have to be recompiled and replaced to be able to work with this new interface.
So, you're better off starting with a property initially. This encapsulates the implementation of the property, leaving you free to change it in the future without having to worry what clients (including assembly B) are already out in the world using assembly A. Because, if there are any clients already out in the world making use of assembly A, changing the interface would break all clients. If they're used by another team in your company, or another company, then they are going to be not happy if you break their assemblies by changing the interface of yours!
The idea is that if you use accessors, the underlying implementation can be changed without changing the API. For example, if you decide that when you set the name, you also need to update a text box, or another variable, none of your client code would have to change.
It might be worth noting that DataBinding in .NET also refuses to work off public fields and demands properties. So that might be another reason.
Good programming practice. This is a very common pattern that fits with OO design methodologies. By exposing a public field you expose the internals of how that data is being stored. Using a public property instead allows you more flexibility to change the way the data is stored internally and not break the public interface. It also allows you more control over what happens when the data is accessed (lazy initialization, null checks, etc.)
Variables are part of the implementation of a class. Properties more logically represent the interface to it. With C# 3.0, automatically implemented properties make this a breeze to do from the start.
I've written more thoughts on this, including the various ways in which changing from a variable to a property breaks not just binary compatibility but also source compatibility, in an article on the topic.
Preparation. You never know when you'll want to removed the set accessor down the road, perform additional operations in the setter, or change the data source for the get.
Publicly accessible members should typically be methods and not fields. It's just good practice, and that practice helps you ensure that the encapsulated state of your objects is always under your control.
For encapsulation, it is not recommended to use public fields.
http://my.safaribooksonline.com/9780321578815/ch05lev1sec5?displaygrbooks=0
As Chris Anderson said later in this book, it would be ideal would be if the caller were blind to the difference of field vs. property.
To retain a high degree of extensibility without the pain of re-compiling all your assemblies, you want to use public properties as accessors. By following a "contract" or a defined mechanism that describes how your objects will exchange data a set of rules will be put in place. This contract is enforced with an interface and fulfilled by the getters and setters of your class that inherits this interface.
Later on, should you create additional classes from that interface, you have flexibility of adhering to the contract with the use of the properties, but since you are providing the data via the getters and setters, the implementation or process of assembling data can anything you want, as along as it returns the type that the "contract" expects.

Categories