Ask your own question, for FREE!
MIT 6.00 Intro Computer Science (OCW) 41 Online
OpenStudy (anonymous):

Question on PSs 5 and 6: Why are the functions passing word_list around?

OpenStudy (anonymous):

Specifically: word_list is defined globally--why do functions need to get it as an argument? Is it set up that way just to provide for the possibility of using a different list?

OpenStudy (anonymous):

I think it is a good design pattern. It makes the functions that use the word list independent of the word list being used. You'd be amazed at how much trouble you can get into by having too many global variables that you have to keep track of. I don't think the "different list" idea would hold water, because you could meet that objective by just supplying a different filename instead of "words.txt". I think the purpose is to minimize the number of global variables, which have a well-earned bad reputation.

OpenStudy (anonymous):

Yeah, that's what it looked like to me, but I wanted to make sure I wasn't missing anything. Thanks!

OpenStudy (shadowfiend):

It's definitely a good idea to do things that way. It's declared as a global variable more as a matter of simplicity than anything else. The starting point that defines the initial word list could just as easily have been in a function that was then invoked as the only thing happening at the top level; e.g.: def doProgram: word_list = [] # do stuff with word_list doProgram()

OpenStudy (anonymous):

That makes sense--If I understand correctly, you're saying that if it was declared in the function the way you have it, it would be local to that function and thus it would need to be passed explicitly to every function that needed it. Your explanation makes it clearer. Thanks!

OpenStudy (shadowfiend):

Correct. And in most applications, you write everything in other classes and functions, and the only thing at the very top level is a call to a function that kicks it all off.

Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!
Can't find your answer? Make a FREE account and ask your own questions, OR help others and earn volunteer hours!

Join our real-time social learning platform and learn together with your friends!