MVVM Property databinding - mvvm

Why do most MVVM databinding properties examples check to see if the current value is equal to previous.
private string name;
public string Name
{
set
{
if(this.name != value) <- why is this check needed.
{...}
}
}
thanks!

In MVVM a property setter triggers the UI update following a property change. Adding this check prevents the UI to refresh (and possibly flicker) unnecessarily.

In the case of a Binding "TwoWay", When changing the value in the XAML, the value in the bound property in the ViewModel side must not re-send the same value. On the other hand if the value (ViewModel bind side) is not changed it is not necessary to throw the "RaiseChangedProperty" event to the View.

Related

getter & setter in Swift VS getter & setter in Java

I'm really confused about the purpose of getter and setter methods in Swift as someone coming from Java world
so in Swift there is something called computed property which lets you create a dynamic variable and you can provide setters and getters for a specific property just like this
var property: Int {
get {
return anotherProperty - 4
}
set {
print("property now has a new value which is \(newValue)")
}
}
the setter gets executed after the property gets assigned with a new value ex:
property = 100
what i don't understand is that setters in general are called when we want to set a new value not after the value is set, that is their purpose and that is why it is called setter(it sets the property with a new value).
am i getting it all wrong? or if i am right then what is the purpose of setters in Swift and why are they useful at all if it's not for setting the value of a property?

What event fires after .Load in Codefluent?

I want to store an initial value when an object is loaded in a private property. If I change the value later on I want to be able to compare the initial and the current value. I can't find a suitable event for capturing the initial value. Should be just after loading the object... OnAfterCreate does not do the trick..
I could propably also use the PropertyChanged event but I am not sure how to implement it..
It was OnAfterReadRecord indeed. Thanks Simon!
protected void OnAfterReadRecord(System.Data.IDataReader reader,
CodeFluent.Runtime.CodeFluentReloadOptions options)
{
_initialActive = CodeFluentPersistence.GetReaderValue(reader, "CwObject_Active",
((bool)(false)));
}

AS3 - Private Object. Make property as read only

I have a object property in my Class which is private and marked as read-only.
private var readOnlyObj:Object;
I can only access it with a get method:
public function get readOnly(){ return readOnlyObj }
I can access it by:
var objClass = new MyClass();
trace(objClass.readOnly)
And if i'll try to modify it:
objClass.readOnly = new Object();
I'll get an error:
Error# Property is read only.
Now my question is:
How do I set the properties of my readOnlyObj as read-only?
If I have set the object in the constructor:
readOnlyObj["property1"] = 0;
And modify that property by:
objClass.readOnly["property1"] = 2;
It is valid. I want set the property1 to a read-only property. Is this possible? Thank You!
You can do this by returning a duplicate of the original object and not the object itself.
The transform properties of DisplayObjects work like this: you can get the object property from a get function and can modify the object, but such modification has no effect until you pass the modified object back to the set function.
In your case, there's no way to give the object back (no setter) and by returning a copy (commonly called 'clone') from the getter, there is no way to modify the object property from outside, because the returned reference reference the newly created independent clone, essentially making the internal object constant.
What you are asking is not possible and only yield the answer "no" if on the other hand you asked about how to achieve that functionality then there would be a few answer possible.
First of all given your code and the problem at hand it is clear that you misunderstand the class scope. You set:
private var readOnlyObj:Object;
As read only while it's really not the object you want to protect, it's its properties. So readOnlyObj should really not even be visible and accessible.
Now that readOnlyObj is private and not accessible, you can put together a simple method to retrieve properties:
public function getProperty(name:String):*
{
if(readOnlyObj[name] != undefined)
{
return readOnlyObj[name];
}
return null;
}
It might also be useful to know how to put together a public setter that cannot be used externally.
Create an internal Boolean variable (only with true package), then internally set that variable to true before setting the property then set it back to false. Since externally that boolean cannot be set you end up with a public setter that cannot be used externally.
internal var allowSetter:Boolean;
public function set whatever(value:*):void
{
if(allowSetter)
{
//set property ect...
allowSetter = false;
}
}
You can't really do this, at least in the way you describe. You can of course make your readOnly object a custom class instance that only has read-only properties, but you can't freeze a dynamic Object instance.

Change G_PARAM_CONSTRUCT_ONLY property via inheritance

I try to inherit a gobject and, among other things, would like to change the value of a G_PARAM_CONSTRUCT_ONLY property so the next child class doesn't have to care.
Here's an example to depict this: GtkComboBox has a construct only property called "has-entry" with default value FALSE. In class A I want to change this value to TRUE, so that class B doesn't need to care.
GtkComboBoxClass <-- AClass <-- BClass
"has-entry" FALSE TRUE
The first naive approach was to use g_object_set() in A's instance_init function, but to no avail.
The next idea was to obtain the GParamSpec with g_object_class_find_property() and change the default value with g_param_value_set_default() in A's class_init function. But I suppose this to change the default for all GtkComboBoxClass derived objects.
The best idea I could come up with: If g_object_class_override_property() creates a new GParamSpec I could find this and set its default value in A's class_init function. But documentation doesn't loose a word about this.
So my question: Is this a working, and intended, way of accomplishing this, or is there a better solution?
Tried so far:
g_object_set() in instance init():
no warning on start
no effect
g_object_set() in GObjectClass->constructor():
no warning on start
no effect
warning on exit: invalid cast from GtkCellCiew to GtkEntry
g_object_set() in GObjectClass->constructed():
warning on start: can't be set after construction
Thanks
Stefan
if you want to set a property in a sub-class, and that property is construct-only, then you should use the constructed virtual function to call g_object_set() instead of the init virtual.
properties marked as construct-only will be applied during construction, using their default value, unless specified on the constructor itself — i.e. with g_object_new(). this means that setting a construct-only property inside init() will not suffice, as the value will be set after init() has been called. the constructed() virtual function, on the other hand, is called after the constructor properties have been applied, so it's possible to override the default value there.
Answering this for myself:
A look into gobject source reveals that the properties list given to constructor() contains all G_PARAM_CONSTRUCT and G_PARAM_CONSTRUCT_ONLY properties and their default or given values.
Modifying these values is undocumented (or at least I couldn't find it), but it works.
Construction time property values have to be modified in this list before chaining up to parents constructor, non construct properties have to be set afterwards. Example code looks like:
static GObject *constructor(GType gtype, guint n_properties, GObjectConstructParam *properties) {
GObject *object;
guint i;
gchar const *name;
GObjectConstructParam *property;
for (i = 0, property = properties; i < n_properties; ++i, ++property) {
name = g_param_spec_get_name(property->pspec);
if (!strcmp(name, "has-entry")) // is G_PARAM_CONSTRUCT_ONLY
g_value_set_boolean(property->value, TRUE);
}
object = G_OBJECT_CLASS(parent_class)->constructor(gtype, n_properties, properties);
g_object_set(object, "entry-text-column", TEXT_COLUMN, NULL);
return object;
}

Is it bad practice to have my getter method change the stored value?

Is it bad practice to change my getter method like version 2 in my class.
Version 1:
public String getMyValue(){
return this.myValue
}
Version 2:
public String getMyValue(){
if(this.myValue == null || this.myValue.isEmpty()){
this.myValue = "N/A";
}
return this.myValue;
}
I think it is actually quite a bad practice if your getter methods change the internal state of the object.
To achieve the same I would suggest just returning the "N/A".
Generally speaking this internal field might be used in other places (internally) for which you don't need to use the getter method. So in the end, the call to foo.getMyValue() could actually change the behaviour of foo.
Alternatively, the translation from null to "N/A" could be done in the setter, i.e. the internal value could be set to "N/A" if null is passed.
A general remark:
I would only add states such as "N/A" if they are expected by some API or other instance relying on your code. If that is not the case you should rely on the standard null types that are available to you in your programming language.
In my opinion, unless you are doing lazy-loading (which you are not in that case), getters should not change the value. So I would either:
Put the change in the setter
public void setMyValue(String value) {
if(value == null || value.isEmpty()){
this.myValue = "N/A";
} else {
this.myValue = value;
}
}
Or make the getter return a default value if value not set properly:
public String getMyValue() {
if(this.myvalue == null || this.myvalue.isEmpty()){
return "N/A";
}
return this.myValue;
}
In the case of lazy-loading, where I would say that changing your members in a getter is fine, you would do something like:
public String getMyValue() {
if (this.myvalue == null) {
this.myvalue = loadMyValue();
}
return this.myValue;
}
No. You're doing two things here. Getting and setting.
Yes. It's a bad practice.
Why?
When the value is set (in a constructor or setter method), it should be validated, not when a getter method is called. Creating a private validate* method for this is also a good idea.
private boolean validateThisValue(String a) {
return this.myValue != null && !this.myValue.isEmpty();
}
public void setThisValue(String a) {
if (validateThisValue(a)) {
this.myValue = a;
}
else {
// do something else
// in this example will be
this.myValue = "N/A";
}
}
And, in the getter method, never ever change the state of the object. I have worked on some projects, and the getter often must be made const: "this method cannot change internal state".
At least, if you do not want to complicate things, in the getter method, you should return "N/A" rather than change internal state and set myValue to "N/A".
I usually define a specific getter.
Never alter original getter:
public String getMyValue(){
return this.myValue
}
And create a specific getter:
public String getMyValueFormatted(){
if(this.myvalue == null || this.myvalue.isEmpty()){
return "N/A";
}else{
return this.myValue;
}
}
I think it's better to initialize this.myValue = "N/A". And subsequent calls to setMyValue should modify the this.myValue according to your business conditions.
The getMyValue shouldn't modify in any way this.myValue. If your needs are to return a certain value, you should return that value (like "N/A") and not alter this.myValue . Getters must not modify member's value.
I would change better the setter method so, if the value is null or empty, the N/A is assigned to the attribute. So, if you use the attribute in other methods inside the class (v.g. toString()) you will have the intended value there.
Alternatively, change the setter method to launch an exception when the value being set is not right, so the programmer is forced to improve its handling prior to setting the value.
Other than that, it is ok.
I do feel this is a bad practice unless and until you explain the reason why it is so necessary for you modify the object inside the getter method instead of doing it inside the setter method.
Do you feel this cannot be done for some reason? Could you please elaborate?
Do what ever you like. After all getters and setters are just another public methods. You could use any other names.
But if you use frameworks like Spring, you are bound to use those standard names and you should never put your custom codes inside them.
absolutely yes, it's a bad pratice.
Imagine you communicate accross network with a third party (remoting, COM, ...), this will increase the round-trip and then hit application performance.
A setter could modify as part of validation, but a getter should return the value and let the validation be done by the caller. If you do validate, then how should be documented.
This actually highly depends on the contract you want to enforce with your get()-method. According to design-by-contract conventions the caller has to make sure that the preconditions are met (which means doing a validation in a setter method often is actually bad design) and the callee (I do not know if that's the correct english term for that, i.e., the called one) makes sure that the post conditions are met.
If you define your contract so that the get()-method is not allowed to change the object then you are breaking your own contract. Think about implementing a method like
public isValid() {
return (this.myvalue == null || this.myvalue.isEmpty());
}
Advantage of this approach is that you do not have to check wether the return of your get() is "N/A" or something else. This also can be called before calling set() to validate that you do not insert illegal values into your object.
If you want to set a default value you should do that during initialization.
State changes in getters should be a hanging offence. It means that client code must be careful about the order in which it accesses getters and setters and to do this it must have knowledge of the implementation. You should be able to call the getters in any order and still get the same results. A related problem occurs when the setter modifies the incoming value depending on the current state of the object.
You can use some value holder for this purpose. Like Optional class in guava library.