In this example the difference is that you wrote an extra line in the first.
There’s zero advantages there, and the only reason I see people using it like that is that they don’t know what is a variable and what it is for. Of course, the taste of the person may be another reason, but there is reason.
If it had a more complex expression, I would understand that it was done earlier and kept in a variable with a significant name. A name that is not informative or indicates obviousness does not increase readability.
If the value was used elsewhere there is the exact reason for a variable to exist.
Do something because one day you might need to violate the principle of YAGNI, and a certain form of KISS. Having a good IDE change the expression to a variable if you need it is the simplest thing you have.
It’s not to save code, it’s to simplify code. Putting the declaration/definition of what you will use as close as possible to where it is used usually gives more readability. Long code is harder to follow. Apart from the semantics that if there is a variable it is because it must be used in several places. Code is expression, when expressed wrong gives the wrong idea and makes the code convoluted.
Depending on the language there is a difference in performance and even memory consumption.
Never do anything without knowing why you’re doing it. Don’t go on automatic, don’t follow rules that others have said is good. Look for what’s good for you, but do it with choice awareness.
It is usually by readability or error handling, I think there is a specific reason. For example, there could be an error in the line
$sql
that if you put directly on the line$result
the difficulty of finding the error is greater. It’s just an example.– bio
It does not affect performance or security. It only affects your code. I am one of those who prefer to use the first example. For me it is more readable and practical, in case I need to use the same variable later, it already exists, just use.
– Francisco
@Francisco, you’re right, there’s still the reuse I forgot to mention.
– bio