Property to be assigned once in a singleton - good practice? - c#

Consider a class that contains a property Name inside. I would like the class to be implemented as singleton, and I want the Name to be set only once (so it can be assigned once but not changed later).
Should I assign it with a constructor (and give it only get accessor, without set) or create a separate "instance variable" for "Name" and a proper method that will work only once?
The first option would force me to pass a string argument to the GetInstance() method every time I call it, while the second one does not seem too elegant for me (as I wouldn't know if "Name" was already set - so I'd need to call this method every time I try to get an instance anyway.) Am I taking a wrong approach? Is there a good practice for such case?

The problem with passing the value into getInstance() every time is that all calling classes will have to know where the value for Name comes from and how to fetch it. Maybe they do all have this access, but then it makes it redundant storing this data on the singleton object as all callers already know its value.
Assuming that some callers know the value, and others don't, you could use a property similar to the way that you have suggested yourself:
public class MySingleton
{
// Singleton properties omitted
private string name;
public string name
{
get{return this.name;}
set
{
if(String.IsNullOrEmpty(this.name))
name = value;
// The exception could be left out, depending on how critical this is
else
throw new exception("The property 'name' can only be set once");
}
}
}
This assumes that neither null or String.Empty are valid assignations for your property and its still not the most elegant solution, so perhaps there is a different approach altogether.
Perhaps the constructor for the singleton could fetch the required value, rather than being passed the value:
public MySingleton()
{
name = configuration.getName(); // or wherever it is coming from
}
This way the calling classes can always assume that the singleton has a valid value for Name, but without caring where it comes from. If possible, I think this would be my preferred choice

Related

How do I derive from two base constructors in a way that allows me to have default argument values?

I'm writing an exception that inherits from ArgumentOutOfRangeException and I want to write constructors that derive from the two base overloads base(string paramName) and base(string paramName, string message) but I want to provide default values for paramName in both constructors and a default value for message in the second. What is the best way to do this? (If it helps, the default value for paramName will be the same in both).
I've thought of overriding the constructor with a single constructor with a third boolean parameter to determine which constructor to call and calling that constructor, but after some testing found out that fails on so many levels.
Here is an example of what I'm trying to do:
public class TrainingSetCardinalityMismatch : ArgumentOutOfRangeException
{
public TrainingSetCardinalityMismatch(string paramName = "trainingSets") : base(paramName)
{
//code here
}
public TrainingSetCardinalityMismatch(string paramName = "trainingSets", message = "Number of training sets provided must match number of answers provided") : base(paramName, message)
{
//code here
}
}
You could call the other constructor with your default values like so
public CustomException(string paramName = "defaultName") : this(paramName, null)
{
}
public CustomException(string paramName = "defaultName", string message = "defaultMessage") : base(paramName, message)
{
}
Well from the question, I can see 2 possibilities.
You always want the message (second argument)
You sometime want the message, sometime not and sometime a different message.
In the first case, you would simply remove the definition of the first constructor. You will always have the message if you don't specify the second argument.
public class TrainingSetCardinalityMismatch : ArgumentOutOfRangeException
{
public TrainingSetCardinalityMismatch(
string paramName = "trainingSets",
message = "Number of training sets provided must match number of answers provided")
: base(paramName, message)
{
//code here
}
}
Then you could call it that ways:
// default param name + default message
throw new TrainingSetCardinalityMismatch();
// custom param, default message
throw new TrainingSetCardinalityMismatch("custom param");
// custom param, custom message
throw new TrainingSetCardinalityMismatch("custom param", "custom message");
However, it won't allows default param but with custom message.
If you want that, you have a few possibilities:
One would be to have a constant for the default message and specify it explicitly instead of the hard coded string.
Another might be to change parameter order if message need to be customized most of the time.
Another one would be to have a static functions that raise the exception.
Another one could be to set the default to null if when null is specified remplace by default value. That way, you can use an empty string if you really want no message.
Another one is to have 2 exception classes (say TrainingSetCardinalityMismatchAandTrainingSetCardinalityMismatchB`) and each one has a single constructor.
Another want would be to use an enum instead of a string when using predefined messages and then constructor with custom message would not have any default as it would be used only for specific message.
Usually, I prefer the last way and then I could use resource and a bit of code to load the appropriate string from the enum identifier which is relatively easy in C# as you can to enum_var.ToString() to get a name and use that name to load a resource by its name using the resource manager (see https://learn.microsoft.com/en-us/dotnet/api/system.resources.resourcemanager?view=netframework-4.7.2).
Why not create your own constructors and call the base ones like i've shown below
class MyArgumentOutOfRangeException : ArgumentOutOfRangeException
{
public MyArgumentOutOfRangeException(string myName):base("PlaceDefaultNamepropValue")
{
// do something with passed my name
}
public MyArgumentOutOfRangeException(string myname, string mymessage):base("PlaceDefaultNamepropValue", "PlaceDefaultMessagepropValue")
{
// do something with passed my name
// do something with passed my message
}
}
class MyOtherArgumentOutOfRangeException : ArgumentOutOfRangeException
{
public MyOtherArgumentOutOfRangeException(string myName) : this("PlaceDefaultNamepropValue",string.Empty)
{
// do something with passed my name
}
public MyOtherArgumentOutOfRangeException(string myname, string mymessage) : base("PlaceDefaultNamepropValue", "PlaceDefaultMessagepropValue")
{
// do something with passed my name
// do something with passed my message
}
}
Other than needing to define the type of message (use string message = "..."), your posted code seems to be functional and doing what you want. So I assume the core of your question is:
What is the best way to do this? .... I've thought of overriding the constructor with a single constructor with a third boolean parameter to determine which constructor to call and calling that constructor.
As a general rule, I advocate against "choose your own adventure" booleans. While they work on a technical level, there are better alternatives here.
Parameters with default values are, by definition, optional parameters. This means you're already able to decide your consumer's constructor selection based on whether the consumer passed the a non-default message value. If they didn't, then they're clearly choosing to use the first option. If they did, then they're clearly choosing the second option. They don't need to then also specify a boolean.
Does it really matter whether you don't initialize message, or instead explicitly pass null or String.empty when the consumer doesn't provide a message value? Because if not, then there's no reason to even try and distinguish between the two base constructors.
Method overloading inherently exists to give users a way to differentiate between different sets of input parameters, and each overloaded body has its own method (which you can choose to chain or not) so you have total control over what happens in which case. Your boolean would be a (IMO poor) substitute for a cleaner method overload.
CYOA booleans tend to only seem viable when you are the consumer of your own code because "I know how I designed this to work". That's often something which leads to avoiding good practice and clean coding. While it will work on a technical level, it's not a good/clean solution and it eventually teaches you bad habits. In most cases, when I use someone else's library, I expect to use the method names to decide what I want to do, not a set of boolean parameters. There are of course exception to this, but they are few and far between. When I've picked the method to use, the parameters should be easy to understand and supply, rather than forcing the user to decide separate behaviors.
Encapsulation suggests that your implementation needs to hide complexities from the consumer of your class, where possible. Which means that you're allowed to use a branching structure inside your class, but you shouldn't require the consumer to knowingly make this choice - your class exists to do this for the consumer and simplify the consumer's workload. If you pass the buck to your consumer, then what is your class' value? What does it do for you/the end user? (Note: Don't misinterpret this as an anti-IOC argument. IOC is a good thing, it just isn't really done via booleans. Using IOC, you'd be injecting behavior objects instead of boolean values).

Should you reference the Property or the Member Variable inside a class? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Should you access a variable within the same class via a Property?
I ran into this recently and was curious if there was some sort of standard for which one you should reference while inside a class.
I mean really it shouldn't make a difference whether you access the member variable directly or go through the property (unless you need to dodge some custom setter code), but I wanted to be sure there wasn't a best practice for it.
partial class MyClass {
private string foo;
internal string Foo {
get {
return foo;
}
private set {
foo=value;
// I do other stuff
}
}
public void DoSomething() {
//Option 1;
Foo="some string";
//Option 2;
foo="some string";
}
}
This shouldn't be a choice you really make. Either the code in the setter is supposed to run, in which case use the property, or it's not, in which case you use the member variable. In most all situations one is right and one is wrong. Neither is always right/wrong in the general case, and it's unusual for it to "not matter".
For example, if the setter code is firing a "changed" event, do you want external objects to be notified that it changed, or not? If you're changing it in response to a previous change, probably not (infinite recursion anyone?) if no, you probably want to make sure it's fired (so that you're not changing a value and not notifying anyone of changes).
If it's just validating that the value being set is valid, then either you know that, in this context, the value is already validated and must be valid, in which case there is no need to validate again; set the property. If you haven't yet validated what you're about to set then you want the validation logic to run, so use the property.
This question is quite a lot debated, so there is no obvious answer to the question.
Personally I prefer to access via the property because you might have some validation or conversion code in it. Even though your getters and setters are trivial, they might change in the future.
If you wrapped the field foo in the property Foo, you probably did so for a reason (conversion, events, validation, etc). So, generally speaking, the only place you should be referencing the field foo is in the getters and setters for the property Foo. The rest of the code should reference the property Foo.
I'm sure there exists some obscure situation where you would need to bypass the property's getters and setters, and that's certainly okay to do, but such situations would be the exception to the rule.
Option 1 is good practice. because if you use the Option 2, you will lose other stuff when setting the foo value.
I would go with Option 1. If you're setting a variable, you should use the property and not access the variable directly. This is because the property has the extra code you indicated with "// I do other stuff". You wouldn't want to have to repeat this "other stuff" just because you didn't set the property...unless, you don't want to do "other stuff" when you're setting it this time.
Honestly, this is just a theoretical situation, and it would be a lot easier to answer if you give a practical situation where you encounter this problem.
When using the INotifyPropertyChanged interface, using the property is a must, if you wish to update binded objects.
If the setter doesn't have a logic there is no point in explicitly declaring the private variable and it's better to use auto-implemented properties:
internal string Foo
{
get;
private set;
}
public void DoSomething()
{
this.Foo = "some string";
}
If the setter has a logic, the private variable should only be used in the setter and never be modified outside of the setter.
In any case (and in my opinion :)) a private variable should never appear anywhere else beside the property setter.
Imagine the code like
public partial class HybridPanel: Panel {
[DefaultValue(BorderStyle.FixedSingle)]
public virtual new BorderStyle BorderStyle {
set {
if(value!=borderStyle) {
borderStyle=value;
base.PerformLayout();
}
}
get {
try {
return borderStyle;
}
finally {
if(borderStyle!=base.BorderStyle)
base.PerformLayout();
}
}
}
BorderStyle borderStyle=BorderStyle.FixedSingle;
bool isCollapsed, isAutoSize;
}
In this conext, the property is not only used as a variable, but also other things to do.
Access the properties in the same class is NOT considered a bad pratice, further, the complier would suggest that:
A method that is just for access a field without passing arguments, consider define as a property instead.
By the way, you might correct the description of access the member variable directory to be access the member variable directly(that is, access with the fields).

how to declare const which can be initialized at runtime only

My class contains LOT_SIZE constant which can not be changed. But I can initialize it only during execution, because I obtain LOT_SIZE from Securities table at runtime. However I want to make clear that this is constant and I want to protect it from changes from any other places except one "friend" place where I want to initialize it ("Securities" table read).
Do we have something for that in C# or I just have to use LOT_SIZE as regular variable?
I can not declare LOT_SIZE as readonly because during object construction "Securities" table still not read and so I don't know LOT_SIZE value.
The best way is probably to read the value before creating the class that must hold it, so you can pass it into the constructor and put it into a readonly field. But as you've excluded doing it the obvious way...
You could use a read-only property (a property with a get but no set) and always access it via the property except in the place where you initially set up the value.
If you don't even want to risk changing it from within your own class, then create a class to "wrap" the value. This class would do nothing more than read the value when required the first time and expose it as a read-only property to your consumer classes.
But whichever way you choose, please don't use "1970's C macro constant" (ALL_CAPS) naming for your constant :-)
You cannot declare a variable in a way that it can be modified in one place and not in any other (except for readonly which you excluded).
I suggest you use some kind of "lazy pattern". Write a class which wraps a value and allows the value to be set exactly one time. You can make the variable referencing an instance of this class read-only.
class WriteOnce<T>
{
T _val;
bool _isInitialized;
public T Value {
get { if (!_isInitialized) throw; return _val; }
set { if (_isInitialized) throw; _val = value; }
}
}
...
class SomeOtherClass {
readonly WriteOnce<int> LOT_SIZE = new WriteOnce<int>();
}
You could make a class to read from your table with a private member variable (even make the class a Singleton to get uber fancy). Then make a static public variable with only a getter. It's a bit overkill, but that would be the only way to allow it to be set after initialization, but only able to be modified the one time.

Which is better between a readonly modifier and a private setter?

I've been working on creating a class and suddenly a thought came to my mind of what is the difference between the two codes:
public readonly string ProductLocation;
AND
public string ProductLocation
{
get;
private set;
}
Can you guys give me idea when to use the following better. thanks.
The first one is a read-only field, while the second one gets compiled as a pair of methods (and all reads of the property ProductLocation gets compiled into calls to the corresponding get method and writes to it gets compiled into calls to the set method; internally, these methods will read from / write to an internal, automatically generated, non-read-only field). I'd say the most important difference is thread-safety! (how? read on!)
The basic usage of the class will look exactly the same: code in other classes will only be able to read the value, not change it. Also, the code to read the value will look exactly the same (for example, print(myInstace.ProductLocation); here, you cannot tell how it has been declared, cool, eh?)
The first, most trivial difference is that the property with private setter allows for instances of the same class to modify the value, while in the case of the readonly property, not even the object itself will be able to change the value.
Now, for the thread-safety. The readonly attribute on the field will change its memory visibility semantics when you are working with multiple threads (just like Java's final fields).
A readonly field can only be assigned to at declaration or in the constructor. The value assigned to a readonly field cannot be changed (at least not in a normal way) and it is guaranteed that every thread will see the correctly, initialized value after the constructor returns. Therefore, a readonly field is inherently thread-safe.
To achieve the same thread-safety with the property, you'd have to add some synchronization on your code, which is error-prone. It might lead to dead-locks, data races or reduced performance, depending on the case, and especially if you are not experienced.
So, if the value represents something that semantically cannot be changed after the object's construction, you should not declare a private setter (this would imply that the object might change it). Go for the readonly field (and maybe declare it private and declare a public property with only a getter accessing the field! This is actually the preferred form, since it is not good to expose fields, it is better to only expose methods -- there are many reasons explaining why in this answer)
With C# 6.0 auto-property initializer there is less boilerplate way of doing
private readonly string productLocation;
public string ProductLocation { get { return productLocation; } }
Which is
public string ProductLocation { get; }
This is readonly. Only initialized from constructor or inline. It cannot be edited after initialization. (Immutable from anywhere)
However, if you use private set;
public string ProductLocation { get; private set }
This is readonly from outside. But can be initialized anytime anywhere within the class itself. And can be edited within its life cycle by the class itself. (Mutable from class, immutable from outside)
Generally, it is not encouraged in .NET to expose member fields publicly, those should be wrapped by a property. So let's assume you might have
private readonly string productLocation;
public string ProductLocation { get { return productLocation; } }
vs
public string ProductLocation { get; private set; }
In this setup, and ignoring what one might be able to accomplish via reflection, the semantics are that in the first case, the productLocation variable can only be initialized in place and in the class constructor. Other members of the class cannot alter the value. External consumers have no ability to set the value.
In the second version, external consumers continue to have no access towards setting the value. However, the class itself can change the value at any time. If all you have is a DTO (that is, a class that only transports data, it has no logic expressed via methods), then this is essentially not all that different from the readonly version. However, for classes with methods, those methods could alter the value behind ProductLocation.
If you want to enforce the concept of an immutable field post-construction, use readonly. But for a DTO, I might go for the private set; option, mainly because it is less boilerplate code.
The first one (using readonly) will mean that the object can't even modify its own field's value, once the object has been instantiated, and others can never modify it.
The second one (using private set) will mean that object can modify the value of its field after it's been instantiated, but others can never modify it.
I would use the former for something that you know will not change, and use the latter for something where the value may change, but you don't want others to change it.
The first is a field whose value can be set only at instantiation.
The second is a property whose value can be set at any time (but only by its containing object).
Correction: The property can be set at any time by any instance of the same class (and not only by its containing object).

What is the proper way to access a value internally?

In the following setter, I can access the property backing field directly or through the getter. Is there a scenario when one would be preferred over the other?
public string Name {
get { return this.name; }
set {
if (value == this.name) return;
// or
// if (value == this.Name) return;
// ?
this.name = value;
NameChanged.Raise(this, this.name);
// or
// NameChanged.Raise(this, this.Name);
// ?
}
}
There is a related question. How would you initialize properties in the c-tor?
public MyClass(string name) { this.name = name; }
// or
public MyClass(string name) { Name = name; }
I use this.name, for the reason that at construction time the instance might be in an invalid/unstable/undefined state, so Name-setter validation might falsely fail. Any other opinions?
I would say that "Name = name" is more correct, because if you were to declare the "name" property as virtual then someone could override your property behaviour, but your constructor would still bypass their logic.
Additionally properties can encapsulate behaviour such as raising change events, which you shouldn't bypass. No user can add a handler to your event until you have constructed the object. Therefore if you make a setting in a constructor where you have external events, it won't be raised.
EDIT
See the comments below for why virtual was a bad example.
My personal approach to this problem is
Only use a this qualifier when to do otherwise would result in incorrect behavior or a compilation error.
I prefer to make my code readable in the abscence of a this qualifier. If it's unreadable without a this qualifier I strive to change the code to be readable.
In this case, the difference between the syntax is that in one case the getter/setter get invoked, while in the other case they don't. Correct?
I think it would be best to use Name rather than this.name. This way, only the getter/setter have access to the "unprotected" variable, and you can confirm any invariants about this value looking only at the getter and setter rather than at the whole class.
My personal opinion is to preferably use the property unless that results in the incorrect behaviour. What it comes down to is that using the property indicates a commitment to the semantics of your class and the design of your API.
Obviously sometimes there are going to be exceptions to this rule... sometimes the 'property' means something distinct to the value of the backing field (in your example, the property raises an event). If the internal use explicitly needs to avoid the semantics of the property (you don't want the event to fire), then the backing field is the correct 'second choice'.
On an unrelated note, for better or for worse, the Microsoft StyleCop application specifically prefers the convention of accessing private fields with the 'this' prefix to differentiate access of local variables and class fields (rather than prefixing such as '_' or 'm_' or variants thereof... which ironically are the convention used in legacy .NET framework code).
I agree with the others; you generally want to use the property. The reason for this is that you will get the logic that comes with it. In WPF, for example, if you don't use the property and instead use the field PropertyChanged events won't be fired, which means that any controls bound to that property won't get updated. Of course, you can't call the property within the property or you'll end up with a stack overflow.
That said, there are times when you would want to avoid that logic entirely, and once in a while variable initialization falls under that. In that case, you want to use the field.
Accessing the field within the property could potentially lead to an overflow if you're not careful. I always access the property to avoid those potential situations.
In the following setter, I can access property backing field directly or through the getter? Is there a scenario when one would be preferred over the other?
only use it when there is a conflict with other variables in scope
There is a related question - how do you initialize properties in the c-tor?
If you have a property, use the property
I you don't want to raise the PropertyChanged event, access the field instead of the property. However, in the constructor, you don't really care about raising that event, since you know for sure that no one has subscribed to the event yet...
My recommendation is that if you have access to the field and the field does not require special logic. An example:
private int width;
public int Width
{
get
{
return width;
}
set
{
if (value < 0)
throw new InvalidArgumentException("Mass cannot be below 0");
width = value;
}
}
In this case you would NOT want to access the field, because you (probably) cannot guarantee that the value you are setting is above 0.
However, if you have a property like:
public int Height { get; set; }
then it would probably be a good idea to access the field when possible.

Categories