Function level constants - declared at the top of the function?

I have a constant value that I only plan to use once in my codebase. I'm going to announce it using an ad const

.

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

+1


source to share


4 answers


The two reasons for using a constant rather than hard-coding are for readability and so it can be easily found and changed later, right? So declare it where it's easiest to find it later. I usually find this to be at the beginning of a function, class, or file - again, no matter how large it makes sense.



+3


source


I am looking at constants as a kind of configuration. If they can change, they become application properties if they cannot put them on 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

+2


source


I usually declare them as close to where I will be using them as possible.

The reason is that when I go through other people's code it is very awkward to jump up and down the file to understand what is going on. Therefore, I try to make it easier to work with others when writing code.

For a small (ish) function, the top of the function may increase readability (and thus clarity to others), so this rule is far from being etched in stone.

+1


source


I put them at the beginning of the file, treating them as configuration throughout the class. Also, when coding with mouse only and no matter the location, your shiny IDE will let you know.

It's not something that you constantly change, if you don't enter your constant, code, try whatever you want when you refactor and make it permanent.

0


source







All Articles