Author Topic: private readonly class variables - why?  (Read 4571 times)

0 Members and 1 Guest are viewing this topic.

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16899
  • Superior Stupidity at its best
private readonly class variables - why?
« on: June 12, 2013, 02:29:36 PM »
I have seen this in some classes that I am working on and I was wondering what the purpose is and if there is an advantage to doing so.

Code - C#: [Select]
  1. public class Foo
  2. {
  3.     private readonly int _item = -1;
  4.  
  5.     public Foo(int item)
  6.     {
  7.         _item = item;
  8.     }
  9. }

As I understand it, class variable are private for encapsulation purposes and readonly to keep the value from being changed.

So ..

If the value is private, it can't be changed outside the class because other classes don't know about it. Making it readonly seems a redundant measure because it seems obvious that if the programmer doesn't want that value to change, then don't change it.

What am I missing? Inheritance perhaps?
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

dgorsman

  • Water Moccasin
  • Posts: 2437
Re: private readonly class variables - why?
« Reply #1 on: June 12, 2013, 02:35:23 PM »
Could be useful as one of those what-WAS-I-thinking protections for the programmer.  We all make mistakes, after all, even the veterans.  So the editor will politely raise its virtual hand and remind the programmer "I don't think so, Tim".
If you are going to fly by the seat of your pants, expect friction burns.

try {GreatPower;}
   catch (notResponsible)
      {NextTime(PlanAhead);}
   finally
      {MasterBasics;}

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16899
  • Superior Stupidity at its best
Re: private readonly class variables - why?
« Reply #2 on: June 12, 2013, 03:12:21 PM »
I had considered that, but I thought the people much smarter than me would just say "dumbass .. if you don't want it changed, then don't change it" ... building a construct into a programming language to handle idiots is idiotic.

I guess in a world where multiple programmers work on the same project it might be useful though.
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

Jeff H

  • Needs a day job
  • Posts: 6144
Re: private readonly class variables - why?
« Reply #3 on: June 12, 2013, 03:29:43 PM »
Hi Keith,
 
You can think of read-only as runtime constant & a const as compile constant.
 
A read-only(runtime constant) is usually a better choice than using a const(compile constant).
 
A const will give a slight performance gain, but nothing worth caring.
 
 
 
A const can only be used for primitive types(int, double, etc..)
Readonly can be any type, and can be used as instance constants.
 
Another advantage is readonly constants reference the readonly variable which are resolved at runtime.
 
Using a AutoCAD example if you have a library that uses P/Invoke and contains a constant like "acad.exe".
When you reference that library into a application and compile it the compiler creates IL that stores "acad.exe" directly in the assembly.
If you update the library to "accoremgd.dll" and distribute new library a application that was built with previous version will still use "acad.exe", and would require the application to be re-built to update the value.
 
If a read-only was used the application that references the new library would get the new value through the read-only variable which is evaluated at runtime and would use new value, without having to rebuild the application since it does not "bake-in" read-only constants into the assembly.
« Last Edit: June 12, 2013, 03:33:41 PM by Jeff H »

MexicanCustard

  • Swamp Rat
  • Posts: 705
Re: private readonly class variables - why?
« Reply #4 on: June 12, 2013, 04:05:51 PM »
Hi Keith,
 
You can think of read-only as runtime constant & a const as compile constant.
 
A read-only(runtime constant) is usually a better choice than using a const(compile constant).
 
A const will give a slight performance gain, but nothing worth caring.
 
 
 
A const can only be used for primitive types(int, double, etc..)
Readonly can be any type, and can be used as instance constants.
 
Another advantage is readonly constants reference the readonly variable which are resolved at runtime.
 
Using a AutoCAD example if you have a library that uses P/Invoke and contains a constant like "acad.exe".
When you reference that library into a application and compile it the compiler creates IL that stores "acad.exe" directly in the assembly.
If you update the library to "accoremgd.dll" and distribute new library a application that was built with previous version will still use "acad.exe", and would require the application to be re-built to update the value.
 
If a read-only was used the application that references the new library would get the new value through the read-only variable which is evaluated at runtime and would use new value, without having to rebuild the application since it does not "bake-in" read-only constants into the assembly.

A readonly is like a const but can be assigned in the constructor.  So if you have a variable that gets assigned in the constructor and never changes then using a readonly is a better option than a standard variable.

Like if your passing in and Autocad Database or Autocad Transaction.  You can assign these to private variables in the constructor and you are not charged much more overhead than a const.
« Last Edit: June 12, 2013, 04:08:59 PM by MexicanCustard »
Revit 2019, AMEP 2019 64bit Win 10

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16899
  • Superior Stupidity at its best
Re: private readonly class variables - why?
« Reply #5 on: June 12, 2013, 04:12:57 PM »
I understand the nuance between "private const" and "private readonly" ... as a general rule I use constants a) where it is unlikely that the value will ever need to be changed during the lifecycle of the project; and b) where a value can be changed at design time to effect change in many places throughout the code base. (i.e. int const MAX_VAL = 1024;)

The issue I was wondering about was why would one declare a class variable both private and readonly. If you are using them as a replacement for constants, then I can see that, although, I would still just stick with constants where it is a better choice.

So, in essence why this:
Code - C#: [Select]
  1. public class Foo{
  2.     private readonly int _item; //What advantage does a readonly variable provide in this context?
  3.     public Foo(int item)
  4.     {
  5.         _item = item;
  6.     }
  7. }

instead of this

Code - C#: [Select]
  1. public class Foo{
  2.     private int _item; //Is there an advantage to making this a readonly variable if it isn't going to be changed elsewhere in code?
  3.     public Foo(int item)
  4.     {
  5.         _item = item;
  6.     }
  7. }
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

dgorsman

  • Water Moccasin
  • Posts: 2437
Re: private readonly class variables - why?
« Reply #6 on: June 12, 2013, 04:34:17 PM »
I had considered that, but I thought the people much smarter than me would just say "dumbass .. if you don't want it changed, then don't change it" ... building a construct into a programming language to handle idiots is idiotic.

I guess in a world where multiple programmers work on the same project it might be useful though.

I don't think of it as catering to the lowest common denominator, rather just another safety net (just not uniquely as such).  Kind of like not allowing an integer type variable being assigned a string value.  A "lesser" programmer might make that mistake, but its still a valuable tool.
If you are going to fly by the seat of your pants, expect friction burns.

try {GreatPower;}
   catch (notResponsible)
      {NextTime(PlanAhead);}
   finally
      {MasterBasics;}

MexicanCustard

  • Swamp Rat
  • Posts: 705
Re: private readonly class variables - why?
« Reply #7 on: June 12, 2013, 04:50:13 PM »
I understand the nuance between "private const" and "private readonly" ... as a general rule I use constants a) where it is unlikely that the value will ever need to be changed during the lifecycle of the project; and b) where a value can be changed at design time to effect change in many places throughout the code base. (i.e. int const MAX_VAL = 1024;)

The issue I was wondering about was why would one declare a class variable both private and readonly. If you are using them as a replacement for constants, then I can see that, although, I would still just stick with constants where it is a better choice.

So, in essence why this:
Code - C#: [Select]
  1. public class Foo{
  2.     private readonly int _item; //What advantage does a readonly variable provide in this context?
  3.     public Foo(int item)
  4.     {
  5.         _item = item;
  6.     }
  7. }

instead of this

Code - C#: [Select]
  1. public class Foo{
  2.     private int _item; //Is there an advantage to making this a readonly variable if it isn't going to be changed elsewhere in code?
  3.     public Foo(int item)
  4.     {
  5.         _item = item;
  6.     }
  7. }

The simple answer to your question is there is no advantage performance wise.  The purpose is to have an immutable object whos value is set at runtime.  Its more for things like having the compiler warn you if you try to change something that shouldn't be changed or letting another developer who is looking at your code know that the value is a runtime constant.
Revit 2019, AMEP 2019 64bit Win 10

Jeff H

  • Needs a day job
  • Posts: 6144
Re: private readonly class variables - why?
« Reply #8 on: June 12, 2013, 05:21:15 PM »
I understand the nuance between "private const" and "private readonly" ... as a general rule I use constants a) where it is unlikely that the value will ever need to be changed during the lifecycle of the project; and b) where a value can be changed at design time to effect change in many places throughout the code base. (i.e. int const MAX_VAL = 1024;)

Read only are constants and not a replacement, the only difference is how they accessed.
 
Runtime Constants(read-only) are usually the best choice, and are much better if the value might or has a one in a million chance of changing.
 
const or compile-time constants should only be used for performance critical situations, and if the value will NEVER change between any release.
 
 

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16899
  • Superior Stupidity at its best
Re: private readonly class variables - why?
« Reply #9 on: June 12, 2013, 06:34:43 PM »
I'll not be changing from "private const" to "private readonly" but I will start using "private readonly" for values that are only filled/modified via the constructor ... that only makes sense ... mainly because they are private and for code maintenance purposes it makes more sense.
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

CADbloke

  • Bull Frog
  • Posts: 342
  • Crash Test Dummy
Re: private readonly class variables - why?
« Reply #10 on: June 12, 2013, 10:54:09 PM »
Hijack!  :-D From a code maintenance point of view you are better off using properties. See http://stackoverflow.com/questions/1180860/public-fields-versus-automatic-properties and especially
Quote
Changing from a field to a property breaks the contract (e.g. requires all referencing code to be recompiled). So when you have an interaction point with other classes - any public (and generally protected) member, you want to plan for future growth. Do so by always using properties.
from http://stackoverflow.com/a/1180864/492 (same page)

On the original topic, I avoid constants like the plague because the .NET C# compiler hardcodes them into their actual values, even in the calling assemblies.

Keith™

  • Villiage Idiot
  • Seagull
  • Posts: 16899
  • Superior Stupidity at its best
Re: private readonly class variables - why?
« Reply #11 on: June 12, 2013, 11:43:38 PM »
Hijack!  :-D From a code maintenance point of view you are better off using properties. See http://stackoverflow.com/questions/1180860/public-fields-versus-automatic-properties and especially
Quote
Changing from a field to a property breaks the contract (e.g. requires all referencing code to be recompiled). So when you have an interaction point with other classes - any public (and generally protected) member, you want to plan for future growth. Do so by always using properties.
from http://stackoverflow.com/a/1180864/492 (same page)

However, when accessing the variables directly in the class only, coding a property creates additional overhead.

In this very simplified example, you can what I mean.

Code - C#: [Select]
  1. private readonly int _item = -1;
  2.  
  3. private int Item
  4. {
  5.     get
  6.     {
  7.         return _item;
  8.     }
  9. }
  10.  
  11. public Foo(int Item)
  12. {
  13.     _item = Item;
  14. }
  15.  
  16. public int Bar()
  17. {
  18.     //return Item * 2; //calls Item property which returns the value of _item to the function which returns the value of Item * 2 to the calling function
  19.     return _item * 2; //returns the value of _item * 2 to the calling function
  20. }
  21.  

So, I'd have to conclude that if you don't intend on the value of the private readonly variables to escape the class, turning them into properties is just more code to have to deal with.

On the original topic, I avoid constants like the plague because the .NET C# compiler hardcodes them into their actual values, even in the calling assemblies.

That is exactly why I use them in so many instances ... the value is compiled into the code explicitly or so I don't have to remember the value six months after the original code was written ...

If you notice what I posted earlier, you will see that I also don't use constants outside of the class in which they are defined. All of my constants are private.
Proud provider of opinion and arrogance since November 22, 2003 at 09:35:31 am
CadJockey Militia Field Marshal

Find me on https://parler.com @kblackie

CADbloke

  • Bull Frog
  • Posts: 342
  • Crash Test Dummy
Re: private readonly class variables - why?
« Reply #12 on: June 13, 2013, 12:30:33 AM »
Keith, I agree with you on your use-cases, namely all privately inside the class. I added my info for folks who drive-by this post and perhaps interpret these scenarios in a wider use-case that could create coupling and dependency issues via painting yourself into a corner with public fields and constants.

The point I was making (badly) with outwardly accessible constants is that they are "baked in" to their various assemblies as their literal value, not as any type of reference to a variable. See the top answer at http://stackoverflow.com/questions/55984/what-is-the-difference-between-const-and-readonly.

MexicanCustard

  • Swamp Rat
  • Posts: 705
Re: private readonly class variables - why?
« Reply #13 on: June 13, 2013, 07:19:38 AM »
Constants are compiled by your compiler, readonly is compiled by the JIT compiler.

So, if you had a const in assembly "A"  that was public and used by assembly "B".  That const is compiled by the compiler in both assemblies. If you make a change to the const you must recompile both assemblies.

If the variable was readonly you would only have to re-compile assembly "A" and assembly "B" would be changed by the JIT compiler.

Not really applicable to your question since you are using private variables in this situation.
Revit 2019, AMEP 2019 64bit Win 10