Polymorphism in Shell
Polymorphism is a very useful programming language feature, so that code can deal with different, but related types of data in uniform manner. In languages like Java or C++, the types must be related vis inheritance or in the case of Java, as interface implementors. In Smalltalk, no such restriction exists. Any class can implement a method of a particular name. The reason I mention Smalltalk is because its semantics most closely resemble the mechanisms used for implementing polymorphism in shell.
Let's dive into the details. In Java or C++, we can use statements of the form:
obj.method(5)and which method is executed depends on which class obj is an instance of. This is called "dispatching on the type of the receiver", as the method chose to execute the "dispatch", is based upon the type of the receiver "obj". In shell, as there are no objects, we have to dispatch on something other than the type of an object. In evaluating an expression i shell, one of the first actions performed is variable expansion. For example, the expression:
rls=ls $rls *.cwill list all the C source files in the current directory. the expansion of the variable rls into ls occurs before the search for the command to be executed. To get useful polymorphism, additional pieces are needed. A setting from a set of values needs to be provided to set the environment variable:
case $REMOTEOS in win32) rls="DIR";; *) rls="ls";; esacwill choose the appropriate command for listing files. Polymorphism is most useful when thare are groupings of functions. Again we use variable expansion to form the complete function name:
function win32_ls()
{
rsh winHost DIR $*
}
function unix_ls()
{
rsh unixHost ls $*
}
function win32_cat()
{
rsh winHost TYPE $*
}
function unix_cat()
{
rsh unixHost cat $*
}
case $REMOTEOS in
win32) rls=win32_ls
rcat=win32_cat
;;
*) rls=unix_ls
rcat=unix_cat
;;
ease
Update: (crutcher)
Alternatively, you could structure the alias construction as something like this:
case $REMOTEOS in
win32)
function rls() { rsh winHost DIR $*; }
function rcat() { rsh winHost TYPE $*; }
;;
*)
function rls() { rsh unixHost ls $*; }
function rcat() { rsh unixHost cat $*; }
;;
esac

0 Comments:
Post a Comment
Links to this post:
Create a Link
<< Home