5

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.

3 Answers 3

13

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.

3

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.

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.