Mailing List Archive: 49091 messages
  • Home
  • Script library
  • AltME Archive
  • Mailing list
  • Articles Index
  • Site search

[REBOL] Re: About Standards and Best Practices

From: rebol:techscribe at: 3-Sep-2003 9:25

Hi. Another issue that comes to mind is name space and side effects. If a function introduces a word that will be used within the context of that function only, then that word should be declared local to the function in order to avoid name clashes that may result in unexpected side effects: f: func [ /local word] [ word: "function's local word." ] This prevents errors that result from setting a global word to some value, then evaluating a function that happens to set the same word locally to a different value, and then continuing to use the global word. This is especially critical if functions are reused either by their original author or by some unsuspecting consumer. Example: ;--- consumer's script REBOL [] ;- globally declared word erase-harddrive-completely?: NO ;- evaluating function from a downloaded library do %down-loaded-library ;- contains function list-directory this-dir-contents: list-directory . . . if erase-harddrive-completely? [ erase-harddrive-completely ] ;--- end user's script So, what's the problem? Imagine the function "borrowed" from the downloaded library looks like this: ;--- function in downloaded library -- list-directory: func [ /interactive ] [ erase-harddrive-completely?: "No" directory-listing: read %. if interactive [ display-directory-listing erase-harddrive-completely?: ask "Should I erase the hard drive completely?" ] directory-listing ];---- end libraray function ---- Note that the user's script sets erase-harddrive-completely? to the logic! value No, whereas the function sets the word erase-harddrive-completely? to the string! "No". The string! "No", however, evaluates as a logic! True:
>> a: No
== false
>> if a [ print "yes" ]
== none
>> a: "No"
== "No"
>> if a [ print "yes" ]
Thus, the harddrive will be erased, even though the library function consumer smartly set the erase-harddrive-completely? word to No. If, however, the library function provider had used a /local word in his function, then it would have not had any affect on the global word. Take Care, Elan