1. Re: When to use Which variable type?
- Posted by Robert Craig <72614.1667 at COMPUSERVE.COM> Oct 10, 1996
- 1643 views
Lucien T. Elliott writes: > is there any rule (or logic) as to when one should use an object, > or a sequence, or any other types over others? For me it's quite simple. I consider the set of possible values that might be assigned to a given variable during execution of my program. I then choose the most restrictive of the predefined types (object, sequence, atom, integer). For small programs I usually leave it at that, but for larger programs I may go a step further and define my own new type that is more specialized or restrictive, especially if I expect to have many variables of that type. I do this mainly for the tighter error-checking that I get, but it also helps to document the purpose of that variable better. > in the collection of code that i have studied thus far, there seems > to be no logic as to why a variable is defined as a sequence or > as an object. If a variable can only be assigned a sequence value then I will normally declare it as a sequence. However, consider the case of a variable that is assigned the result of gets(). Normally a sequence is returned by gets(), but at end-of-file a -1 atom will be returned. If you declare x as a sequence and you execute: x = gets(file_num) when it's the end-of-file, Euphoria will pull the plug on your program and report a type_check failure. You should declare x as an object so both sequences *and* atoms (such as -1) can be legally assigned to it. You could then have a test like: x = gets(file_num) if atom(x) then exit -- end of file! end if to handle the end-of-file situation. Note that this allows more than just -1 to be assigned. A purist might want to make his own type that would allow sequences and -1, but not any other atoms to be assigned. There are some other functions (e.g. get_mouse) that will also return a sequence in some cases and an atom in other cases. The results of these functions are typically assigned to object variables. Finally, there can be a very slight performance difference depending on whether you choose object, sequence, atom or integer. Usually a more restrictive type will gain you a tiny bit of speed, but occasionally it can work the opposite way. Regards, Rob Craig Rapid Deployment Software