Correct way for constants
-
Hi Can somebody point me to a standard/common method of storing and retrieving constants in code? The things that come to my mind: 1) Strore them in a module. Drawback: Would not know the origins of the constant by reading the code. There can be more than one module and constants can be spread across them.. 2) Store them in a class as Shared (static in C#) variables. Drawback: Cannot define them as const, hence the probability of somebody changing the value remains. 3) Store them in a class as Shared (static in C#)ReadOnly Properties. Drawback: None that I can see (actually this occurred to me while typing this post). What would be your suggestions and what do you do? As an aside, do you follow some naming convention for these constants to denote what they might contain and to help in classification?
Shreekar
-
Hi Can somebody point me to a standard/common method of storing and retrieving constants in code? The things that come to my mind: 1) Strore them in a module. Drawback: Would not know the origins of the constant by reading the code. There can be more than one module and constants can be spread across them.. 2) Store them in a class as Shared (static in C#) variables. Drawback: Cannot define them as const, hence the probability of somebody changing the value remains. 3) Store them in a class as Shared (static in C#)ReadOnly Properties. Drawback: None that I can see (actually this occurred to me while typing this post). What would be your suggestions and what do you do? As an aside, do you follow some naming convention for these constants to denote what they might contain and to help in classification?
Shreekar
There are two types of constant values, constants and read-only members. You have to decide what type you want to use. Constants are compiled into the code, so if you use a constant from a different project, and then change the constant in that project, you have to recompile the code that uses the constant in order for it to change there too. Read-only members are read from the source every time, so if you change the value, it's guaranteed to change everywhere it's used. Also, a read-only member can get it's value from an external source like AppSettings. If the external source is expensive to read (like a file or a web service), you can read it the first time it's used and cache it in a local variable. I usually create a static class called Settings where I put application wide constants and settings. It will contain constants and read-only static properties.
--- Year happy = new Year(2007);