Re: scope of variables

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

For the record, I have no interest in "declaring variables willy-nilly". I like to declare them at the top of a file or at the top of a procedure.

I haven't found the need to mask a file-level variable in a procedure, but it makes sense to me since other languages work that way. Since unnamed blocks are like procedures I think that it should work the same way.

Declaring variables inside of the scope can make mainteance and readability much easier. It keeps variable definition close to variable use.

i.e.

function copy_file(sequence from_fname, sequence to_fname) 
    integer status 
 
    status = c_func(hCopyFile, { ... }) 
    if status = BAD then 
        sequence error_message = c_func(hErrMessage, { ... }) 
 
        log_error(error_message) 
 
        return { status, error_message } 
    end if 
 
    return status 
end function 

It can also prevent declaration when not necessary, i.e.

function backup_file(sequence fname) 
    sequence full_fname = absolute_filename(fname) 
 
    if not file_exists(full_fname) then 
        return { 0, "Source file not found" } 
    end if 
 
    sequence backup_fname = full_fname & ".bak" 
    if file_exists(backup_fname) then 
        return { 0, "Backup file already exists" } 
    end if 
 
    integer status = copy_file(full_fname, backup_fname) 
    if status = BAD then 
        sequence error_message = blah() 
        log_failure(error_message) 
        return { status, error_message, full_fname, backup_fname } 
    end if 
 
    return status 
end function 

Those are just two very simplistic examples. Declaring those at the top of the method declares variables that will not be used most of the time (a valid copy/backup). It also makes the point of definition futher from the point of use making it more difficult to follow when you begin to have hundreds of methods in your program. Code templates also can not be used as much if all variables are declared at the top of the procedure/function, reducing the automation gained by your editor/IDE and increasing potential for bugs. Declaring at the top instead of close to the use also encourages one to "reuse" a variable w/a slightly incorrect name. Another problem with declaring at the top is that the temp variable is not cleared until it goes out of scope, thus your program will use more memory (maybe not an issue for most routines but some it can be significant).

Much more complex examples of how declaring variables close to their use and w/in the blocks they are to be used can be found throughout the standard library, various 4.0 projects and various places in Euphoria code.

Jeremy

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

Search



Quick Links

User menu

Not signed in.

Misc Menu