views:

168

answers:

4

I have a constant value that I only plan to use once in my codebase. I am going to declare it using a const declaration.

If this was a function-level variable I would declare it at the point of usage, but doing so with a constant just seems to clutter my function.

+2  A: 

I look a constants as a kind of configuration. If they can change they become application properties, if they can't I put them at the top of the class in which they will be used even for function level constants.

This way you can just open the file and see them all in one list

TimothyP
+3  A: 

The two reasons for using a constant instead of hard-coding a value is for readability and so it can be easily found and changed later, right? So declare it where it would be most easily found later. Usually I find this is at the beginning of the function, class, or file - again, whatever scope makes sense.

lc
+1  A: 

I usually declare them as close to where I'll use them as possible.

Reason is that when I'm going through other people's code, it's very inconvenient to have to jump up and down a file to understand what's going on. So I try to make it easy on others when writing code myself.

For small(ish) function at the top of the function could increase readability (and hence understandability for others), so this rule is far from etched in stone.

Pieter
get a better ide where you can hover the identifier and get info about it including its integral constant value
A: 

I put them in the beginning of the file, treats them as configuration all over the class. Also while coding just mouse-over and regardless of the location your shiny IDE will tell you the value of it.

It's not something you keep changing if it's don't introduce your constant yet, code it, try whatever you want then when you done refactor, and make it a constant.

dr. evil