LinuxQuestions.org
Visit Jeremy's Blog.
Home Forums Tutorials Articles Register
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 12-01-2017, 06:53 AM   #1
svetlanarosemond
LQ Newbie
 
Registered: Nov 2017
Posts: 14

Rep: Reputation: Disabled
Variable Scope for Scripts


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?

When should you worry about variable scope?
 
Old 12-01-2017, 07:18 AM   #2
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,882
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
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.
 
1 members found this post helpful.
Old 12-01-2017, 07:24 AM   #3
svetlanarosemond
LQ Newbie
 
Registered: Nov 2017
Posts: 14

Original Poster
Rep: Reputation: Disabled
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.
 
Old 12-01-2017, 07:35 AM   #4
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,882
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
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.
 
1 members found this post helpful.
Old 12-01-2017, 07:51 AM   #5
svetlanarosemond
LQ Newbie
 
Registered: Nov 2017
Posts: 14

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by rtmistler View Post
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.
Thanks for the clarification!
 
Old 12-01-2017, 08:27 AM   #6
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
Quote:
Originally Posted by rtmistler View Post

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

Last edited by keefaz; 12-01-2017 at 08:35 AM.
 
1 members found this post helpful.
Old 12-01-2017, 08:42 AM   #7
svetlanarosemond
LQ Newbie
 
Registered: Nov 2017
Posts: 14

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by keefaz View Post
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.
 
Old 12-01-2017, 09:00 AM   #8
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
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.
 
Old 12-01-2017, 09:17 AM   #9
svetlanarosemond
LQ Newbie
 
Registered: Nov 2017
Posts: 14

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by keefaz View Post
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.
 
Old 12-01-2017, 09:22 AM   #10
keefaz
LQ Guru
 
Registered: Mar 2004
Distribution: Slackware
Posts: 6,552

Rep: Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872Reputation: 872
Quote:
Originally Posted by svetlanarosemond View Post
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"
 
Old 12-01-2017, 09:23 AM   #11
TB0ne
LQ Guru
 
Registered: Jul 2003
Location: Birmingham, Alabama
Distribution: SuSE, RedHat, Slack,CentOS
Posts: 26,634

Rep: Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965
Quote:
Originally Posted by svetlanarosemond View Post
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.
 
Old 12-01-2017, 09:29 AM   #12
rtmistler
Moderator
 
Registered: Mar 2011
Location: USA
Distribution: MINT Debian, Angstrom, SUSE, Ubuntu, Debian
Posts: 9,882
Blog Entries: 13

Rep: Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930Reputation: 4930
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
 
Old 12-01-2017, 10:38 AM   #13
svetlanarosemond
LQ Newbie
 
Registered: Nov 2017
Posts: 14

Original Poster
Rep: Reputation: Disabled
Quote:
Originally Posted by TB0ne View Post
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.
 
Old 12-01-2017, 11:58 AM   #14
TB0ne
LQ Guru
 
Registered: Jul 2003
Location: Birmingham, Alabama
Distribution: SuSE, RedHat, Slack,CentOS
Posts: 26,634

Rep: Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965Reputation: 7965
Quote:
Originally Posted by svetlanarosemond View Post
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.
 
1 members found this post helpful.
Old 12-08-2017, 04:33 AM   #15
SAbhi
Member
 
Registered: Aug 2009
Location: Bangaluru, India
Distribution: CentOS 6.5, SuSE SLED/ SLES 10.2 SP2 /11.2, Fedora 11/16
Posts: 665

Rep: Reputation: Disabled
Quote:
Originally Posted by TB0ne View Post
With any skill, it's always a process of learning. You'll learn lots by doing that is never taught in a book.

All about experience.
That's a very strong point made here.
 
  


Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
(Scope of address) == (scope of variable) kaz2100 Programming 10 01-26-2014 10:54 PM
[SOLVED] (BASH) How to keep variable in scope? Dick Dastardly Programming 8 07-15-2011 12:51 PM
Variable scope in KSH v5.2.14 99/07/13.2 UltramaticOrange Programming 4 08-20-2008 10:41 AM
Variable scope Ephracis Programming 5 07-28-2006 01:22 PM
Variable available scope problem ArthurHuang Programming 1 05-22-2006 12:16 AM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 11:43 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration