10 Replies - 1160 Views - Last Post: 09 May 2016 - 05:46 AM

#1 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2386
  • View blog
  • Posts: 5,008
  • Joined: 11-December 07

Why do you all use properties?

Posted 07 May 2016 - 03:04 PM

Apologies for the emotive title. I use properties too but I don't understand why Microsoft included them in C# or why they are so popular. Bearing in mind I come from Java Land and am used to writing getters (and occasionally setters), I don't really see what properties have to offer beyond a concise syntax for the most simple case.
Is This A Good Question/Topic? 0
  • +

Replies To: Why do you all use properties?

#2 Atli  Icon User is offline

  • Enhance Your Calm
  • member icon

Reputation: 4238
  • View blog
  • Posts: 7,216
  • Joined: 08-June 10

Re: Why do you all use properties?

Posted 07 May 2016 - 05:10 PM

Basically, it future proofs "simple case" attributes.

Without properties, you either have to decide whether to write getters/setters for all attributes, or to make attributes that don't apparently need them public. (Which is arguably not a good way to code.)

The former is a lot of extra code for something that isn't likely to be ever used. The latter makes it harder for those rare cases in which "simple attributes" that were made public in the beginning all of a sudden need getters/setters; where you have to update all uses of the attributes to instead use the getter/setter.

Properties let you define public attributes that can later be extended to include getters/setters, without any additional code up front.
Was This Post Helpful? 1
  • +
  • -

#3 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon


Reputation: 6966
  • View blog
  • Posts: 14,572
  • Joined: 16-October 07

Re: Why do you all use properties?

Posted 07 May 2016 - 05:33 PM

View Postcfoley, on 07 May 2016 - 05:04 PM, said:

writing getters (and occasionally setters


Well, that's a Java convention. There's really nothing stopping a programmer from writing getX or setX that doesn't behave in an EJB expected way. In contrast, a property implicitly offers such behavior.

Further, a property is more than just rule over convention. A property allows an object to behave exactly as if it had public variables, when in reality it has nothing of the kind. Properties leave no excuse at all for public variables, in their simplest form behave exactly like them, yet offer intrinsic getter setter future proofing.

If you're using a getter / setter convention in C#, you're simply doing it wrong.
Was This Post Helpful? 1
  • +
  • -

#4 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2386
  • View blog
  • Posts: 5,008
  • Joined: 11-December 07

Re: Why do you all use properties?

Posted 07 May 2016 - 05:46 PM

I'm happy with following the convention and using properties for that reason.

I don't understand why using them guarantees future proofing. What is it about them that makes them more future proof than other methods? Perhaps an example (or a link with an example) would help clarify it for me.
Was This Post Helpful? 0
  • +
  • -

#5 tlhIn`toq  Icon User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6505
  • View blog
  • Posts: 14,360
  • Joined: 02-June 10

Re: Why do you all use properties?

Posted 08 May 2016 - 08:33 AM

Properties are also a major part of lots of Windows coding foundation classes.
You can databind to a property, not a field.
Data contracts need properties, not fields.
You can raise events such as INotifyPropertyChanged and INotifyCollectionchanged on properties, not fields.
UserControls and CustomControls update off properties and DependencyProperties, not fields.

Lets say you make a program that is an Address/Contact manager.
You make a Window that shows all the details about the CurrentContact - CurrentContact is a property in your ViewModel.
The label that shows the contact's phone number needs 1 line to bind it to the CurrentContact.PhoneNumber property. That's its: Done.
Now when you update the phone number from code behind (maybe an update comes down from a REST call, ActiveDirectory update or from syncing with your phone, or whatever) then your UI updates automatically. When you update your UI by typing in a new number, it automatically updates the CurrentContact because of the binding.
When you select a new contact from the list, your entire UI for that contact updates. No events, no code behind. Nothing. Just updating the CurrentContact property forces updates to trickle down to every property and UI element that references its.

Its a HUGE reduction in code, logic, maintenance and so on. HUGE. There's a tutorial on properties linked in my signature block. Also look at the first WPF for the WinForms developer tutorial to better see properties in action. Its one of those things that once you start using them, and getting the benefits of them you wonder how you ever did things without them.

This post has been edited by tlhIn`toq: 08 May 2016 - 08:34 AM

Was This Post Helpful? 1
  • +
  • -

#6 baavgai  Icon User is offline

  • Dreaming Coder
  • member icon


Reputation: 6966
  • View blog
  • Posts: 14,572
  • Joined: 16-October 07

Re: Why do you all use properties?

Posted 08 May 2016 - 10:57 AM

View Postcfoley, on 07 May 2016 - 07:46 PM, said:

I don't understand why using them guarantees future proofing.


Let's start out with:
class Person {
   public int Age;



You should be screaming out in horror, so you change this to:
class Person {
   public int Age { get; set; }



For now, both those snippets behave the same. Then, in the future, some idiot starts using -1 as a place holder. With a property, you simple do something like:
class Person {
   private int age;
   public int Age { 
       get { return age; }
       set { 
           if (value<0) { 
              throw new ArgumentException("Age may not be negative."); }
           }
           age = value;
       }
   }



You could reasonably say you could change a public value to a property when you need to add the above logic, to which I would ask, why start out wrong? ;)
Was This Post Helpful? 1
  • +
  • -

#7 tlhIn`toq  Icon User is offline

  • Xamarin Cert. Dev.
  • member icon

Reputation: 6505
  • View blog
  • Posts: 14,360
  • Joined: 02-June 10

Re: Why do you all use properties?

Posted 08 May 2016 - 11:12 AM

I like baavgai's example, except for the missing call to raise a notification about the property changing. You want this INotifyPropertyChanged event to be raised so any other class (including UI binding) can be aware of the change in an event-driven pattern.
http://www.dreaminco...ies-properties/

Here is a nice Visual Studio snippet for Properties. Its shortcut is 'nuprop'. That way you can just type 'nuprop{tab}', enter the name {tab} enter the type {return} and you're done: Everything else updates, its wrapped in named #region etc. I find this to be one of my most used snippets.

Spoiler

This post has been edited by tlhIn`toq: 08 May 2016 - 11:26 AM

Was This Post Helpful? 1
  • +
  • -

#8 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2386
  • View blog
  • Posts: 5,008
  • Joined: 11-December 07

Re: Why do you all use properties?

Posted 08 May 2016 - 01:41 PM

Thanks for providing the examples and explanations but my confusion is over the relative merits of properties and methods. It was already obvious to my why both of these are preferable to properties. So far I have got:

  • Convention: my code will like like my co-workers if I use properties.
  • Syntax: more concise for the simple case and for the complex case makes you put the getter and setter close together.
  • Data Binding: This seems like an awesome thing to bake into the language.


Just about to look at the tutorials now.

Edit: I just read the tutorial about binding properties. I thought doing bindings like this was just another (very nice) way to do the observer pattern, but that saying it was to do with properties was beside the point: You can do the observer pattern with methods too. Then I realised you were telling me that the binding works both ways. That really is cool and I see how it can reduce the logic in an application enormously. Very nice!

This post has been edited by cfoley: 08 May 2016 - 02:04 PM

Was This Post Helpful? 0
  • +
  • -

#9 sepp2k  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 2506
  • View blog
  • Posts: 3,959
  • Joined: 21-June 11

Re: Why do you all use properties?

Posted 08 May 2016 - 02:08 PM

View Postcfoley, on 08 May 2016 - 10:41 PM, said:

  • Syntax: more concise for the simple case and for the complex case makes you put the getter and setter close together.


When you say that it's more concise only in the simple, you're talking about the definition? Like in the simple case you can just write get; set; while in the complex case, you have to define a body, just like with regular getters and setters, right?

To me the more important point regarding conciseness is not the definition, but the use, which gets more concise (compared to getters and setters) the more complicated it gets. Like Pos.X = 42; is a bit more consise than pos.setX(42);, but Pos.X += Pos.Y; is a lot more concise (and, IMO, more readable) than pos.setX(pos.getX() + pos.getY()). Of course the latter could be simplified by defining addX in addition to setX, but then the definition becomes more complicated again.
Was This Post Helpful? 1
  • +
  • -

#10 cfoley  Icon User is offline

  • Cabbage
  • member icon

Reputation: 2386
  • View blog
  • Posts: 5,008
  • Joined: 11-December 07

Re: Why do you all use properties?

Posted 08 May 2016 - 02:51 PM

That is an excellent point. Thanks!
Was This Post Helpful? 0
  • +
  • -

#11 Skydiver  Icon User is offline

  • Code herder
  • member icon

Reputation: 5828
  • View blog
  • Posts: 19,864
  • Joined: 05-May 12

Re: Why do you all use properties?

Posted 09 May 2016 - 05:46 AM

Also, properties need not have any backing fields behind them. Consider:
class SimpleTimeSpan
{
    public int Milliseconds { get; set; }

    public double Seconds
    {
        get { return Milliseconds / 1000.0; }
        set { Milliseconds = value * 1000; }
    }

    public double Minutes
    {
        get { return Seconds / 60; }
        set { Seconds = value * 60; }
    }
}



It is only Milliseconds which has the automatic backing field, while Seconds and Minutes are exposed as properties, but just use Milliseconds behind the scenes.

And as an example of future proofing, let's say that after all profiling runs, I determine that I make a ton of calls getting the Minutes value. So my first stab at improving performance would be:
class SimpleTimeSpan
{
    public int Milliseconds { get; set; }

    public double Seconds
    {
        get { return Milliseconds / 1000.0; }
        set { Milliseconds = value * 1000; }
    }

    public double Minutes
    {
        get { return Milliseconds / (double)(1000 * 60); }
        set { Milliseconds = value * 60 * 1000; }
    }
}



But if that still doesn't yield enough speed I would likely write ugly code like:
class SimpleTimeSpan
{
    int _milliseconds;
    double _minutes;

    public int Milliseconds
    {
        get { return _milliseconds; }
        set
        {
            _milliseconds = value;
            _minutes = _milliseconds / (double)(60 * 1000);
        }
    }

    public double Seconds
    {
        get { return Milliseconds / 1000.0; }
        set { Milliseconds = value * 1000; }
    }

    public double Minutes
    {
        get { return _minutes; }
        set
        {
            _minutes = value;
            _milliseconds = value * 60 * 1000;
        }
    }
}


Was This Post Helpful? 0
  • +
  • -

Page 1 of 1