I am using an instance of a private class as the state object supplied to a stream.BeginRead operation. (The class is private to my main stream reading/writing class.)
public class MainClass
{
// ...
private class ResponseState
{
public IResponse response;
public Stream stream;
public byte[] buffer = new byte[1024];
}
}
Access to the class is via the fields directly. Should I really be providing access to the class via properties in this case, even though it is only to be used for holding state?
Interested to know what others do.
It's not required by the C# language, but it is good practice never to expose a field directly for maintainability reasons - it is suggested to use a property instead.
See StyleCop SA1401: FieldsMustBePrivate.
TypeName - FieldsMustBePrivate
CheckId - SA1401
Category - Maintainability Rules
Cause
A field within a C# class has an access modifier other than private.
Rule Description
A violation of this rule occurs whenever a field in a class is given non-private access. For maintainability reasons, properties should always be used as the mechanism for exposing fields outside of a class, and fields should always be declared with private access. This allows the internal implementation of the property to change over time without changing the interface of the class.
Fields located within C# structs are allowed to have any access level.
How to Fix Violations
To fix a violation of this rule, make the field private and add a property to expose the field outside of the class.
If your class is purely state for the containing class then you could consider placing the members directly inside the class that uses them. If your class is more than just state (and I suspect it is) then it should follow the usual maintainability rules.
I would - encapsulation is useful inside the class as well as outside the class. By funneling all access to a member through a well know interface (i.e. the property) you are giving yourself the flexibility to add logic around that access later without changing calling code.
It may seem like overkill but honestly, given automatically implemented properties, it is so easy to declare a property that you may as well go ahead and use one to give yourself maximum flexibility.
In my organization, when a class was private or internal, and it's a entity class, we used public fields to access it.
However, since C# 3.0 we use automatic properties, so we always use properties to access private fields.
Anyway, the effect is the same, in our case it was to do the code more readable.
Best practice is to use properties for every member accessible by other types. Automatic properties at C# 3.0 makes this quite easy.
I have just done some reading on this a week or two ago. There are the two camps. One the majority say you must wrap in the property because my teacher said so and everyone else does it. They say that is easier to add extra logic to a property or more maintainable and some other weak reasons. The other camp, call themselves "the true OO guys" tend to be along the line of if you use properties at all you are doing it wrong (with some exceptions of course). Your case would be the exception as far as I can tell. Actually, thinking about it, they would probably still say you are doing it wrong :) Just cant win. Anyway, they also say if you are going to use them don't bother wrapping unless you need the extra logic in your setters and getters. Why slow your program down for nothing. (apparently they can measure how slow too).
I tend to use properties over fields as I do a lot of MVVM and need to implement INotifyPropertyChanged which requires them. In your case I wouldn't worry about wrapping them in properties just makes for pointless fat. But if it was in a class that needed a property then I would wrap them to keep things similar in that class.
If after all that you didn't wrap them, and needed to later, it's a right click refactor->encapsulate field to wrap a property if you have Resharper.
Related
I know this is a largely debated question in stackoverflow (as e.g. in Should I use public or private variables?), but I haven'd been able to find a suitable answer to my doubt.
Shortly said, OO coding etiquette mandates that members of a class be kept private or that getters/setters be used as an alternative.
However, data binding in WPF will not succeed unless the bound class members are public. So, what's the best way out here? Shall I accept declaring public members as an ugly but necessary compromise?
Data binding is normally used on properties, not fields, so that does not contradict the general principle that fields should be kept private.
The sentence "that members of a class be kept private" is, as such, not correct. Fields should be kept private. The term "members" means fields as well as methods or properties. And of course, it is perfectly sensible to have methods or properties that are public.
In Class A(What will output the List if it is not empty):
private List<int> _myList = new List<int>
public List<int> MyList {get{return _myList;} set{_myList = value;}}
In Class B:
public bool MyClassBMethod(stuff)
{
//stuff
try{
something
}
catch(Exception){
ClassA.MyList.Add(stuff);
return false;
}
return true;
}
Is editing a List like this bad practice? Or is it okay?
Edit: I am only adding to the list as such when my method needs to return something else(bool, object, string, etc).
In general, a class should be responsible for managing its own internal state. By giving full public access to a member like this, you are basically saying that Class A is giving up responsibility of that part of its state. It cannot make assumptions about what _myList contains because anyone could change that at any time.
Whether that's good or not depends on what your intent is, but it certainly runs contrary to the ideas of decoupling and encapsulation. Again, whether you want decoupling and encapsulation is up to you.
A better question would be to determine what sort of decoupling between classes A and B would be most beneficial to your design, and then you'd be able to decide what member to expose and how.
You shouldn't normally do that.
You are exposing a very large interface to the clients of your class, making it difficult to test that your class works in all situations. What happens if someone removes values when you aren't expecting it? Or what if they add a value that is out of range? You can't validate it at the time they call the method on your List, so your class might just suddenly break at some later point in time when it might be difficult to trace where the bad data came from.
It's better to have an Add method on your class that calls the list's Add, and keep the list private. Then you can control what your clients do, and only expose the functionality they need to use (and that you've tested).
This is a pretty common practice. What is not so common is to have the set public. Make it private, initialize the list on the A constuctor and you're all set.
public ObservableCollection<int> MyPublicList {get; private set;}
WPF is full of declarations like this one.
It depends on whether you care about whether the list is exposed or not. By exposing & accessing a public, concrete type, you are exposing an implementation detail and increasing the coupling between the class and its consumers. You are also limiting ClassA's opportunities to enforce data consistency, since its implementations details are no longer encapsulated properly.
Sometimes, this is perfectly acceptable, sometimes, it is not.
I'd say it's acceptable in cases where the object model is dumb. By dumb, I mean that it just contains data. Situations like this often occur when parsing JSON / XML to objects -- things are structured to mirror the data, and behaviour doesn't really matter much, as there's very little of it. It's also more acceptable if you're just hacking away in a small codebase and/or there is limited scope for change, or there is very little behaviour involved.
I'd usually avoid it, though.
Firstly, imagine that the items you add to ClassA's list must be prime numbers. You could easily enforce this check if you write an AddItem() method, but it becomes much harder to do effectively if the list is publicly exposed.
Secondly, suppose you decide to change the list to be a dictionary. You will now likely break the calling code sites (ClassB, for one), as they were previously relying on an implementation detail of ClassA. If, instead, you created methods called AddItem() and RemoveItem() or similar for ClassA, ClassB wouldn't care whether the internal implementation is a Set, Dictionary or List etc, nor would it break when the changes are made.
Guidelines surrounding 'Dotting into things' (like blah.List[3].GetProduct(3).Reviews.First()) has a name: The Law of Demeter.
The salient point of The Law of Demeter is:
The fundamental notion is that a given object should assume as little
as possible about the structure or properties of anything else
(including its subcomponents).
You often have to write more code, but it insulates against change.
As always, it depends. If the list is intended to be edited outside of the class (it is part of the interface for that class) and all of the regular list operations are allowed, it is OK. If only a subset of operations are allowed then you should't use it like this - use a custom list (or wrapper around your list) that enforces all of the constraints. For example, if the list must be read-only outside of the class then you could provide a ReadOnlyCollection wrapper outside of the class. It all comes down to enforcing data integrity.
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; }
I got a requirement in my project to add another property to some class.
Now I want to avoid changing the class because I figured it shouldn't be aware that he has this property (this property only has significance in the context of this project).
The way I thought to accomplish this was (Please critic this because I wanna know if there are simpler ways of doing this)
Adding a new singleton class that has a mapping between objects of my class and the type of the property I wanted to add
adding in this class an extension method (extension property?) to access the mapping and fetch the property.
Is there a simpler alternative?
Is this just unnecessary complexity? Maybe I should just add a new property to my class?
Thanks!
The design you've described is actually the one used by Microsoft to implement the DependencyProperty system and, in particular, Attached Properties, though in the greater context of a binding framework. That said, using a dictionary with 'attached' data is a very typical solution when you need to tag a class with additional context for a particular use, but don't want to modify the class.
Why do you say "not inheritance"? Surely the way to do this, if you don't want to alter the original class, would be to inherit from the original class and then add your property to the derived class?
BTW, there are only extension methods, not properties, so you can't do it via property.
I would suggest the DECORATOR pattern. I know you say you don't want to use inheritence, but sometimes it's cleaner to do so. The pattern only uses inheritance to define the interface.
An extension method makes sense and it's also relatively simple.
[visibility] [type] [methodName](this [class to extend] c, ... more args if necessary)
{
....
}
Adding a property doesn't break the class's interactions with existing clients, so that really seems the "simplest" approach.
More important, though, is the function of the new property. Is it logically part of the existing class? Change the class. If not, then an extension method might be preferable, but the problem then becomes the visibility of the extension method, and scope of its clients.
As always, complexity is the enemy. In this case, it sounds as though the singleton is a very complex solution, and the extension method is hit-and-miss, depending on scope and visilbity issues. Changing the class is simplest, and will probably make long-term maintenance much easier.
UPDATE: Note that extension methods are static, and that makes it pretty difficult for the extension method to hold data of any time, as a property would be exptected to do.
SECOND UPDATE: If you have access to the source for the class, consider making it a partial class, and put your new property in a separate file, but part of the same partial class. This keeps it separate from the main body of the class for maintenance purposes, and will work with most ORMs. However, there is a restriction that the partial class members have to be in a single assembly.
Define a Nullable values with their Properties(while the Property has significance only for this project)
your major problem is that you don't want to change the class itself because this requirement is ONLY for 1 project (build), i think you are considering SOLID priniciples, one of these principles is OCP (Open-Closed Principle), that is,
your Entity must be open for extension
but closed for modification
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.