Just wondering...
Is there any reasons not to use protected properties?
I mean instead of using this:
public abstract class Foo
{
protected Bar { get; private set; }
}
to use this one:
public abstract class Foo
{
private Bar _bar;
protected Foo(Bar bar)
{
_bar = bar;
}
protected GetBar()
{
return _bar;
}
}
I don't see any reason why you would use a GetXXX() method instead of a property regardless of it's modifiers.
Since you tagged this question with C# tag, I strictly recommend using the first approach. That is what properties are for.
Use a method only when value returned by it can be different every time you call it regardless of it's state. For example, DateTime.Now was a mistake and should have been a method.
For more details refer to Property Usage Guidelines on MSDN. On a side note, it's surprising how they haven't had a need to change it since Framework 1.1.
A few more reasons to use properties instead of methods:
Data binding can only see properties
You can use read only or write only semantics.
Only if you have non-writable or non-readable Attributes inside the class
The question is not really about protected it has more with: why should I use properties?
Propeties are logically equivalent with Getter/Setter method pairs, whatever you can do with a with a Name {get{} \ set{}} you can do with a GetName() \ SetName() pair and vice versa, especially as C# has getter and setter accessors, so we can play with the accessibility too.
But, there are some folks that feel that public (or protected) properties are a bit like cheating from an OOP perspective, especially if all that the property does is just expose a backing field. After all person.Name = "SWeko" seems like it changes the state of the object externally, while person.SetName("SWeko") merely tells the object that it needs to change it's state. And from a purely theoretic standpoint I think that those objections have merit.
However, not all of us have the luxury of living in ivory towers, so the concept of properties is really usefull, as it's more readable, less error prone, and IMHO, closer to the real world model. It also provides us with a kind of dichotomy, when i write something like this:
person.Name = "SWeko";
person.Work();
I expect that the first line will a fast assignment, and will not have side-effects, while I expect that the second line will do something more, and probably affect the inner state of the object. When I use Getter and Setter method, no such distiction is immediately obvious:
person.SetName("SWeko");
person.Work();
Related
In C# there exists a type of member that is called a Property. This allows you to easily and simply define a private field and provide simple or complex getters and setters while saving space by not having to define whole methods. Java does not have anything like this, and from what I can see, the general consensus has been to suck it up and define complete getter and setter methods for private variables.
Currently, I have been toying with the following class:
public class Property<T> {
private T value = null;
public Property(){}
public Property(T initialValue){
value = initialValue;
}
public T get(){
return value;
}
public void set(T newValue){
value = newValue;
}
}
With this implementation, you can define simple properties that only require getters and setters:
final Property<String> name = new Property<>("Dog");
Or more advanced options like the one that MSDN provides for C#:
...
public double seconds;
public final Property<Double> Hours = new Property<Double>(){
#Override
public Double get() {
return seconds/3600;
}
#Override
public void set(Double newValue) {
seconds = newValue * 3600;
}
};
...
What would be the pros and cons of this solution?
The pros are largely obvious. I'll point out some that make it better than C#'s properties:
The backing field is tucked away so that you don't accidentally use it instead of the property. (but the downside is that you can't easily choose to use the backing field if you want)
Unlike C#'s auto-properties, you can choose to override only the get or set method, not both, e.g.
public Property<List<String>> MyList = new Property<List<String>>(){
#Override
public List<String> get() {
if (value == null)
value = new ArrayList<String>();
return value;
}
// set still works
};
There are cons, however:
It is not part of the Java language, or any common libraries, so it can be confusing for people who read your code (including yourself in the future).
You cannot change the visibility of the get and set methods: if the Property<T> can be accessed, you can both get and set the value.
If you don't make your Property field final, anyone that can access it can change it to their own Property implementation. This could be useful, but mostly would be a pain.
(this is a con shared with C#'s properties) You can't change the arguments that are passed to the get and set methods. E.g. you can't have a Property<MyType> with both a set(MyType) and a set(CompatibleType) method (unless you extend Property).
Using generics pervasively means that at run-time, (thanks to type erasure) you're using Object pervasively. This boxing/unboxing might make for a slight performance decrease (not noticeable in most apps) if you use primitives (e.g. using double vs Property<Double>).
By the way, Scala is a language that runs on the JVM that includes properties as a native feature, and interoperates with Java's version of properties (getters/setters). You might want to look into that, since basically someone else already hacked the Java language for you. =)
All in all, I'd say you shouldn't try to make Java have properties. When in Rome, do as the Romans do. If you don't like how the Romans do it, move down the street (Scala) or across the country (C#).
So the complete syntax, say for name, would now be:
theObject.name.set("new name");
The point is, how are you accessing that name object? Is it public / protected Then it could be overridden. Is it private? Then you can't change it outside the class anyways.
The solution you've proposed only works if you already have access to the object, at which point you don't need the solution.
The pros of this solution (your anonymous inner class) is that, if you are not needing to implement this anywhere else, it saves you from writing an entire extra class just for this one situation.
The con of this solution is that later you may want to implement it elsewhere, and then you'd want to refactor your code to extract the implementation of Property<Double> into its own class to avoid repeating yourself.
I'd say, if you're pretty sure you're not going to need this implementation anywhere else (I'm guessing you won't), just go ahead with the later solution of an anonymous inner class. It's a good one.
I was wondering what's considered the C# best practice, private/protected members with public getters, or public getters with private/protected setters?
public int PublicGetPrivateSetter
{
get;
private set;
}
private int _privateMember;
public int PublicGetPrivateMember
{
get { return _privateMember; }
}
I feel that using a private member is more explicit in your code that it's a private setter (using naming conventions).
On the other hand using private setters gives you an option to use virtual (protected), write less code, has less room for mistakes and can give you an option to add a side effect later on if you need to.
I couldn't find what's considered a best practice, or even if one is considered better than the other. From what I've seen usually 80% of the time (from code that I'VE seen) people DONT use private setters... I'm not sure if this is because people don't know about private setters, or because it's considered better to actually use private members.
EDIT:
Indeed, other benefits which I forgot about when using private members is default values and the use of readonly.
I prefer to use auto-implemented properties unless the default implementation doesn't do what I want. So in this case, since the auto-implemented property does what you need, just use that:
public int Foo { get; private set; }
However another situation is if you want to make the field readonly (meaning that the only place where the field can be set is in the constructor). Then you need to define the backing field and mark it readonly as this isn't supported by auto-implemented properties:
private readonly int foo;
public int Foo
{
get { return foo; }
}
There is no best practice I'm aware of. I know automatic properties were mainly to make things easier even more easier for code generation and LINQ related stuff.
For me, I start with automatic properties and refactor later if needed. Depending on the need I may change something to virtual or protected as you mentioned, or maybe refactor to use a variable (When I want to refactor the set accessor to have some logic.
Its the same thing. In the first example, the compiler generates the backing store. In the second, you generated the backing store. Since the implementation is internal to the class, refactoring one into the other is not a big deal. Tools like Resharper make that trivial. The reason you probably haven't seen private setters that much is that its a C# 3.0 feature.
There's nothing wrong with private setters. In most case, it's used with auto properties to make the property readonly outside the object's scope.
Conceptualy speaking, it doesn't change anything. It's mostly a matter of taste.
I personnally use the private setter because I'm lazy and use the propg snippet a lot. (propg tab tab)
Also, most of the time I end up setting dirty flags and binding events to those properties, so I might as well do a part of the work right now. If you ever need to add a setter later, it's much easier if the code is written without using the member behind since the beggining as it will be less code to change.
There is no good answer to this question. the best pratice is to follow our compagnie nomenclature and if your alone then the way you prefer
In my opinion there is no best practice and very little (if any) difference in the resulting compiled code, it really just depends on your needs or own likes/dislikes. If you're following your group's naming standards and meeting requirements (e.g. don't need to propagate a change notification) then it shouldn't matter.
An advantage of private fields is that you can define a default value in the same place as your declaration. In an auto-implemented property you'll have do define the default in the constructor if it's not null or the type's default value.
However, I still like private setters. But we usually don't use auto-implemented properties since our setters usually have a richer functionality - e.g. property update notifications, logging, etc.
If I have a simple class setup like this:
class MyClass
{
private string _myName = string.Empty;
public string MyName
{
get
{
return _myName;
}
}
public void DoSomething()
{
// Get the name...
string name = string.Empty;
name = _myName;
// OR
name = MyName;
// ...and do something with it...
}
}
Which should I use, the public property, or the data member?
Obviously, in this example it doesn't make a difference, since they both just reference the same variable. But what about real world uses of Public Properties?
In general, do Public Properties perform very little, in which case it is OK to call them? Or do people put a lot of functionality into their Public Properties that should not be called by internal class references?
I saw something in another post about NOT putting lots of functionality into Properties, since examining them in the Debugger can perform unexpected results. Is that true?
Use the property - any logic that may be encapsulated within the setters and getters ought to apply, even within the class itself. If there is no logic within the getters and setters it is still not safe to use the fields themselves because if at any point you wish to add logic around the access to those fields you will have to refactor much more.
I believe that you should reference the property as a general practice. While in this particular example it really doesn't make much of a difference, the get/set accessors offer the ability to do a bit more work when grabbing a property. For example, many of our property "get" accessors perform some lookup within a more complex data structure or set default values if nothing has been defined. So that the rest of the class can take advantage of this logic, we make a habit of using the properties. Just so we don't have to think too hard about it, we try to generalize the practice.
There may be instances in which we want to directly access the underlying data member, but then that is a conscious decision with a specific reason and it tends to be the exception.
I prefer properties because they easily handle read-only situations and it's easy to wrap them with any basic validation you might need to do.
If I'm just returning the value of the internal variable, I make the variable public - there's no harm to doing so. I've always used Public Properties when I want to do something in response to either a viewing or a changing of the value - ie, write it to a database, set something else too (as in the second part of your example).
The question you have to ask is whether you want what happens inside your class to trigger these events. If you do, the same way an external caller would, then access the values via the property. If you just want to read the value, use the internal variable.
To answer your question, there's no harm to doing it either way - just consideration of the potential side-effects.
E.g. which way is better
class Foo {
private string _Bar ;
Foo ( string bar)
{
_Bar = bar ;
}
public string Bar
{
get { return _Bar ; //more logic here
}
set { _Bar = value ; //more logic could be added
}
}
}
OR
class Foo {
private string _Bar ;
Foo ( string bar)
{
this.Bar = bar ;
}
public string Bar {
get { return _Bar ; //more logic could be added }
set { _Bar = value ; //more logic could be added }}
}
Edit: I know that the latter allows to put some more logic in it , yet is it justifiable to use it because of it ...
Whichever way makes sense for the class; there is no "best practice".
Sometimes you might want to ensure that you only perform the same operations the property could; in which case it makes sense to use the property.
Sometimes you want to do things that can only be done in the constructor which violate the things you can do via the property post-construction, in which case it makes sense to use the field.
It depends.
I prefer using the properties, when there are no side effects. There are times, however, when setting a property has other side effects, such as event notification, potentially unnecessary (at this point) validation, etc. In those cases, setting the backing field directly is a better option.
It depends, if you need the logic in the public property to be executed, use that method. If you are just doing a straight assignment, then assigning to the private member is fine.
I often use the properties, as it allows me to only write my validation in one place (the property setter). It helps avoid duplicate code.
public class Foo
{
private string _Bar = String.Empty;
public string Bar
{
get { return _Bar; }
set
{
if (value == null)
throw new ArgumentNullException("Bar");
_Bar = value;
}
}
public Foo(string bar)
{
Bar = bar;
}
}
Please read this excellent blog post by Eric Lippert: Automatic vs Explicit Properties :
Here's a question I got from a C# user
last year, a question I get fairly
frequently:
User: With “regular” explicit properties, I tend to use the private
backing field directly from within the
class. Of course, with an automatic
property, you can’t do this. My
concern is that in the future, if I
decide I need an explicit property for
whatever reason, I’m left with the
choice of changing the class
implementation to use the new private
field, or continue going through the
property. I’m not sure what the right
thing to do in this case is.
You say “for whatever reason”, and
that's key. The answer to your
question will depend entirely upon
what the reason was that motivated the
change.
If the reason that motivated the
change from automatically implemented
property to explicitly implemented
property was to change the semantics
of the property then you should
evaluate whether the desired semantics
when accessing the property from
within the class are identical to or
different from the desired semantics
when accessing the property from
outside the class. [emphasis mine]
Your example is a bit too simple, but your comment "//more logic could be added" alludes to the possibility that the set property could be more complex than a simple assignment to a private variable.
Don't repeat the same logic in the constructor if you have already coded the same logic in the property set. This would be unnecessary duplicate code, and could be error prone when the logic needs to change and is a pain in the neck for a developer in the future who has to maintain your code.
If your set property has some side-effect that would be unwanted/unneeded in the constructor like event notification then you should refactor the common code to its own method. The constructor and set property can both call this method.
You're going to get a lot of "it depends" answers because, well, it depends. Some of the reason for that is going to be personal preference (often determined by past experience where something was hard to maintain or buggy). Some of the reason it that every situation is different, and while there is certainly a lot of common patterns and tasks we implement with code there always needs to be the possibility of not following the norm to be creative or innovative in your coding solutions to your problem. Remember we don't program code, we program solutions using code as tool.
I'll put some flesh on my "it depends" answer: you're trying to find a balance between making sure that the internal state remains consistent, duplication of code, and performance.
I agree w/Adam P, because your current example is very simple it really doesn't matter.
Consider an example where a readonly variable Qux is dependent on Bar and another member Baz. Qux is fairly costly to calculate, so you wouldn't want to do it on the fly -- this suggests a private field to store the state, and change it IFF Bar and Baz change.
So in your constructor you could set Bar and Baz publicly, knowing that Qux will be resolved twice, or defer the resolution of Qux until the end of the constructor (and save one Qux resolution call).
In fairly trivial code that is not likely to change (e.g. public properties backing simple private fields), pick one style, stick with it, and concentrate on solving your programs real problems.
I have a class Bar with a private field containing the reference type Foo. I would like to expose Foo in a public property, but I do not want the consumers of the property to be able to alter Foo... It should however be alterable internally by Bar, i.e. I can't make the field readonly.
So what I would like is:
private _Foo;
public Foo
{
get { return readonly _Foo; }
}
...which is of course not valid. I could just return a clone of Foo (assumming that it is IClonable), but this is not obvious to the consumer. Should I change the name of the property to FooCopy?? Should it be a GetCopyOfFoo method instead? What would you consider best practice? Thanks!
It sounds like you're after the equivalent of "const" from C++. This doesn't exist in C#. There's no way of indicating that consumers can't modify the properties of an object, but something else can (assuming the mutating members are public, of course).
You could return a clone of the Foo as suggested, or possibly a view onto the Foo, as ReadOnlyCollection does for collections. Of course if you could make Foo an immutable type, that would make life simpler...
Note that there's a big difference between making the field readonly and making the object itself immutable.
Currently, the type itself could change things in both ways. It could do:
_Foo = new Foo(...);
or
_Foo.SomeProperty = newValue;
If it only needs to be able to do the second, the field could be readonly but you still have the problem of people fetching the property being able to mutate the object. If it only needs to do the first, and actually Foo is either already immutable or could be made immutable, you can just provide a property which only has the "getter" and you'll be fine.
It's very important that you understand the difference between changing the value of the field (to make it refer to a different instance) and changing the contents of the object that the field refers to.
Unfortunately, there's no easy way around this in C# at the moment. You could extract the "read only part" of Foo in an interface and let your property return that instead of Foo.
Making a copy, a ReadOnlyCollection, or having Foo be immutable are usually the three best routes, as you've already speculated.
I sometimes favor methods instead of properties whenever I'm doing anything more significant than simply returning the underlying field, depending on how much work is involved. Methods imply that something is going on and raise more of a flag for consumers when they're using your API.
"Cloning" the Foo objects you receive and give back out is a normal practice called defensive copying. Unless there is some unseen side-effect to cloning that will be visible to the user, there is absolutely no reason to NOT do this. It is often the only way to protect your classes' internal private data, especially in C# or Java, where the C++ idea of const is not available. (IE, it must be done in order to properly create truly immutable objects in these two languages.)
Just to clarify, possible side effects would be things like your user (reasonably) expecting that the original object be returned, or some resource being held by Foo that will not be cloned correctly. (In which case, what is it doing implementing IClonable?!)
If you don't want anyone to mess with your state...don't expose it! As others have said, if something needs to view your internal state, provide an immutable representation of it. Alternatively, get clients to tell you to do something (Google for "tell don't ask"), instead of doing it themselves.
To clarify Jon Skeet's comment you can make a view, that is an immutable wrapper class for the mutable Foo. Here's an example:
class Foo{
public string A{get; set;}
public string B{get; set;}
//...
}
class ReadOnlyFoo{
Foo foo;
public string A { get { return foo.A; }}
public string B { get { return foo.B; }}
}
You can actually reproduce the behaviour of C++ const in C# - you just have to do it manually.
Whatever Foo is, the only way the caller can modify its state is by calling methods on it or setting properties.
For example, Foo is of type FooClass:
class FooClass
{
public void MutateMyStateYouBadBoy() { ... }
public string Message
{
get { ... }
set { ... }
}
}
So in your case, you're happy for them to get the Message property, but not set it, and you're definitely not happy about them calling that method.
So define an interface describing what they're allowed to do:
interface IFooConst
{
public string Message
{
get { ... }
}
}
We've left out the mutating method and only left in the getter on the property.
Then add that interface to the base list of FooClass.
Now in your class with the Foo property, you have a field:
private FooClass _foo;
And a property getter:
public IFooConst Foo
{
get { return _foo; }
}
This basically reproduces by hand precisely what the C++ const keyword would do automatically. In psuedo-C++ terms, a reference of type const Foo & is like an automatically generated type that only includes those members of Foo that were marked as const members. Translating this into some theoretical future version of C#, you'd declare FooClass like this:
class FooClass
{
public void MutateMyStateYouBadBoy() { ... }
public string Message
{
get const { ... }
set { ... }
}
}
Really all I've done is merged the information in IFooConst back into FooClass, by tagging the one safe member with a new const keyword. So in a way, adding a const keyword wouldn't add much to the language besides a formal approach to this pattern.
Then if you had a const reference to a FooClass object:
const FooClass f = GetMeAFooClass();
You would only be able to call the const members on f.
Note that if the FooClass definition is public, the caller could cast an IFooConst into a FooClass. But they can do that in C++ too - it's called "casting away const" and involves a special operator called const_cast<T>(const T &).
There's also the issue of interfaces not being very easy to evolve between versions of your product. If a third party may implement an interface you define (which they are free to do if they can see it), then you can't add new methods to it in future versions without requiring others to recompile their code. But that's only a problem if you are writing an extensible library for others to build on. Maybe a built-in const feature would solve this problem.
I was thinking about similar security things. There is probably a way. Quite clear but not short. The general idea is quite simple. However I always found some ways around so never tested it. But you could check it - maybe it will work for you.
This is pseudo code, but I hope idea behind it is clear
public delegate void OnlyRuller(string s1, string s2);
public delegate void RullerCoronation(OnlyRuller d);
class Foo {
private Foo();
public Foo(RullerCoronation followMyOrders) {
followMyOrders(SetMe);
}
private SetMe(string whatToSet, string whitWhatValue) {
//lot of unclear but private code
}
}
So in class which creates this property you have access to SetMe method, but it's still private so except for creator Foo looks unmutable.
Still for anything bigger than few properties this will probably became soon super mess - that's why I always preferred other ways of encapsulation. However if it's super important for you to not allow the client to change Foo, than this is one alternative.
However, as I said, this is only theory.