In Java, I consider it a best practice to replace string literals with a constant variable any time they are used in more than one place and expected to match. For example, if you're going to set a cookie and then later read it back, the name of the cookie should be in a constant so the compiler can help you catch spelling errors, not to mention allowing you to have a readable variable name versus the actual value of the String.
I'm reviewing some code like this in JavaScript and I'm inclined to recommend that the literals be replaced with a constant. However, I'm not sure the same reasons apply since there isn't a compiler and the cookie name is just as descriptive as a variable name would be.
Edit: Related to comments and responses received so far, I am definitely more concerned with the usage of constants versus how they are actually implemented. I see their value in Java and other compiled languages as a way to prevent errors, but I'm not sure I see the same value in Javascript.
As a documentation mechanism, say for magic numbers, I think having a named variable (even if it's not enforced as a constant) is still a good way to improve readability. But for string literals, I'm not sure this:
var trackingCookieName = "trackingCookie";
is any better than just using "trackingCookie" since you could typo either the literal or the variable name and either way, it would only be caught at runtime.
Literals are often used more than once in your code. Having them defined as a constant reduces typos in your code and improves the maintainability.
String constants, also known as string literals, are a special type of constants which store fixed sequences of characters. A string literal is a sequence of any number of characters surrounded by double quotes: "This is a string."
A literal is a value that is expressed as itself. For example, the number 25 or the string "Hello World" are both literals. A constant is a data type that substitutes a literal. Constants are used when a specific, unchanging value is used various times during the program.
The characters of a literal string are stored in order at contiguous memory locations. An escape sequence (such as \\ or \") within a string literal counts as a single character. A null character (represented by the \0 escape sequence) is automatically appended to, and marks the end of, each string literal.
Extracting string literals to constants means
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With