Re: scope of variables

new topic     » goto parent     » topic index » view thread      » older message » newer message
coconut said...

here an example, an editor as a text buffer with cursor position referenced by 2 top level variables bcol and bline and there is a procedure that modify the content of that buffer but must leave cursor position unchanged at exit. all the code elsewhere use bcol and bline to access character in buffer. It make sense to use local variables of same name inside that procedure

sequence buffer -- text buffer 
sequence bcol -- cursor column 
sequence bline -- cursro line 
 
--insert text at current cursor position and leave cursor where it is. 
procedure insert_text(sequence text) 
integer bcol=bcol -- local copy 
integer bline=bline -- local copy 
--- code here 
    
end procedure 
-- at exit bcol and bline are preserved without need to restore from a temporary storage 

That's bad practice. You know there is a global (file level) bcol, bline. Now imaging scrolling from the bottom of your file up browsing code trying to figure out why your bcol and bline variables are getting out of sync and you see the bottom end of your routine:

    bcol += 10 
    bline+= 10 
    set_line("Hello, World!") 
end procedure 

What will you think? You don't even know what method you are in at this point. Now, imagine if you would have named the variables to their real meaning, not simply shadowed a well used, well known name (why else would it be at the file level?):

    local_bcol += 10 
    local_bline+= 10 
    set_line("Hello, World!") 
end procedure 

Now what do you think? You keep on scanning looking for why your bcol and bline variables are getting screwed up.

Jeremy

new topic     » goto parent     » topic index » view thread      » older message » newer message

Search



Quick Links

User menu

Not signed in.

Misc Menu