tags:

views:

216

answers:

3

Hi,

I have seen these two approaches for constant declaration which are to be used in the project.

  1. Constants in a public module.

  2. Constants in a NonInheritable(Sealed) class

Does anybody uses any other approach for the constant declartion ?

Is there any difference between these approaches, any pros and cons ?

Thanks.

+11  A: 

Put the constant in the class where it's most relevant - e.g. Math.Pi, Int32.MinValue etc.

I've seen various constants which should actually be enums, too - particularly for status codes etc.

I don't think it's wise to create a class (or module) just for constants unless there really is no sensible class that those constants are associated with.

Jon Skeet
+2  A: 

I agree with @Jon. However, for constants that are unique to your application -- i.e., they are configuration defaults, tuning parameters, etc., I sometimes create a strongly-typed static configuration class to hold them. I expose the values via properties with only public getters defined. This way they can be loaded from a configuration file, but referenced throughout your code as fixed values.

tvanfosson
+1  A: 

My practice is similar to what Jon states. The vast majority of the enums and constant are obviously tied to a particular class or module and are declared public in there.

The lowest level of my software is called Utility and contains math routines and other functions and method of general utility (rather than specific utility to that application's mode). In there is a module that has as a bunch of function that just are utility functions/subroutines that have no common theme. It is in that one area that any enums or constant go.

There is a similar area for the application model where utilities that are of general use for that application go. And that where constants that can't be tied to any one class of the MODEL go.

So there three areas where constant can be found in my personal framework

The class declarations The general utility module of the application model The general utility module of the utility assembly.

In practice only a handful out of dozens of enum and constant ever needed to be declared in either utility modules. Most of those are Win32 decelerations used by Win32 function that are imported into my assembly.

RS Conley