3

If you need to use a constant inside only one method, should you declare it in the method or as a field?

Also, if you should declare it in the method, then should you use a lowercase or uppercase first letter for the name?

EDIT: This is not a duplicate because I am asking whether or not you should declare the const in your method or as a field.

David Klempfner
  • 8,700
  • 20
  • 73
  • 153
  • check out this for the diff of constant in method vs in class: https://stackoverflow.com/questions/6373072/defining-local-variable-const-vs-class-const – Bishoy Oct 23 '15 at 02:38
  • 1
    Possible duplicate of [C# naming convention for constants?](http://stackoverflow.com/questions/242534/c-sharp-naming-convention-for-constants) – Will Oct 23 '15 at 02:45

2 Answers2

9

In general, declare variables in the narrowest scope practical. If you need that thing to have global scope in the future, ok fine, then make it global in the future.

The above reinforces appropriate, desired, encapsulation and abstraction.

  • It helps clients by exposing a coherent, expressive API without mystery bits hanging around the corners.
  • It helps the maintenance programmer by signaling something about the design and intended use of the variable.
radarbob
  • 4,964
  • 2
  • 23
  • 36
  • 3
    Putting a constant that's specific to a method outside of the method is just asking for trouble. – Rob Oct 23 '15 at 02:56
4

Standards are just that, standards. My team happens to use NameOfConstant instead of NAMEOFCONSTANT or NAME_OF_CONSTANT for constants. If the constant is only used within a method, the best (from a coding maintenence/readability perspective) is to place it inside the most constrained place possible. In this case that would be inside the only method using it.

Trevor Ash
  • 623
  • 4
  • 8