David Klempfner
David Klempfner

Reputation: 9870

Using a const inside a method

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.

Upvotes: 5

Views: 3505

Answers (2)

radarbob
radarbob

Reputation: 5101

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.

Upvotes: 10

Trevor Ash
Trevor Ash

Reputation: 633

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.

Upvotes: 5

Related Questions