ProgrammingThis forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.
Notices
Welcome to LinuxQuestions.org, a friendly and active Linux Community.
You are currently viewing LQ as a guest. By joining our community you will have the ability to post topics, receive our newsletter, use the advanced search, subscribe to threads and access many other special features. Registration is quick, simple and absolutely free. Join our community today!
Note that registered members see fewer ads, and ContentLink is completely disabled once you log in.
If you have any problems with the registration process or your account login, please contact us. If you need to reset your password, click here.
Having a problem logging in? Please visit this page to clear all LQ-related cookies.
Get a virtual cloud desktop with the Linux distro that you want in less than five minutes with Shells! With over 10 pre-installed distros to choose from, the worry-free installation life is here! Whether you are a digital nomad or just looking for flexibility, Shells can put your Linux machine on the device that you want to use.
Exclusive for LQ members, get up to 45% off per month. Click here for more info.
I just came across the book Code Complete, 2nd Ed on amazon. It comes with a checklist to ensure you write maintainable code.
From the PDF
Chapter 10: General Issues In Using Variables
Other General Issues in Using Data (p. 17)
One of the points says:
Quote:
Do all variables have the smallest scope possible?
When referring to variable scope, do they mean large scale applications and using classes to achieve encapsulation? Suppose I had a script that doesn't use classes, but a List and functions to do certain tasks, example, a backup script:
Code:
def read_data_from_file(file_to_read):
#code to read from file and build list
return list_of_files
def copy_files_to_backup_folder(file_to_copy):
#code to copy files
file_name="some/path/to/file"
files_to_backup = read_data_from_file(file_name)
for f in files_to_backup:
copy_files_to_backup_folder(f)
Do you have to worry about variable scope when writing scripts for common admin tasks? In this case file_name?
This could just as easily have been a bash script, and other than declaring a variable inside a function, I don't see how you can limit variable scope.
How would you properly declare it to limit the variable scope as suggested by the checklist/book?
Variable scope seems to me to be far more important when you have large code files and numerous files as part of a project.
Within the limits of a BASH script file, the only scope rule I'm aware of is "if it hasn't been declared yet, then referencing it in advance of a declaration will be a problem."
My own opinions:
I feel that BASH variables are the same as file scope.
If you use a BASH function to do a specific task for you, you are likely separating the data and operations so that the function does it's work as designed and returns a specific result.
If you declare a variable within a function, and then use that variable somewhere else in the main section of your script, it seems as if you've contradicted the purpose of creating a function to separate operations.
Suppose I had a Python script written exactly as I have in my example above, is worrying about variable scope necessary? Is there anything wrong by making the file_name a variable in the main? I personally don't see a problem, because file_name could be used elsewhere, for example, writing a log, or error handling. My point is, when writing scripts to automate day-to-day tasks, is variable scope something you need to worry about? When referring to variable scope that the PDF is talking about, what context are they talking about?(I think this a better question, and the one I really want to ask) Large scale enterprise level applications and scripts for day-to-day tasks, or just large scale applications
Last edited by svetlanarosemond; 12-01-2017 at 07:26 AM.
Once again, my feeling is that script variables are file scope.
I have just run a BASH test to declare and run a function:
Code:
test()
{
a=1;
}
And later, outside of this function, before invoking it, and after invoking it, I echoed out the value of variable "a". The first echo resulted in nothing, because variable "a" was never declared. The second echo resulted in "1". Meanwhile neither of these echo calls were part of function test().
Therefore the variable is file scope.
What do you need to worry about? Simply the fact that the variable name is file scope and if you intend to have several variables named "a", you really cannot and will not, they will instead be the same variable.
Once again, my feeling is that script variables are file scope.
...
What do you need to worry about? Simply the fact that the variable name is file scope and if you intend to have several variables named "a", you really cannot and will not, they will instead be the same variable.
What do you need to worry about? Simply the fact that the variable name is file scope and if you intend to have several variables named "a", you really cannot and will not, they will instead be the same variable.
It's still possible to declare a local variable inside a function, no?
Code:
bla()
{
local a=2
echo "a = $a"
}
a=3
echo "a = $a"
bla
echo "a = $a"
Quote:
and other than declaring a variable inside a function, I don't see how you can limit variable scope.
Ah! I didn't read that part, sorry for being off topic then
Ah! I didn't read that part, sorry for being off topic then
Don't worry about it.
My initial concern is, my example Python script could be written in bash/powershell/batch scripts, no need to use Python, but suppose if you insist on continuing with Python, when using variables like I have, with file_name, files_to_backup, is that okay? What context is the Book\PDF referring to when they ask
Quote:
Do all variables have the smallest scope possible?
Declaring variables that could be used elsewhere in your script(I could use it for writing a log) in the main, to me seems fine. However, I'm in no position to say if it's correct.
I assume they aren't talking about scripts for day-to-day admin tasks, but rather large scale applications where classes are involved, and you'd want to limit variables that don't need to be exposed.
Last edited by svetlanarosemond; 12-01-2017 at 09:00 AM.
I think the key is context.
In your script example 'file_name' looks like a constant. So for usefullness, its accessibility needs to be on global scope.
I think the key is context.
In your script example 'file_name' looks like a constant. So for usefullness, its accessibility needs to be on global scope.
What about files_to_backup? That list might be used elsewhere as well, for example, I could generate a log about which files were successfully backup and which weren't.
What about files_to_backup? That list might be used elsewhere as well, for example, I could generate a log about which files were successfully backup and which weren't.
Yes true, I meant don't forget the usefullness part of programming.
If your script is a sort of library script, which will be included in other script maybe by other users than you. You don't ship the library and says "these variable names are not allowed anymore because they are used in the library"
Don't worry about it.
My initial concern is, my example Python script could be written in bash/powershell/batch scripts, no need to use Python, but suppose if you insist on continuing with Python, when using variables like I have, with file_name, files_to_backup, is that okay? What context is the Book\PDF referring to when they ask
Declaring variables that could be used elsewhere in your script(I could use it for writing a log) in the main, to me seems fine. However, I'm in no position to say if it's correct.
I assume they aren't talking about scripts for day-to-day admin tasks, but rather large scale applications where classes are involved, and you'd want to limit variables that don't need to be exposed.
You could have scripts that are VERY large for day-to-day tasks...you never know what you're going to encounter or need. In the example you cite about the log file, that's where "global" variables come in, and if they're useful throughout your program, that's why you define them.
But I think the big take-away from your thread and that book should be "Learn good practices and use them". Use what you *NEED* going in to a routine, and clear/close/release those things when you are done with them. There are never going to be 100% hard-and-fast rules...if you program for ANY length of time, you will wind up kludging something together and it will be some of the ugliest junk you've ever seen. But sometimes, you HAVE to throw elegance out the window to get a result.
Personally I don't feel that making this much out of variable scope in a script is worth this much thought or analysis.
Secondly, per the examples offered, you can test how scope is applied or treated, by writing additional lines in your script to test and give you debug.
I'm not much of a python script person, but I've done a good amount of bash scripting and it's always been one file, the script has a main section, and then it may have functions. When I have functions, if I happen to use a variable in them, I'll treat it as local scope to the function even if I hadn't used the "local" declaration, which I never knew about in the first place. Yes there's a risk that I could make an error with re-using a variable name; however I also don't use simple variable names, if my variable means "position in string", then it will be named, $POSITION_IN_STRING.
Another example, not properly written at all, but say I'm doing a sort, and I decide two list members need to be swapped, I'd have a function called "swap()" and I'd also pass the reference locations for the members to be swapped to the function but probably have the full list as global:
Code:
# More like pseudocode
swap(first_loc, second_loc)
{
temp_value = G_ARRAY[first_loc];
G_ARRAY[first_loc] = G_ARRAY[second_loc];
G_ARRAY[second_loc] = temp_value;
}
# Some amount of the main code
if(members need to be swapped, send their locations to the swap function)
swap(first_location second_location);
fi
if you program for ANY length of time, you will wind up kludging something together and it will be some of the ugliest junk you've ever seen. But sometimes, you HAVE to throw elegance out the window to get a result.
I don't have that much professional programming experience, so I don't really know when my code is ugly. This is why I ask questions about code quality, and when to follow a guideline. Problem is, I take guidelines as rules that must be followed strictly, but I've seen here and elsewhere that it's just a guideline, not something set in stone.
I don't have that much professional programming experience, so I don't really know when my code is ugly. This is why I ask questions about code quality, and when to follow a guideline. Problem is, I take guidelines as rules that must be followed strictly, but I've seen here and elsewhere that it's just a guideline, not something set in stone.
That's 100% true. I don't think there is a programmer ANYWHERE that ever looks at anything they've written (me included) after some time has elapsed and not thought "Wow...I'm a TOTAL IDIOT..this could have been so much better..."
With any skill, it's always a process of learning. You'll learn lots by doing that is never taught in a book. Don't concentrate on your coding style so much, as in your way of thinking about a problem. If you have 100 things to process, think about those things; can you write one small routine to modify each one and just call it over and over, rather than writing 100 that all basically do the same thing.
Over time your code will get smaller and smaller; faster and faster...because of the knowledge you'll gain. I've written SQL queries that take minutes to run, only to have a professional DBA look at it and make a few small tweaks, and get it to run in SECONDS. All about experience.
LinuxQuestions.org is looking for people interested in writing
Editorials, Articles, Reviews, and more. If you'd like to contribute
content, let us know.