Self-Documented Code is Easier to Read and Maintain
Follow the Principle of Least Atonishment and of the precept of code-as-documentation: use one variable for one goal, to both make its use easy to understand and the code easy to read without explanations.
Correctly Structured Code is Easier (thus Cheaper) to (Re)Use
Also, here it would appear that query
is always used to prepare a statement before executing it. That's probably a sign that you want to refactor part of this code into one (or more) helper methods to prepare and execute the query (to comply to the DRY principle).
This way, you'll effectively:
- use only one variable in your helper method to identify the query of the current context,
- need to type less code everytime you want to re-execute a query,
- render your code more readable for others.
Examples:
Consider this, taken from your example, where the refactored version is obviously better. Of course your snippet was just an example for the purpose of this question, but the concept still holds true and scales.
Your Example 1:
Strings querycre,queryins,queryup,querydel;
querycre = 'Create table XYZ ...';
execute querycre ;
queryins = 'Insert into XYZ ...';
execute queryins ;
queryup = 'Update XYZ set ...';
execute queryup;
querydel = 'Delete from XYZ ...';
execute querydel ;
Your Example 2:
Strings query;
query= 'Create table XYZ ...';
execute query ;
query= 'Insert into XYZ ...';
execute query ;
query= 'Update XYZ set ...';
execute query ;
query= 'Delete from XYZ ...';
execute query ;
Example 3 (Refactored pseudo-code):
def executeQuery(query, parameters...)
statement = prepareStatement(query, parameters);
execute statement;
end
// call point:
executeQuery('Create table XYZ ... ');
executeQuery('Insert into XYZ ...');
executeQuery('Update XYZ set ...');
executeQuery('Delete from XYZ ...');
The benefit shows with regular reuse.
Personal Anecdote
I originally started as a C programmer working with limited screen real-estate, so re-using variables made sense both for the compiled code (back then) and to allow more code to be readable at once.
However, having then moved on to higher-level languages and brushed up on functional programming, I took the habit of using immutable variables and immutable references whereever possible to limit side-effects.
What's In It For Me?
If you take the habit of having all your function's inputs be immutable and to return a new result (as a true mathematical function would), you get into the habit of not duplicating stores.
By extension, this leads to:
- you writing short functions,
- with well-defined objectives,
- that are easier to understand,
- to re-use,
- to extend (whether by OO inheritance or by functional chaining),
- and document (as already self-documenting).
I'm not saying there's no benefit to mutable state here, I'm just pointing out how the habit might grow on you and how it impacts code readability.