Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it "wrong" for properties to call methods or start events [closed]

Naming conventions imply that (typically) properties are nouns, methods are verbs. Now, I know these are guides, not rules, but it's something best to follow a guide when you can.

This means, the following

Person.Name = "Dave";

should only set the Name property. I would not expect the property to look like

public string Name
{ 
    set
      { 
          UpdateDatabase(value);
      }
}

My question is pretty much exactly the example above but in relation to DependencyProperties.

My application has a UserControl, it looks like

 <uc:MyControl MyControlMyValue="{Binding RelativeSource={RelativeSource AncestorType=userControls:MyOtherControl}, Path=MyValue, Mode=OneWayToSource}" />

So, as you can see in the above, when the MyControlMyValue property is updated, it updates the MyValue property. The problem I have is when this property is updated I need it to perform more logic than simple binding!

At the moment, I'm voting to ignore the guide and implement something like

    private double _myValue;
    public double MyValue
    {
        get { return __myValue; }
        set
        {
            if (value == __myValue)
                return;

            __myValue= value;
            LookAtMeHiddenAway();
            OnPropertyChanged("MyValue");
        }
    }

Is there a better approach as it does feel very wrong to me?

like image 791
Dave Avatar asked Dec 25 '22 17:12

Dave


1 Answers

Well, it depends. If we are talking about general programming guideline, I would say no. Do not call methods inside properties, as I and others when we use properties (write/read) we expect of storing and retrieving data. So if you are going to change something, change it by calling a method, that manifests by declaration its behavior.

In case, instead, of WPF that is actually an expected behavior. So in case of WPF properties are suitable for changing data inside and are expected to behave in that way.

Bottom line: there are no strong restrictions on subject, but suggested guideline that is based on expected behavior of the code in the given environment.

like image 78
Tigran Avatar answered Jan 11 '23 04:01

Tigran