How will be better in optimization goals?
public SpeedGraphModel SpeedGraphModel
{
get { return _speedGraphModel; }
set {
if (_speedGraphModel == value)
return;
_speedGraphModel = value;
}
}
or
public SpeedGraphModel SpeedGraphModel
{
get { return _speedGraphModel; }
set { _speedGraphModel = value; }
}
I think for string type will be better without checking, but for other types?
Adding another condition check instead of setting the variable value, even if it equal is redundant.
The best case if they are equal you will make 1 operation (condition).
The worst case you will make 2 operations (condition + assignment).
Instead of setting the variable no matter what. => 1 operation.
Such checking is usually used when you call some logic on the setting value (not only just set it). For instance, in desktop (WPF/WinForms) or mobile (Xamarin) you can implement your own property that behavior will be similar to the Dependency Property and call the OnPropertyChanged() method inside it. It can be used for refreshing items of the view after their updating etc. In this way, even if you set the same value to your item and then call OnPropertyChanged() it will update part of the view that can affect the performance, so you would like to make an additional check here.
If you just have a usual property, the only responsibility of which is to set value inside the private field without any logic behind, you don’t need an additional checking as it redundant and won’t increase your performance.
Related
Context: C#, WPF, MVVM
In my viewmodels I have been using initialization logic for some of my properties that is basically a check to see if the backing property is null and, if so, initialize it. Finally, return the backing property. Here's an example for list that allows a user to select items to filter by:
List<CBPicklistString> _clientClassificationFilterList;
public List<CBPicklistString> ClientClassificationFilterList
{
get
{
Debug.WriteLine("ClientClassificationFilterList - Get: " + _clientClassificationFilterList?.Count ?? "Null");
if (_clientClassificationFilterList == null)
{
_clientClassificationFilterList = CBPicklists.PicklistStrings(CBPicklists.CLIENT_CLASSIFICATIONS).ToList();
_clientClassificationFilterList.Insert(0, new CBPicklistString() { PicklistStringId = 0, PicklistStringValue = "(All Client Classes)" });
SelectedClientClassificationFilter = _effectiveClientClassificationFilter = _clientClassificationFilterList[0];
OnPropertyChanged("SelectedClientClassificationFilter");
}
return _clientClassificationFilterList;
}
}
My method to apply the filter logic has this code:
if (_effectiveClientClassificationFilter != ClientClassificationFilterList[0])
ActiveClientFilters.Add(new ActiveFilter(_effectiveClientClassificationFilter.PicklistStringValue, "ClientClassification"));
On the initial run, the getter should initialize the list and _effectiveClientClassificationFilter and the if statement should see the comparison as false (objects are equal), meaning that there is no active filter to set. But what I am seeing is that the if statement is behaving as if it sees a true (objects are not equal). When I check the values in the debugger, they are, in fact, equal. It's acting as if there is a concurrency issue where the initialization isn't finishing prior to the comparison. But this isn't a multi-threaded bit of code. Is .Net (or WPF) doing its own thing, here? Is this not a valid way to approach the list initialization? I use this logic paradigm all over the place, (and have been, for years) but this is the first time and the only place I am seeing this funky behavior. There's not a lot of other related code involved.
What am I missing?
I am not sure, but i think the initial value of _effectiveClientClassificationFilter being first in the comparison is used and then the ClientClassificationFilterList is calculated changing the value of _effectiveClientClassificationFilter which i suppose it does not know. So if you reverse the order of condition, it will work correctly.
Instead of
if (_effectiveClientClassificationFilter != ClientClassificationFilterList[0])
use
if (ClientClassificationFilterList[0] != _effectiveClientClassificationFilter)
Suppose you have a private variable like so
private int _x;
And you have a property that provides external access to this variable:
public int X
{
get
{
return _x;
}
set
{
_x = value;
}
}
Is it better to put "validation" logic (value non-negative, within bounds, etc)
in the getter portion or the setter portion? It seems like it might be acceptable in either, but is there a preferred option?
The setter is preferred, for the following reason: It is better to throw and exception or display a message to the user upon inputting a garbage value, rather than allowing the garbage value, and subjecting your class to internal bad data.
You will note that the MSDN Example uses the setter for input validation.
You want your code to fail as quickly as possible, which is at the point you try to set an invalid value.
When you fail in the setter, the user knows about the problem immediately, and can fix it. If you wait until they try to retrieve the value, you are waiting too late, and the user may have no idea what went wrong, or where.
If the invalid value gets used elsewhere in the code, you are propagating bad data throughout the application, making things much worse, and even less clear to the user what went wrong.
The validation logic should be in the setter, to prevent invalid data from even reaching _x. That way, you have a useful invariant in your class: _x will always contain a valid value.
The idiomatic way to perform validation is to throw an ArgumentException or any of its subclasses when the consuming code tries to assign an invalid value to X.
Validation should be called first. If you want to use this approach you should implement your logic in set clause.
If you want create nice clean code, you should consider dedicated method for it, e.g.:
public class Test
{
public int X { get; private set; }
public void SetX(int value)
{
//... your logic, throw exception if validation failed
X = value;
}
}
Your class should keep your object in valid state.
For discussion, I have this class with properties
public class Intresting
{
decimal _mQty, _mSpareQty;
public Qty { get { return _mQty; } set { _mQty = value; } }
public SpareQty { get { return _mSpareQty; } set { _mSpareQty= value; } }
public SparePercentage
{
get { return _mQty == 0 ? 0 : _mSpareQty / _mQty; }
set { _SpareQty = Qty * value; }
}
}
I am concern If I have 1,000,000 Interesting objects displayed in a custom GridView in a read only situation which shows SparePercentage via the property, the SparePercentage will be calculated over and over again or will there be optimised for example using a third _mSpareQtyPercentage which gets recalculated when Qty and SpareQty is set?
I very much doubt that there's anything in the JIT which would perform that optimization for you - after all, that requires more work each time Qty and SpareQty are set, and more space per object. That's not a trade-off the JIT should be doing for you. You could do that yourself, of course - just don't expect either the C# or JIT compiler to do it for you.
I would expect the JIT compiler to inline your trivial properties - which can be written as automatically implemented properties as of C# 3:
public decimal Quantity { get; set; }
public decimal SpareQuantity { get; set; }
(Note the changes to make the names more readable at the same time, by the way.)
The JIT will do nothing in particular to optimize this property and it will hence be re-evaluated in full every time it's asked for. However I doubt this would ever show up as a source of performance problems in your application. I certainly wouldn't go thruogh the troulbe of caching the result myself until a profile noted that as a problem in my application.
Note: It's also odd to have a property which has a get which is a calculation and has a set at all. When there is a calculation in the getter I usually prefer to avoid a setter entirely and instead force the caller to mutate the underlying values that are a par of the calculation
No, it will perform the calculation every time it is called. If you want to avoid that, you will have to implement your own cacheing.
.NET doesn't "optimize" properties any more than it optimizes any other functions.
This is one reason it is not recommended to put more than a getter to the backing field. If there is an operation to be performed, it should occur in a method. There is nothing in the compiler that would make an assumption about how the code should be executed.
The sample will execute the formula every time that getter is called. OT, but in a threaded environment, I would expect that the only way I could get the value would be to call a method.
In existing code of my project, at number of places the property is declared like this:
public long ResourceID
{
get
{
return this.resourceID;
}
set
{
if (this.resourceID != value)
{
this.resourceID = value;
}
}
}
Note: private long resourceID is already declared.
Properties not only of value types but also of reference types (including string) too are declared like this.
Another example:
public Collection<Ability> Abilities
{
get
{
return this.abilities;
}
set
{
if (value == null)
{
throw new ArgumentNullException("Abilities");
}
this.abilities = value;
}
}
As per my knowledge, the setter in the first example does not make any sense and the if condition is meaningless there. So i decided to change the code (as part of refactoring) to make them Auto-Properties. (In second example I need setter since exception is handled there.)
I want to know from experts here, will whether making existing properties auto properties (or at least removing if condition from setter) cause any harm? Sometimes there are subtle things which a developer may not be aware of and some changes can have side effects too. That's why I am asking this question. (My libraries are used at many places.)
Note: Let me know if this is purely a homework question.
Converting:
private long resourceID;
public long ResourceID
{
get
{
return this.resourceID;
}
set
{
this.resourceID = value;
}
}
into:
public long ResourceID { get; set; }
won't cause any harm, guaranteed.
Removing the if statement might cause harm. For example in WPF when working with the MVVM pattern and implementing the INotifyPropertyChanged interface it is often good practice to check whether the value has changed before actually setting it. Removing this check will provoke notifications to be sent to the UI no matter whether the value changed or not. So it would be a breaking change.
I can only think of one kind of problem you could run into (which is fixable):
If you are using ORM or other external tool, they might rely on a naming convention for finding properties/fields. So, the 3rd party dll might be looking for a field resourceId that no longer exists.
So, code using reflection to access fields might break, but if you have control over the codebase, that is unlikely to be an issue.
There are some edge-cases where this might cause harm:
Changing to an automatically implemented property {get;set;}
if you are using field-based serialization at any point (for example, BinaryFormatter), then this will break when changing to an automatically implemented property, as the field-name will change. This will also impact any other scenario that uses reflection to access the (hopefully private) fields, but BinaryFormatter is the most common cause of confusion here.
Removing the if test
will be fine for most data-types such as long etc, however, if you use it with a type that implements a custom equality operation, you might find you are suddenly swapping a reference when previously (with the if) the objects reported equal for different references
The first is a more likely problem. If you are using BinaryFormatter, then keep the private field (byt maybe remove the if test). And then start refactoring your code away from BinaryFormatter ;p
What you have done is correct. The if statement is meaningless. I always think that less code is better, because the lines of code is directly proportional to the number of faults.
public long ResourceID { get; set; }
Your first example only sets the resourceID field if its value has changed.
The only difference you would see by removing the "if" test is a possible impact if multiple threads are reading the value. In which case they probably should be using a lock, so it's almost certainly safe to remove the test.
Your second example prevents a caller from setting the property value to null. Presumably the field is initialized to a non-null value, and this has value as it means that callers can read the property without needing to check for null.
Usually in such scenarios and how you've explained, it shouldn't be a concern.
You could just go ahead and change the code of all properties;
public long ResourceID { get; set; }
Or
public long ResourceID
{
get { return this.resourceID; }
set { this.resourceID = value; }
}
But it might cause an issue if upon
changing the value of the property,
it cascades to some other custom
function-call which is only executed
if the new value is different from
old ones. Usually when when you've implemented custom events or even maybe in case of property-changed events
Also might affect, when using
Data-Context classes
Both scenarios are totally application specific.
I'd suggest you reactor with caution. Or as you've written yourself, HOMEWORK.
I often need to use a function which performs and action X is condition Y is set. What is the best way to name such a function?
I don't want to repeat if statements, since they could be complex.
For instance, if I want to trim a string if a property is set, function could be named:
void TrimIfOptionSet(string) -- too unwieldy, especially if condition is complex
bool TryTrim(string) -- does not mention an external condition, I'd expect it to only take the argument into account.
void ConditionalTrim(string) -- bit verbose
Are there any conventions for this situation in C#/.Net, or any similar language?
Try something like:
if(IsComplexCondition(complexData))
{
DoThing(otherData);
}
You generally don't want to couple the condition with the operation because you're making a single function capture too much semantic information at that point. It's "doing more than one thing." Instead, if you have a complex condition, capture that condition in a function to encapsulate it.
If you're referring to a much more common situation, such as parameter validation at the top of functions, consider something like fluent parameter validation. If you're not doing something like parameter validation, then I might question why it's at the top of every function and not captured in a common location or performed once at a system boundary.
I don't think that there is a good answer for naming the general ActionIfSomething() case simply because it's not generally a good solution to a problem. I'd probably just say make the function call Action() and document it, perhaps in <remarks>, to only perform the action when Something is true. If the Action belongs with the condition in the function, then it only makes sense in the context of that condition, so re-specifying it in the function name is redundant.
Given the constraints, I'd pick TrimIfOptionSet or TrimIfNeeded.
TryTrim feels like it'll always run a trim operation (in a try block), which isn't the same as running it only if needed
ConditionalTrim is too long -- the reader's eyes stay on "conditional" and never get to "trim"
Could this be solved through the use of accessors?
public class MyObject
{
private string _content = string.Empty;
public bool Trim { get; set; }
public string Content
{
get
{
return this.Trim ? _content.Trim() : _content;
}
internal set
{
if (string.IsNullOrEmpty(value))
_content = string.Empty;
else
_content = value;
}
}
}
This will take the action determined by the Trim boolean whenever the Content is accessed. I've protected the set accessor, since it might be somewhat ambigious what happens when the value of Content is set while Trim is true, and checked for the special case of trying to set the content to null. Good documentation should cover these cases.