Public readonly vs distinct accessor

Probably more of a coding style/preference question here so please forgive me but I a bit curious. Is there any harm in using public readonly properties…

  Example: public int TurnNumber {get; private set; }

… versus having a private property and use accessors?

The mutators, I get. You want to restrict write access, I was just wondering if there was any particular issue with it. Fwiw, I also tend to associate get methods with calculated fields or “this does more under the hood than return a constant”…

  Example: LINQ .Count() vs array.Length or list.Count
2 Likes

Yup it’s just coding style and personal preference.
Personally I do not like properties, they look like variables but act like functions, I find that behaviour to make the core really confusing. For my brain if I don’t see parenthesis then I assume I’m just grabbing the value, but on a property that can also mean I’m running some logic.
So personally I find it much simpler to use simple variables and if I need the value just make a simple Set()/Get()
But yes if you like using properties then go ahead and use them, there’s nothing inherently wrong with them.

1 Like

It definitely a style question. Properties reduce the amount of code you have to write, right up until they contain more than just get;set; . Then they become a confusing place to hide code that should probably be in a method.

My general rule of thumb is that a property is better so long as it can be expressed as shorthand, ie public int TurnNumber {get; private set; } Once the property does anything other than fetching/storing a value (like changing other properties, performing validation, etc. I change it to method calls.

1 Like

That’s fair and totally agree. Like I said, was just curious and wanted to get some takes on it. I tend to follow the rule of thumb you posted. Accessor if I need to do processing before I return a value and leave it as a property if I don’t. To me, in C# at least, accessor methods indicate there is some level of calculation going on, whereas properties access the raw value. Do try to stay away from going further than the simple

int Turn {get; private set;}

but, that may just be my personal code preference.
Appreciate the reply, I like getting the opinions of those that may be more experienced in case there is a reason for or against something I hadn’t considered before.

3 Likes

Privacy & Terms